Issue
When this code runs
try(Session session = HibernateUtil.getSessionFactory().openSession())
{
Transaction trans = session.beginTransaction();
session.persist(venue);
the entity is inserted without calling trans.commit();
. The logs show
Hibernate: insert into venue_users etc.....
Any ideas why this is happening?
My HibernateUtil class
private static StandardServiceRegistry registry;
private static SessionFactory sessionFactory;
public static SessionFactory getSessionFactory() {
if (sessionFactory == null) {
try {
// Create registry
registry = new StandardServiceRegistryBuilder().configure().build();
// Create MetadataSources
MetadataSources sources = new MetadataSources(registry);
// Create Metadata
Metadata metadata = sources.getMetadataBuilder().build();
// Create SessionFactory
sessionFactory = metadata.getSessionFactoryBuilder().build();
} catch (Exception e) {
e.printStackTrace();
if (registry != null) {
StandardServiceRegistryBuilder.destroy(registry);
}
}
}
return sessionFactory;
}
public static void shutdown() {
if (registry != null) {
StandardServiceRegistryBuilder.destroy(registry);
}
}
Hibernate.cfg (without entities/personal info)
<hibernate-configuration>
<session-factory>
<property name="hibernate.connection.driver_class">com.mysql.cj.jdbc.Driver</property>
<property name="hibernate.connection.url">jdbc:mysql://localhost:3306/sof?serverTimezone=UTC&useLegacyDatetimeCode=false;</property>
<property name="hibernate.connection.password">root</property>
<property name="hibernate.connection.username">root</property>
<property name="hibernate.dialect">org.hibernate.dialect.MySQL5Dialect</property>
<property name="show_sql">true</property>
<property name="hbm2ddl.auto">update</property>
</session-factory>
Solution
The contract of the method persist
is that after calling the method the ID of the entity must be set.
If you have GenerationType.IDENTITY
then the only possible solution is to execute the insert statement to get the auto increment value from the database.
That's why you see the insert statement.
Answered By - Simon Martinelli