4
這裏是我的表:Hibernate不會保存實體與多對一關係
CREATE TABLE `admin_log` (
`LOG_ID` bigint(20) NOT NULL AUTO_INCREMENT,
`USER_ID` bigint(20) NOT NULL,
`CREATION_DATE` timestamp NOT NULL DEFAULT '0000-00-00 00:00:00',
`ACTION` varchar(100) NOT NULL,
`DETAILS` varchar(100) DEFAULT NULL,
PRIMARY KEY (`LOG_ID`),
KEY `ADMIN_LOG_FK1` (`USER_ID`),
CONSTRAINT `ADMIN_LOG_FK1` FOREIGN KEY (`USER_ID`) REFERENCES `user_master` (`USER_ID`)
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8
這裏是我的實體:
@Entity
@Table (name = "admin_log")
public class AdminLog {
private Long logId;
private UserMaster user;
...
@Id
@GeneratedValue (strategy = IDENTITY)
@Column (name = "LOG_ID", unique = true, nullable = false, length = 20)
public Long getLogId() {
return logId;
}
public void setLogId (Long logId) {
this.logId = logId;
}
@ManyToOne
@JoinColumn (name = "USER_ID")
public UserMaster getUser() {
return user;
}
public void setUser (UserMaster user) {
this.user = user;
}
...
}
@Entity
@Table (name = "user_master")
public class UserMaster {
private Long userId;
...
@Id
@GeneratedValue (strategy = IDENTITY)
@Column (name = "USER_ID", unique = true, nullable = false, length = 20)
public Long getUserId() {
return this.userId;
}
public void setUserId (Long userId) {
this.userId = userId;
}
...
}
當我嘗試使用save()
方法保存AdminLog
從HibernateTemplate
我得到以下錯誤:
SEVERE: Column 'USER_ID' cannot be null
org.springframework.dao.DataIntegrityViolationException: could not insert [...AdminLog];
SQL [insert into admin_log (ACTION, CREATION_DATE, DETAILS, USER_ID) values (?, ?, ?, ?)];
constraint [null] nested exception is org.hibernate.exception.ConstraintViolationException: could not insert: [...AdminLog]
問題是,userId
絕對不是null!這就像Hibernate無法從user
中檢索中的屬性。我究竟做錯了什麼?
在保存管理日誌之前您的用戶是否持續存在? – Perception
使用@ManyToOne(.. cascade = {CascadeType.PERSIST,CascadeType.MERGE})如果你想在一次調用中同時存在。 – twillouer
您可以在AdminLog中設置用戶屬性的位置顯示測試或示例代碼嗎?你說UserMaster有一個id,這是因爲你是否將UserMaster從休眠狀態中拉出來了? –