Get database generated ID after persist in Hibernate
<p>I need to retrieve the ID that a database generates after a <code>persist()</code>. My entity looks like this:</p>

<pre><code>@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;

    ...
}
</code></pre>

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

<pre><code>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();
</code></pre>

<p>Could anybody help me, please?</p>

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

<p><strong>EDIT:</strong></p>

<p>I've tried adding a <code>flush()</code> after the <code>save()</code> method, but still not working:</p>

<pre><code>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();
</code></pre>

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