简体   繁体   中英

Get database generated ID after persist in Hibernate

I need to retrieve the ID that a database generates after a persist() . My entity looks like this:

@Entity
@Table(name = "TableName")
public class TableNameClass {

    @Id
    @Generated(GenerationTime.INSERT)
    @Column(name = "ID", insertable = false, nullable = false, unique = true, updatable = false)
private int ID;

    ...
}

However, when executing the next piece of code, the entity is saved in the DB but the result of the System.out.println is 0:

Session s = HibernateUtil.getSessionFactory().openSession();
TableNameClass tnc = new TableNameClass();
tnc.setName("SessionTest4");
Transaction t = s.beginTransaction();
s.save(tnc);
t.commit();
System.out.println(tnc.getID());
s.close();

Could anybody help me, please?

PD: I don't care about using Session or EntityManager, so a solution on any one of them will be fine.

EDIT:

I've tried adding a flush() after the save() method, but still not working:

Session s = HibernateUtil.getSessionFactory().openSession();
AlertType at = new AlertType();
at.setName("SessionTest4");
Transaction t = s.beginTransaction();
s.save(at);
s.flush();
t.commit();        
System.out.println(at.getID());
s.close();

I've also tried adding the flush() function after the commit() , however an Exception is thrown saying that there is no Transaction active.

You need to add a

em.flush();

to force the entity manager to synchronize the data. Then at.getID() will return the value.

Here you have a solution:

ENTITY :

@Entity
@Table(name = "TableName")
public class TableNameClass {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "ID", insertable = false, nullable = false, unique = true, updatable = false)
    private int ID;

    ...
}

CREATE FUNCTION

TableNameClass tnc = new TableNameClass();
tnc.setName("Solution");
Session s = HibernateUtil.getSessionFactory().openSession();
Transaction t = s.beginTransaction();
Integer myID = (Integer)s.save(tnc);
t.commit();
s.close();
System.out.println(myID);

As you can see, I've changed the @Generated annotation for @GeneratedValue(strategy = GenerationType.IDENTITY) . I don't know if both of them represent the same, but it works.

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