Hiyas,
I am having some problems with creating new objects in the db with Hibernate 3.1.3. (I know this version is a little dated but it's what the project is based on.)
I am trying to create new objects in a transactional context. I have the following scenario:
Code:
public boolean startFamily(parentId, Set<Map<String, String>> childrenInfo) {
try {
Session session = getSessionFactory().openSession();
Parent parent = (Parent) session.get(Parent.class, parentId);
return addChildren(session, parent, childrenInfo);
} catch (Exception e) {
e.printStackTrace();
}
return false;
}
private boolean addChildren(Session session, Parent parent, Set<Map<String, String>> childrenInfo) {
try {
tx = session.beginTransaction();
for (Map<String, String> newItem : newItems) {
DatabaseObject dbo = new DatabaseObject();
mapItemToDbo(newItem, dbo);
dbo.setParent(parent);
parent.add(dbo);
//session.save(dbo);
}
tx.commit();
return true;
} catch (Exception e) {
if (tx != null) {
tx.rollback();
}
e.printStackTrace();
}
return false;
}
The problem is that only the first object of the set is getting created. Any additional objects are still showing null IDs and timestamps after the commit takes place (even with a refresh). I have confirmed through the debug logs that only 1 INSERT statement is executed (though I cannot see the values but I know from subsequent db calls that only the 1st child is created).
The "session.save(dbo)" is commented because, per the documentation, i do not think it should be necessary. (As stated above... if children info only has 1 entry... the child is successfully created.)
Quote:
The usage and semantics of saveOrUpdate() seems to be confusing for new users. Firstly, so long as you are
not trying to use instances from one session in another new session, you should not need to use update(), saveOrUpdate(),
or merge(). Some whole applications will never use either of these methods.
However, for arguments sake, I have tried the scenario using the session.save() and the problem is that the items are created instantly without regard for the running transaction and not rolled back if an exception occurs...
Can anyone tell me if there is something I am doing wrong or if this may have been a bug in the version I am using... I have scoured the changelogs for more recent versions of code and don't find anything that seems to be related to this as an issue (google searches have been fruitless as well) so I am thinking this might be a user error. Any help would be appreciated.
Thanks.
Keith
PS.... in case you are wondering... the underlying db implementation is MySQL.