【问题标题】:Hibernate session.flush() even though autocommit is set休眠 session.flush() 即使设置了自动提交
【发布时间】:2017-03-11 09:57:02
【问题描述】:

我意识到需要为主键不是 GeneratedValue 的实体调用 session.flush(),然后才能将它们持久化到数据库中。即使我已经将自动提交设置为 true,我也必须这样做。 这是我的休眠配置

<property name="hibernate.dialect">${hibernate.dialect}</property>
<property name="hibernate.connection.driver_class">${hibernate.connection.driver_class}</property>
<property name="hibernate.connection.url">${hibernate.connection.url}</property>
<property name="hibernate.connection.username">${hibernate.connection.username}</property>
<property name="hibernate.connection.password">${hibernate.connection.password}</property>
<property name="connection.autocommit">true</property>

这是一个实体示例,我需要在保存后在代码中调用 session.flush() 之后才能持久化

    @Id
    @Column(name = "MembTypeCode")
    private String memTypeCode;
    @Column(name = "MemberType")
    private String memberType;
  ...

但是对于 Id 为 GeneratedValue 的实体(如下面的实体),我不需要在保存后在代码中调用 session.flush() 以使其持久保存在数据库中,因为我已将自动提交设置为 true .

@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "PrescriptId")
private int prescriptId;
@Column(name = "InvNum")
private Integer invNum;
@Column(name = "DocType")
private String docType;
...

有人可以向我解释为什么我会遇到这种情况吗?我正在使用 Hibernate 4.1.0.FINAL

【问题讨论】:

    标签: java sql-server hibernate session


    【解决方案1】:

    Autocommit 和 session.flush() 是两个不同的东西:

    1. Autocommit 设置底层 JDBC 事务的自动提交模式。这基本上意味着每个 SQL 语句(SELECT、UPDATE、INSERT、DELETE...)都在自己的事务中执行。
    2. session.flush() 告诉 Hibernate 将内存中的状态与数据库同步,以便将 SQL 语句写入 JDBC 连接。在此处查看更多信息:What's the use of session.flush() in Hibernate

    因此,虽然我不知道为什么您的示例中的实体仅在一种情况下被持久化到数据库中,但它可能与自动提交模式无关。

    【讨论】:

      猜你喜欢
      • 2010-11-16
      • 2014-11-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-10-26
      • 2021-12-08
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多