首页 > 解决方案 > 休眠持久化正在插入而没有事务提交

问题描述

当此代码运行时

try(Session session = HibernateUtil.getSessionFactory().openSession())
{
   Transaction trans = session.beginTransaction();
   session.persist(venue);

实体被插入而不调用trans.commit();. 日志显示

休眠:插入场地_用户等.....

任何想法为什么会发生这种情况?

我的 HibernateUtil 类

     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(没有实体/个人信息)

<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&amp;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>

标签: javahibernate

解决方案


方法的约定persist是调用方法后必须设置实体的ID。

如果您有,GenerationType.IDENTITY那么唯一可能的解决方案是执行插入语句以从数据库中获取自动增量值。

这就是您看到插入语句的原因。


推荐阅读