views:

35

answers:

1

I want to save some Objects to database with predefined IDs using Hibernate. Is it possible to do it using save method of Hibernate session?

I know there are following workarounds:

1) execute SQL script with necessary insert statements:

insert into MyObj(id,name) values (100,'aaa'), (101,'bbb');

2) use SQL query in Hibernate:

public static boolean createObj(Long id, String name) {
  Session session = HibernateUtil.getSessionFactory().getCurrentSession();
  if (session.get(MyObj.class, id) == null) {        
    session.beginTransaction();
    SQLQuery sqlQuery = session.createSQLQuery
      ("insert into myobj(id,name) values(?,?)");
    sqlQuery.setLong(0, id);
    sqlQuery.setString(1, name);
    sqlQuery.executeUpdate();
    session.getTransaction().commit();
    return true;
  } else {
    return false;
  }
}

But: is it possible to do without SQLQuery?

In Hibernate reference in section 11.2. Making objects persistent there is example of code:

Alternatively, you can assign the identifier using an overloaded version of save().

DomesticCat pk = new DomesticCat();
pk.setColor(Color.TABBY);
pk.setSex('F');
pk.setName("PK");
pk.setKittens( new HashSet() );
pk.addKitten(fritz);
sess.save( pk, new Long(1234) );

But I couldn't find example of how to do this.

So, is it possible to save new objects with supplied IDs to database with Hibernate not using SQL query? If yes then how? And how to overload session method save() as mentioned in Hibernate reference?

Thanks!

+3  A: 

The documentation asks you not to override save yourself, but to use the variant of save which takes two arguments. See the [JavaDocs][1] for more details.

YourEntity entity = // ..
entity.setFoo(foo);
entity.setBar(bar);
//..
session.save(entity, theIDYouWantToUse);

[1]: http://docs.jboss.org/hibernate/core/3.6/javadocs/org/hibernate/Session.html#save(java.lang.String, java.lang.Object)

binil
Don't forget not to use ID generators when using two-arguments `save`
denis_k
Eh, the right link is: http://docs.jboss.org/hibernate/core/3.6/javadocs/org/hibernate/classic/Session.html#save(java.lang.Object, java.io.Serializable)
IvanR