java - 休眠持久化正在插入而没有事务提交
问题描述
当此代码运行时
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&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>
解决方案
方法的约定persist
是调用方法后必须设置实体的ID。
如果您有,GenerationType.IDENTITY
那么唯一可能的解决方案是执行插入语句以从数据库中获取自动增量值。
这就是您看到插入语句的原因。
推荐阅读
- sas - 用于值比较的 Proc freq
- sql - 使用 spark sql 进行数据分发
- ruby-on-rails - 上传到 Azure 时,Rails wicked_pdf 页眉、页脚和 html 不显示
- php - 在 Drupal 中隐藏选择
- python - 如何使用 git 在 pip install 中处理 @?
- c - 解析 C X-宏表
- flutter - 在graphql颤振中接收订阅结果后如何更新查询
- r - 图层创建失败 rgdal macOS R
- apache-kafka - 如何使用 java 代码重置 kafka 流应用程序?
- javascript - 使用 selenium 和 Nodejs 在自动化测试中查找元素的最佳方法?