JPA Entities

April 2, 2020

This post covers how to define a JPA entity in a Spring Boot application. Getter and setter methods have been excluded from this example.

import java.time.LocalDate;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Index;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.Table;
import javax.validation.constraints.NotNull;

import org.hibernate.envers.AuditOverride;
import org.hibernate.envers.Audited;

@Entity
@Audited
@AuditOverride(forClass = AbstractModelEntity.class, isAudited = true)
@Table(name = "room_day", indexes = { @Index(columnList = "room_id", unique = false) })
public class RoomDayEntity extends AbstractModelEntity<String> {

    @ManyToOne(optional = true)
    @JoinColumn(name = "staff_member_id", nullable = true)
    private StaffMemberEntity staffMember;

    @Column(name = "calendar_date", nullable = false)
    @NotNull(message = "Calendar Date may not be blank")
    private LocalDate calendarDate;

    @Column(name = "staff_member_name", nullable = true)
    private String cacheStaffMemberName;

    @ManyToOne(optional = false)
    @JoinColumn(name = "room_id", nullable = false
    private RoomEntity room;
}

AbstractModelEntity represents a superclass with common attributes on it. Again, getters and setters have been excluded.

import java.time.LocalDateTime;

import javax.persistence.EntityListeners;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.MappedSuperclass;
import javax.persistence.Version;

import org.springframework.data.annotation.CreatedBy;
import org.springframework.data.annotation.CreatedDate;
import org.springframework.data.annotation.LastModifiedBy;
import org.springframework.data.annotation.LastModifiedDate;
import org.springframework.data.jpa.domain.support.AuditingEntityListener;

@MappedSuperclass
@EntityListeners({ AuditingEntityListener.class })
public abstract class AbstractModelEntity<U> {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private long id;

    @Version
    private long version;

    @CreatedBy
    private U createdBy;

    @CreatedDate
    private LocalDateTime createdOn;

    @LastModifiedBy
    private U updatedBy;

    @LastModifiedDate
    private LocalDateTime updatedOn; 
}

I had problems with the @Created... and @LastModified... annotations not working. Didn't get to the bottom of why, I just populated them manually.