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.
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.
No. Hibernate doesn't allow to change the primary key.
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.
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.
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();
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With