Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Persisting an object in Hibernate while having a known primary key.

My problem is with detached objects...

I am currently using Spring with Hibernate.

I have a mapped object that has a primary key as a String (I know it sucks... but refactoring the code would take months), and I wish to persist it. (I have simplified the object with just two attributes)

@Id
private String id;

private String pattern;

So for example I want to add something like:

["id":"myFirstPattern","pattern":".*"]

Notice that my primary key is already set. The problem with that is that whenever I try to persist, Hibernate will try to link this object with any object within the context (because of the primary key) and will fail to do so, since there are none. Throwing a detached object error.

I've done some research and came to the conclusion that merge() would suffice my needs, since it persists and updates even if the object is not available. However I found this a rather dirty workaround and wanted to check if there are any other solutions to this problem.

Take into account that we have a Helper layer, so Services layer will not work directly with the HibernateDao layer. So I can "mask" this by adding 'persist' and 'update' methods that will invoke the same merge DAO method.

Thanks, Flavio.

like image 573
flavio_yama Avatar asked Jul 28 '11 13:07

flavio_yama


People also ask

How do you persist objects in Hibernate?

All classes should contain an ID in order to allow easy identification of your objects within Hibernate and the database. This property maps to the primary key column of a database table. All attributes that will be persisted should be declared private and have getXXX and setXXX methods defined in the JavaBean style.

Can we update primary key in Hibernate?

No. Hibernate doesn't allow to change the primary key.

Which annotation is used to mark a column as a primary key while doing Hibernate mapping?

Join the Persistence Hub! Mapping a primary key column with JPA and Hibernate is simple. You just need to add an attribute to your entity, make sure that its type and name match the database column, annotate it with @Column and you're done.

Does Hibernate require primary key?

Hibernate requires that entity tables have primary keys. End of story. 50k records is simply not that many when you're talking about a database.


1 Answers

Have you tried saveOrUpdate?

Session sess = factory.openSession();
Transaction tx;
try {
    tx = sess.beginTransaction();
    session.saveOrUpdate( yourObjectHere );

    tx.commit();
}
catch (Exception e) {
    if (tx!=null) tx.rollback();
    throw e;
}
finally {
    sess.close();
}
like image 108
Maurício Linhares Avatar answered Sep 24 '22 14:09

Maurício Linhares