Hibernate不会使用ManyToOne关系保存实体

时间:2013-02-07 18:02:37

标签: java mysql 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;
    }
    ...
}

当我尝试使用AdminLog中的save()方法保存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绝对不是空的!这就像Hibernate无法从userId中的user属性中检索AdminLog。我做错了什么?

2 个答案:

答案 0 :(得分:2)

您正在尝试保存UserMaster的瞬态实例。如果您有一个id的对象,那么您应该先加载它并在保存之前设置为AdminLog对象。

答案 1 :(得分:1)

在坚持UserMaster

之前,您必须坚持AdminLog