【问题标题】:Use non-commited values in SQL query在 SQL 查询中使用未提交的值
【发布时间】:2014-09-19 21:37:13
【问题描述】:

在某些功能(此处简化)中,我有这样的东西:

public void transfertOrganisms(Organism firstOrganism, Organism secondOrganism){

  firstOrganism.setMetaExercice(DaoHelper.getMaxMetaExercieId("organisme") + 1);
  HibernateUtil.getCurrentSession().saveOrUpdate(firstOrganism);

  secondOrganism.setMetaExercice(DaoHelper.getMaxMetaExercieId("organisme") + 1);
  HibernateUtil.getCurrentSession().saveOrUpdate(secondOrganism);
}

在 DaoHelper.java 中

public static int getMaxMetaExercieId(String tableName) {
    Query query;
    Session session = HibernateUtil.getSessionFactory().openSession();
    Transaction tx = session.beginTransaction();
    query = session.createSQLQuery("SELECT MAX(META_EXERCICE_ID) FROM " + tableName);
    Integer max = (Integer) query.uniqueResult();
    tx.commit();
    if (max == null)
      return 0;
    return max;
}

现在,由于事务尚未提交,DaoHelper.getMaxMetaExercieId("organisme") 将始终返回相同的值。无需自己管理 currentMax(例如制作全局变量或其他东西),有没有办法使用表的未提交值?

【问题讨论】:

    标签: java hibernate transactions commit


    【解决方案1】:

    不幸的是,如果更新 Organism 表的其他事务可以同时执行(例如,如果应用程序的其他用户正在创建 Organism 行同时)。我为此使用了两种解决方案:使用“自动递增”列(MySQL 和 MSSQL 中的auto_increment);或者创建一个保存最大值的表,并在单独的事务中更新该表中的值。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-07-06
      • 1970-01-01
      • 1970-01-01
      • 2013-01-05
      • 2018-02-10
      • 2023-02-25
      相关资源
      最近更新 更多