@Transactional 服务

@Transactional in Service

我已经创建了一个投票应用程序并且我有改变投票数的方法。它实现了一个带有@Transactional 注释的接口。

@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);
}

我用的是SpringBoot。 它能在同时给多个用户投票时正常工作吗?您如何测试这样的操作?

顺序投票工作正常。

更改声音数量的代码如下:

    @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 +
                '}';
    }
}

谢谢!

  • VotingService是一个接口。
  • 实施class VotingServiceImpl在spring中默认是单例class。这是 线程间共享。
  • 它不应该有实例变量 持有投票资料。

您可以使用postman或jmeter执行并行请求来验证服务的正确性