I do have a Java Web Application. It does use hibernate
for creating, updating, saving the web form data to database. The task is to create a new record in the database within the same table based on previous record. So, what I have now:
The code:
//Function which returns a record from database based on UUID
@Override
public Marriage getMarriageUuId(String uuId) {
Session session = sessionFactory.getCurrentSession();
Criteria criteria = session.createCriteria(Marriage.class);
criteria.add(Restrictions.eq( "uuId", uuId ));
return (Marriage) criteria.uniqueResult();
}
//function which does save new record
@Override
public Integer addMarriage(Marriage marry) {
Session session = sessionFactory.getCurrentSession();
return (Integer) session.save(marry);
}
//the action itself
Marriage newVersion= caseRegisterService.getMarriageUuId(marriage4.getUuId());
newVersion.setVoided(false);
newVersion.setState("3.EDIT");
newVersion.setVersion(oldVersion.getVersion()+1);
newVersion.setUuId(newUuId);
caseRegisterService.addMarriage( newVersion );
I do have UUID
and based on this I get some record from the database and assign it to the corresponding object. It's not set as primary key. The primary key is just an auto increment in postgresql
. The code works but it just keeps updating the current object with the new data. Instead I want to to create the new record in the database with new data, plus previous data. If I create it the very first time, when it doesn't exist in the database, then it creates that object but after it just keeps updating it.
From what I understand the problem is in primary key
. So, when I get back the object from the database it comes back with it's unique primary key
, and as the result hibernate
just updates it. So, how to reset
that primary key
for the new object? So, that hibernate
will think it's new object. I also dont want to manually increase it, it's not the right way.
As I understand, when we have something like this:
// open session, transaction
Marriage newVersion= caseRegisterService.getMarriageUuId(marriage4.getUuId());
newVersion.setVoided(false);
newVersion.setState("3.EDIT");
// close session, transaction
Hibernate will update newVersion
(with old uuId
) cause of a session flush, even if you didn't call update()
method.
So what you can try to do:
Marriage newVersion= caseRegisterService.getMarriageUuId(marriage4.getUuId());
// detach entity from session
session.evict(newVersion);
newVersion.setVoided(false);
newVersion.setState("3.EDIT");
newVersion.setVersion(oldVersion.getVersion()+1);
// reset primary key
newVersion.setId(null);
caseRegisterService.addMarriage( newVersion );
You can use a bit simpler code to load entity:
session.get(Marriage.class, uuId);
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.