简体   繁体   中英

what is difference between “update” method of Session class and “executeupdate” method of Query class in hibernate, when which method use?

Session类的“update”方法与hibernate中Query类的“executeupdate”方法有什么区别,哪种方法使用?

The two methods work at a different level of abstraction:

  • update Basically takes it's parameter entity, finds a row in it's table with the same primary key and issues an UPDATE so that after you commit your transaction, the row has all the information your parameter object had. In addition, the update is cascaded to all dependent objects if they were annotated/marked with cascade = save-update .

  • executeUpdate will parse the query you created (which should be an UPDATE or DELETE statement) and issues it to the database. No cascading or other logic is executed.

When to use which depends on your needs, as bellabax said: executeUpdate is useful for updating a specific table and several rows, but I prefer the simplicity of update if I don't work with severe time constraints (issuing several database UPDATE s will be slower).

In short: Session.update() is used to update a single mapped entity; with Query.executeupdate() you can perform custom delete/update statement (written is HQL or pure SQL) and get as result the updated/deleted entities count.
Which is the right method depends which is your need: with executeupdate() you can delete/update an arbitrary number of objects based on a query, with update() you can only update one single object at time.

executeUpdate allows you to run a native SQL query which can be not supported by Hibernate. For example, you need to update with certain conditions.

Using executeUpdate is more powerful but do not use it within a Hibernate transaction. Give a method as below:

    @@Transactional(readOnly = false)
public void updateLastActivity(VaultUserImpl user, Date lastActivity) {
    Query query = getCurrentSession().createQuery("UPDATE VaultUserImpl user set user.lastActivity=:lastActivity where user.id=:id");
    query.setDate("lastActivity", lastActivity);
    query.setLong("id", user.getId());
    query.executeUpdate();

    user.setLastActivity(lastActivity);
}

By default, Hibernate will call update method automatically within a transaction annotation. That means the query above is not only necessary but dangereux because we lost data.

In fact, query.setDate(Date datetime) does not return full date+time value but date only.

The code above can be write shortly:

    @@Transactional(readOnly = false)
public void updateLastActivity(VaultUserImpl user, Date lastActivity) {
    user.setLastActivity(lastActivity);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM