我有 @Embeddable 类 AuditColumn.java ,如下所示。
public class AuditColumn {
@Column( name = "create_user", nullable = false )
private String createUser = null ;
@Column( name = "create_date", nullable = false , columnDefinition = "datetime default now()" )
private Calendar createDate = null ;
@Column( name = "update_user", nullable = false )
private String updateUser = null ;
@Column( name = "update_date", nullable = false, columnDefinition = "datetime default now()" )
private Calendar updateDate = null ;
public static AuditColumn getInstance( String user ) {
AuditColumn auditColumn = new AuditColumn();
auditColumn.setCreateUser(user);
auditColumn.setUpdateUser(user);
return auditColumn ;
}
}
其他类 A.java 使用 AuditColumn.java 作为 @Embedded ,如下所示。
public class A {
@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
private int id = -1 ;
@Column(name = "first_name")
private String firstName = null ;
@Column( name = "last_name" )
private String lastName = null ;
@Embedded
AuditColumn auditColumn = null ;
}
尝试保存实体A,如下所示。
A a = new A();
a.setFirstName("firstName " );
a.setLastName("lastName " );
AuditColumn auditColumn = AuditColumn.getInstance("USER");
a.setAuditColumn(auditColumn);
session.save(a);
On执行上述代码获取:
Exception in thread "main" org.hibernate.PropertyValueException: not-null property references a null or transient value : com.bpk.hibernate.data.model.A.auditColumn.createDate
有没有办法在没有通过java设置值的情况下传递AuditColumn的CreateDate的默认值?
答案 0 :(得分:0)
您可以使用@CreationTimeStamp注释createDate字段。
public class AuditColumn {
@Column( name = "create_user", nullable = false )
private String createUser = null ;
@Column( name = "create_date", nullable = false , columnDefinition = "datetime default now()" )
@CreationTimestamp
private Calendar createDate = null ;
@Column( name = "update_user", nullable = false )
private String updateUser = null ;
@Column( name = "update_date", nullable = false, columnDefinition = "datetime default now()" )
private Calendar updateDate = null ;
public static AuditColumn getInstance( String user ) {
AuditColumn auditColumn = new AuditColumn();
auditColumn.setCreateUser(user);
auditColumn.setUpdateUser(user);
return auditColumn ;
}
}
请参阅Hibernate用户指南 https://docs.jboss.org/hibernate/orm/current/userguide/html_single/Hibernate_User_Guide.html#annotations-hibernate-creationtimestamp