Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

In my Java applicaion, I am using hibernate .hbm file to access database; Is this possible to update the primary key 'id' column in the table; Where the 'id' column in my .hbm file is like:

<hibernate-mapping package="org.jems.user.model">
<class name="Student_Details" table="t_student">
<id name="id" type="int" column="id">
<generator class="increment"/>
</id>
<property name="name" column="name" type="string" unique="true" not-null="true" />
<property name="description" column="description" type="string"  />
<property name="comments" column="comments" type="string"  />
<property name="active"     column="isActive"   type="boolean"  not-null="true" />
</class>
</hibernate-mapping>
like image 506
It's me Avatar asked Mar 21 '13 05:03

It's me


Video Answer


2 Answers

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.

like image 32
dcernahoschi Avatar answered Sep 20 '22 10:09

dcernahoschi


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);  
like image 177
lichengwu Avatar answered Sep 18 '22 10:09

lichengwu