简体   繁体   中英

JPA MappedSuperClass column as not nullable

I am working on creating a few abstract classes to abstract the properties each of my entities would share, like an ID for example.

I created a AbstractModel class shown below.

import javax.persistence.*;
import java.io.Serializable;

@MappedSuperclass
public abstract class AbstractModel implements Serializable {

    @Id
    @GeneratedValue(strategy = GenerationType.SEQUENCE)
    protected Long id;

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    @Override
    public abstract int hashCode();

    @Override
    public abstract boolean equals(Object obj);

    @Override
    public abstract String toString();
}

I created another abstract class with extends AbstractModel to add some auditing information, such as date created and last modified.

import org.springframework.data.annotation.CreatedDate;
import org.springframework.data.annotation.LastModifiedDate;

import javax.persistence.MappedSuperclass;
import java.util.Date;

@MappedSuperclass
public abstract class AbstractAuditModel extends AbstractModel {

    @CreatedDate
    protected Date createdAt;

    @LastModifiedDate
    protected Date lastModifiedAt;

    @Override
    public abstract int hashCode();

    @Override
    public abstract boolean equals(Object obj);

    @Override
    public abstract String toString();
}

I'm using JPA/Hibernate to create the database. There is no physical database in place, Hibernate will be generating and updating the schema (Code First approach).

My question is how can I force JPA/Hiberante to make createdAt and lastModifiedAt NON NULLABLE fields in the database?

I know I can use Java validation and Hibernate validation to prevent the application from inserting null values but I want the database to enforce it as well incase someone decides to do some manually inserting into the database.

You can use the @Column annotation to define the metadata of how the schema is generated, the annotation has some properties to define how the column will be created for example the nullable property indicates if the column not allow null values.

These properties are specific to schema generation process and not works as validations in runtime for that as you mention you can use BeanValidations. You can check all the properties for the @Column annotation here

In your example you can use in this way:

@MappedSuperclass
public abstract class AbstractAuditModel extends AbstractModel {

    @CreatedDate
    @Column(nullable = false)
    protected Date createdAt;

    @LastModifiedDate
    @Column(nullable = false)
    protected Date lastModifiedAt;

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM