Hibernate - update the primary key 'id' column in the table

允我心安 提交于 2019-12-01 18:01:31

try this:

String hql="update table set id=? where id=? ";
Query query=HibernateSessionFactory.getSession().createQuery(hql);
query.setInteger(0,1);
query.setInteger(1,2);
query.executeUpdate();
HibernateSessionFactory.getSession().beginTransaction().commit();

or just use sql:

String sql = "update table set id = ? where id= ?"
Session session = HibernateSessionFactory.getSession();  
SQLQuery query = session.createSQLQuery(sql);
query.setParameter(0, 1);
query.setParameter(1, 2);  

No. Hibernate doesn't allow to change the primary key. In general, a primary key value should never change, if needs to be changed than the primary key column(s) are not good candidate(s) for a primary key.

There is a workaround if you prefer to update via entity instead of query:

1) clone the entity to a new entity.
2) delete the old entity. (be careful of your cascade children entities)
3) change the primary key of new entity (or set it null depend your generation strategy).
4) save the new entity.

In hibernate id column values are automatically incremented while session.save() is executed based on which generation strategy you use. Check this post for a simple example

try to writing query like

update table_name set id=value where...............(specify remaining conditions)

Basically, Hibernate does not allow to update or change the primary key of a database entity. The reason is the entity data that you fetch from database via some query or .get or .load method goes into persistent context layer. So from hibernate perspective updating of such persistent entity object means deletion of the older one from database and creation of a new one.
It better to make normal update query like

Query query=HibernateSessionFactory.getSession().createQuery(update table set id=? where id=?);
query.executeUpdate();
HibernateSessionFactory.getSession().beginTransaction().commit();
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!