I want to store some objects in a database with predefined identifiers using Hibernate. Can this be done using the Hibernate session persistence method?
I know that the following workarounds exist:
1) execute the SQL script with the necessary insert statements:
insert into MyObj(id,name) values (100,'aaa'), (101,'bbb');
2) use the 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 the Hibernate link in section 11.2. Constantly saving objects , there is an example code:
Alternatively, you can assign an identifier using the 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 could not find an example of how to do this.
So, is it possible to save new objects with provided identifiers to the database using Hibernate without using an SQL query? If so, how? And how to overload the session save () method as specified in Hibernate?
Thanks!
java hibernate session
iryndin
source share