Hibernate Many To One在没有被要求时总是级联

时间:2014-12-07 19:00:43

标签: java hibernate jpa many-to-one

说我有一个User表和一个UserRecordInfo表,它保存了更改用户信息所采取的操作。例如:

用户:

|用户ID |用户名|

| 1 |测试|

和UserRecordInfo:

| UserRecordInfoID |用户ID |行动| oldValue | newValue |

| 1 | 1 |更新名称| oldTest | test2 |

| 2 | 1 |更新名称| test2 |测试|

显然在Java中,在设计Objects时,我不想在User中有UserRecordInfo字段,因为每个用户可能有数百个UserRecordInfo。我所拥有的是:

@Entity
@Table(name="User")
public class User {
private userName;
@Column(name = "userName")
    public String getUserName() {
        System.out.println("getting username");
        return userName;
    }
...
}

@Entity
@Table(name="UserRecordInfo")
public class UserRecordInfo {
    private User user;

    @JoinColumn(name = "UserID")  // using javax.persistence.JoinColumn
    @ManyToOne(fetch = FetchType.LAZY) // using javax.persistence.ManyToOne
    public User getUser() {
        return user;
    }
    public void setUser(User user) {
        this.user = user;
    }

}

我创建新的UserRecordInfo的方式是:

User u = {get user from hibernate}
UserRecordInfo record = new UserRecordInfo();
record.setUser(u);
 .setNewName("test1");
...

Session session = DBSessionHandler.getSession();
    Transaction tx = null;
    try {
        tx = session.beginTransaction();
        Serializable result = session.save(record);
        tx.commit();
        return result;
    }
    catch (HibernateException ex) {
        ex.printStackTrace(); 
        if (tx!=null) tx.rollback();
        throw ex;
    }
    finally {
        DBSessionHandler.close();
    }

但是,无论何时插入新的UserRecordInfo,用户对象总是被触摸(println始终打印“获取用户名”)。为什么会这样?我做错了什么?

1 个答案:

答案 0 :(得分:1)

尝试将" updatable = false' @JoinColumn注释中的属性。

您可能希望将抓取类型标记为' Eager'用于@ManyToOne注释。

另外,我建议你注释字段而不是getters。

UserRecordInfo类看起来像:

@Entity
@Table(name="UserRecordInfo")
public class UserRecordInfo {

    @ManyToOne(optional = false, fetch = FetchType.EAGER)
    @JoinColumn(name = "UserID", nullable = false, updatable = false)
    @NotNull
    private User user;

    public User getUser() {
        return user;
    }
    public void setUser(User user) {
        this.user = user;
    }
}

Doc for"可更新'读作:

  

(可选)列是否包含在SQL UPDATE语句中   由持久性提供程序生成。

似乎是你要解决的案例