如何在保存实体时传递Hibernate Entity字段值的默认值

时间:2017-04-19 09:59:15

标签: hibernate

我有 @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的默认值?

1 个答案:

答案 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