简体   繁体   中英

Save new object with Hibernate using supplied ID

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!

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)

Use session.replicate

YourEntity entity = // ..
entity.setId(yourId);
entity.setBar(bar);
//..
session.replicate(entity,ReplicationMode.EXCEPTION);

Specify assigned as the generator on the ID column.

http://docs.jboss.org/hibernate/orm/3.3/reference/en/html/mapping.html#mapping-declaration-id-generator

Note that for this to perform well, it helps to have a nullable version property . Hibernate then treats 'null' version values as being unsaved.

<id name="id" type="int">
    <generator class="assigned" />
</id>
<version name="version" type="int">

public class Person {
    // ID;    assigned, SPEC.
    public int getId();
    public void setId (int id);
    // Version;  NOTE -- must be nullable!
    public Integer getVersion();
    public void setVersion (Integer version);
}

Hope this helps.

Use save method of hibernate:- save(String entityName,Object object) For more information kindly follow:- http://docs.jboss.org/hibernate/core/3.6/javadocs/org/hibernate/Session.html#save(java.lang.String , java.lang.Object)

Note:- Do not use GeneratedValue of any type on above of your Primary key @GeneratedValue(strategy=GenerationType.IDENTITY)

For now replicate(Object object, ReplicationMode replicationMode) seems to be an acceptable and the preferred way. You may want to play a little with the different values for ReplicationMode to suit your needs.

You can write your own ID generator, that defers to a Hibernate generator when you don't have an ID set.

    <id column="MyEntity" name="id" type="long">
        <generator class="com.me.MySequenceStyleGenerator">
            <param name="sequence_name">MY_SEQUENCE</param>
            <param name="increment_size">1000</param>
            <param name="optimizer">pooled</param>
        </generator>
        ...

public class MySequenceStyleGenerator extends org.hibernate.id.enhanced.SequenceStyleGenerator {

public Serializable generate(SessionImplementor session, Object entity) throws HibernateException {
    if (entity instanceof MyEntity) {
        MyEntity myEntity = (MyEntity) entity;
        if (myEntity.isUseMyId()) {  // this is a transient field
            return myEntity.getId(); // this is an id you generated
        }
    }
    return super.generate(session, entity);
}

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM