Save new object with Hibernate using supplied ID

20,551

Solution 1

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)

Solution 2

Use session.replicate

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

Solution 3

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)

Solution 4

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.

Share:
20,551
iryndin
Author by

iryndin

Making software development mostly in Java stack. I specialise mostly in backends in cloud-based or premise-based environments.

Updated on January 22, 2020

Comments

  • iryndin
    iryndin over 4 years

    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!

  • Denys Kniazhev-Support Ukraine
    Denys Kniazhev-Support Ukraine over 13 years
    Don't forget not to use ID generators when using two-arguments save
  • iryndin
    iryndin over 13 years
    Eh, the right link is: docs.jboss.org/hibernate/core/3.6/javadocs/org/hibernate/…, java.io.Serializable)
  • Nyerguds
    Nyerguds over 8 years
    The only variant of Save() using two args takes a string and then the object itself... not a key.
  • Binil Thomas
    Binil Thomas over 8 years
    @Nyerguds in 3.6 JavaDocs, I still see the method mentioned above: red.ht/1hHZwLT
  • Nyerguds
    Nyerguds over 8 years
    Yes, but it's an interface, in a separate namespace (namely, org.hibernate.classic). Not sure how that can ever be useful, since it's simply not there in the session object I get..
  • teknopaul
    teknopaul almost 2 years
    I get null Id exceptions even when Id is non null, Hibernate 3.3.2. save(o, id) is hibernate 2 and deprecated