Hibernate version:
Mapping documents:
Hello.
My question relates to one
posted by hsivonen - I need to change the primary key (assigned id) of an entity. I know that Hibernate doesn't support this and that it's not recommended practice, but it's a requirement of a specific project that have to be met.
I have added cascade statements (so that changes would cascade to foreign keys as well) into hibernate-generated SQL schema by hand and exported the schema into database. Also because I cannot use session.createSQLQuery() to execute update query because of Hibernate restrictions. I'm using raw JDBC statement to do the job:
Code:
currentHibernateSession.flush();
Connection jdbcConnection = currentHibernateSession.connection();
jdbcConnection.setAutoCommit(true);
// 'email' is the primary key and it's mapped as assigned id property in Hibernate mapping
PreparedStatement updatePersonStmt = jdbcConnection.prepareStatement("UPDATE person SET email = ? WHERE email = ?");
updatePersonStmt.setString(1, newKey);
updatePersonStmt.setString(2, oldKey);
updatePersonStmt.execute();
currentHibernateSession.clear();
So basic idea is to flush all changes from session cache into DB, then execute some raw SQL which will trigger cascading updates in the DB and then clear session cache so Hibernate would reload all entities from DB in the future and catch the changed id ('email' in this example).
Now I don't know if this is a "legal" way to do what I need to be done, but it works in most of my cases. However, today I had a problem with this approach: I got "collection was evicted" HibernateException when I tried to load a collection (of type 'set') after clearing the session. The exception was thrown when I tried to iterate through that collection. Part of the mapping XML:
Code:
<class name="xxx.model.Person" table="Person">
<id name="email" column="email" type="string">
<generator class="assigned"/>
</id>
<set name="favoritePersons" table="PersonFavorites">
<key column="owner"/>
<many-to-many column="favorite" class="xxx.model.Person"/>
</set>
</class>
The code is just a basic iteration:
Code:
Set favs = person.getFavoritePersons();
for (Iterator iter = objs.iterator(); iter.hasNext();) {
Person per = (Person) iter.next();
// do stuff
}
Maybe I don't understand the difference between terms "evicted" and "not cached" (I understand them as synonyms). Can anyone give any recommendations how that exception can be avoided?
I've tried adding cascade="all-delete-orphan" as attribute of the favoritePersons set in Hibernate mapping (without any success). I've also tried emptying the second-level cache (I'm using EHCache) by evicting all collections and entities, but that caused "unknown entity" exceptions. So the main question is: how can I tell Hibernate to just reload all entities and collections from the database next time they're requested. Clearing the session cache apparently isn't enough.