在数据库中插入期间出现 OptimisticLockException org.hibernate.exception.LockAcquisitionException

发布于 2025-01-09 05:45:11 字数 1558 浏览 0 评论 0原文

我正在尝试构建一个订餐系统,其逻辑如下:

  1. 选择查询来检查用户是否已经订餐,
  2. 如果选择查询返回0则插入表中

我只有一张表meal_booking< /code>,用于存储订餐状态详细信息。

这在正常情况下工作得很好。但是每当系统有负载时,我就会得到 OptimisticLockException org.hibernate.exception.LockAcquisitionException

我正在使用 Spring Boot 和 Hibernate JPA。

我的 DAO 层代码:

@Repository
@Transactional
public class MealBookingDAO {

private EntityManager entityManager;

@Autowired
public MealBookingDAO(EntityManager theEntityManager) {
    entityManager = theEntityManager;
}

public Object bookMeal(Map < String, Object > payload) {

    Session currentSession = entityManager.unwrap(Session.class);

    try {
        String countQuery = "select count(sm.id) as count from meal_booking where meal_id = " + payload.get("mealId");

        NativeQuery countQuery = currentSession.createNativeQuery(countQueryString);

        List < Object > countResult = countQuery.getResultList();

        StringBuilder msg = new StringBuilder();

        BigInteger data = (BigInteger) countResult.get(0);

        if (data.intValue() == 0) {

            String insertQueryString = "insert into meal_booking(`user_id`, `meal_id`, `status`) values (?,?,?)";

            int inserted = entityManager.createNativeQuery(insertQueryString).setParameter(1, payload.get("userId"))
                .setParameter(2, payload.get("mealId")).setParameter(3, payload.get("status")).executeUpdate();
        }
     } catch (Exception e) {
            e.printStacktrace();
        }

    }

}

I am trying to build a meal booking system, where the logic is as follows:

  1. select query to check if the user has already booked a meal,
  2. if select query returns 0 then insert into the table

I have only one table meal_booking, which is used for storing the meal booking status details.

This works fine in normal cases. But whenever there is a load on the system, I am getting
OptimisticLockException org.hibernate.exception.LockAcquisitionException

I am using Spring Boot and Hibernate JPA.

My DAO Layer Code:

@Repository
@Transactional
public class MealBookingDAO {

private EntityManager entityManager;

@Autowired
public MealBookingDAO(EntityManager theEntityManager) {
    entityManager = theEntityManager;
}

public Object bookMeal(Map < String, Object > payload) {

    Session currentSession = entityManager.unwrap(Session.class);

    try {
        String countQuery = "select count(sm.id) as count from meal_booking where meal_id = " + payload.get("mealId");

        NativeQuery countQuery = currentSession.createNativeQuery(countQueryString);

        List < Object > countResult = countQuery.getResultList();

        StringBuilder msg = new StringBuilder();

        BigInteger data = (BigInteger) countResult.get(0);

        if (data.intValue() == 0) {

            String insertQueryString = "insert into meal_booking(`user_id`, `meal_id`, `status`) values (?,?,?)";

            int inserted = entityManager.createNativeQuery(insertQueryString).setParameter(1, payload.get("userId"))
                .setParameter(2, payload.get("mealId")).setParameter(3, payload.get("status")).executeUpdate();
        }
     } catch (Exception e) {
            e.printStacktrace();
        }

    }

}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

倒数 2025-01-16 05:45:11

在您的查询中,您可以添加额外的提示来锁定行并防止其他人更新它。

    this.setLockMode(lockMode ?: LockModeType.PESSIMISTIC_WRITE)
    .setHint("javax.persistence.lock.timeout", duration ?: LockOptions.WAIT_FOREVER)
    .setHint("javax.persistence.lock.scope", scope ?: PessimisticLockScope.NORMAL)

请务必查看:
悲观锁定

On your query you can add additional hints to lock a row and prevent others from updating it.

    this.setLockMode(lockMode ?: LockModeType.PESSIMISTIC_WRITE)
    .setHint("javax.persistence.lock.timeout", duration ?: LockOptions.WAIT_FOREVER)
    .setHint("javax.persistence.lock.scope", scope ?: PessimisticLockScope.NORMAL)

Be sure to check out:
Pessimistic locking

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文