【问题标题】:Hibernate is not updating a database recordHibernate 没有更新数据库记录
【发布时间】:2018-02-04 21:19:49
【问题描述】:

我正在尝试使用 Hibernate 从数据库中更新现有对象。

我运行代码,它没有给我任何错误,但它也没有更新数据库。我搜索了问题,但我看不到我的错误在哪里。

这是我在userDAO 类中的函数:

public void updateYear(int id, int year) {
            try {

                Configuration configuration = new Configuration().configure();
                SessionFactory sessionFactory = configuration.buildSessionFactory();
                Session session = sessionFactory.openSession();
                Transaction transaction = null;
                transaction = session.beginTransaction();


            String hql = "UPDATE User u set u.year= :year WHERE u.id= :id";
            Query query=session.createQuery(hql).setParameter("year", year).setParameter("id", id);
            int result = query.executeUpdate();
            System.out.println("Rows affected: " + result+"!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!");


            transaction.commit();
             session.close();

            } catch (HibernateException e) {
                System.out.println(e.getMessage());
                System.out.println("error");
            }

        }

这就是我的称呼:

UserDAO u = new UserDAO();
        u.updateYear(1,6);

结果是这样的:

aa DEBUG org.hibernate.hql.internal.ast.ErrorCounter: throwQueryException() : no errors
aa DEBUG org.hibernate.hql.internal.ast.ErrorCounter: throwQueryException() : no errors
aa DEBUG org.hibernate.SQL: 
    update
        user 
    set
        year=? 
    where
        id=?
Hibernate: 
    update
        user 
    set
        year=? 
    where
        id=?

有时,我会收到此错误,但不是完全在运行后,我觉得很奇怪:

aa DEBUG org.hibernate.engine.jdbc.spi.SqlExceptionHelper: could not execute statement [n/a]
java.sql.SQLException: Lock wait timeout exceeded; try restarting transaction
    at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:1073)
    at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:4096)
    at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:4028)
    at com.mysql.jdbc.MysqlIO.sendCommand(MysqlIO.java:2490)
    at com.mysql.jdbc.MysqlIO.sqlQueryDirect(MysqlIO.java:2651)
    at com.mysql.jdbc.ConnectionImpl.execSQL(ConnectionImpl.java:2683)
    at com.mysql.jdbc.PreparedStatement.executeInternal(PreparedStatement.java:2144)
    at com.mysql.jdbc.PreparedStatement.executeUpdate(PreparedStatement.java:2444)
    at com.mysql.jdbc.PreparedStatement.executeUpdate(PreparedStatement.java:2362)
    at com.mysql.jdbc.PreparedStatement.executeUpdate(PreparedStatement.java:2347)
    at org.hibernate.engine.jdbc.internal.ResultSetReturnImpl.executeUpdate(ResultSetReturnImpl.java:205)
    at org.hibernate.hql.internal.ast.exec.BasicExecutor.doExecute(BasicExecutor.java:90)
    at org.hibernate.hql.internal.ast.exec.BasicExecutor.execute(BasicExecutor.java:59)
    at org.hibernate.hql.internal.ast.QueryTranslatorImpl.executeUpdate(QueryTranslatorImpl.java:437)
    at org.hibernate.engine.query.spi.HQLQueryPlan.performExecuteUpdate(HQLQueryPlan.java:374)
    at org.hibernate.internal.SessionImpl.executeUpdate(SessionImpl.java:1510)
    at org.hibernate.query.internal.AbstractProducedQuery.doExecuteUpdate(AbstractProducedQuery.java:1526)
    at org.hibernate.query.internal.AbstractProducedQuery.executeUpdate(AbstractProducedQuery.java:1504)
    at dao.UserDAO.updateYear(UserDAO.java:160)
    at Main.main(Main.java:52)

如果你需要,这是我的休眠配置文件:

<hibernate-configuration>
    <session-factory>
        <property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
        <property name="hibernate.connection.url">jdbc:mysql://localhost:3306/licenta</property>
        <property name="hibernate.connection.username">root</property>
        <property name="hibernate.connection.password">root</property>
        <property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
        <property name="show_sql">true</property>
        <property name="format_sql">true</property>
        <property name="hbm2ddl.auto">validate</property>
        <property name="hibernate.show_sql">true</property>

        <mapping resource="user.hbm.xml"/>
        <mapping resource="chapter.hbm.xml"/>
        <mapping resource="comments.hbm.xml"/>
        <mapping resource="problems.hbm.xml"/>
        <mapping resource="questions.hbm.xml"/>

    </session-factory>
</hibernate-configuration>

我提到其他操作,如插入或读取用户,它工作正常。

那么,关于如何进行此更新的任何想法?

【问题讨论】:

  • 你有用户 POJO 吗?如果是这样,我认为 Hibernate 找不到与您的条件 (id=1) 匹配的用户实例,因此不会更新任何内容。通常您可以使用 Session.get(User.class, id) 来检索 User 实例并直接更新该实例 (Session.update(user) )

标签: java mysql hibernate sql-update deadlock


【解决方案1】:

你在这里做错了很多事情:

  1. 为什么每次需要调用updateYear 时都创建SessionFactorySessionFactory is an expensive object which should be created during application bootstrap and reused afterward. Use Spring or Java EE for that and inject the SesisonFactory` 作为依赖项。

  2. 如果抛出异常,您永远不会调用transaction.rollback(),因此可以保留锁定直到默认事务超时。

  3. 另外,session.close() 应该在 finally 块中调用。在High-Performance Java Persistence GitHub repository 上查看此模板方法。

  4. 为什么在使用 Hibernate 时要手动调用UPDATE?你应该这样做:

     User user = session.get(User.class, id);
     user.setYear(year);
    

    脏检查机制将为您处理更新,因此无需为托管实体调用 saveOrUpdateupdatemerge

  5. 正如您从日志中看到的那样,发出了UPDATE,但您得到了java.sql.SQLException: Lock wait timeout exceeded; try restarting transaction,因为并发事务已经获得了对该特定记录或包括该记录在内的一系列记录的锁定。如果是这种情况,您只需要在死锁时重试您的事务。您甚至可以使用自动重试机制。

【讨论】:

  • 非常感谢所有这些解释。无论如何,我让代码在没有这些的情况下工作,但这远非一个好的实现。我真的会阅读您建议我的所有内容并相应地进行更改。谢谢!
猜你喜欢
  • 1970-01-01
  • 2016-01-15
  • 1970-01-01
  • 2013-03-06
  • 2018-06-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-04-07
相关资源
最近更新 更多