Reputation: 183
I have created a voting application and I have method that changes the number of votes. It implements an interface with @Transactional annotation.
@Transactional(readOnly = true)
public interface VotingService {
Vote getByRestaurantId(int restaurantId);
Vote get(int id);
List<Vote> getWithRestaurantsByDate(LocalDateTime date);
List<Vote> getWithRestaurantsToday(HttpServletResponse response, int id);
@Transactional
Vote voteFor(int restaurantId, int userId);
}
I use SpringBoot. Will it work correctly while simultaneously voting several users. And how can you test such an action?
The sequential voting is working properly.
Code for changes the number of voices like this:
@Service
public class VotingServiceImpl implements VotingService {
...
@Override
public Vote voteFor(int restaurantId, int userId) {
...
Vote vote = getByRestaurantId(restaurantId);
vote.setNumberOfVotes(vote.getNumberOfVotes() + 1)
...
return vote;
...
}
...
}
@Entity
@Table(name = "votes", uniqueConstraints = {@UniqueConstraint(columnNames = {"restaurant_id", "date", "votes"}, name = "votes_unique_restaurant_date_votes_idx")})
public class Vote extends AbstractEntity {
@Column(name = "votes")
private int numberOfVotes;
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "restaurant_id", nullable = false)
@NotNull
private Restaurant restaurant;
public int getNumberOfVotes() {
return numberOfVotes;
}
public void setNumberOfVotes(int numberOfVotes) {
this.numberOfVotes = numberOfVotes;
}
public Vote() {
}
public Restaurant getRestaurant() {
return restaurant;
}
public void setRestaurant(Restaurant restaurant) {
this.restaurant = restaurant;
}
@Override
public String toString() {
return "Vote{" +
super.toString() +
"numberOfVotes=" + numberOfVotes +
", restaurant=" + restaurant +
'}';
}
}
Thanks!
Upvotes: 0
Views: 82
Reputation: 582
VotingService
is an interface. VotingServiceImpl
is singleton class by default in spring. It is
shared between threads. You can verify the correctness of the service by executing parallel request using postman or jmeter
Upvotes: 1