Search code examples
javahibernateentitiesbase-class

Do you have a common base class for Hibernate entities?


Do you have a common base class for Hibernate entities, i.e. a MappedSuperclass with id, version and other common properties? Are there any drawbacks?

Example:

@MappedSuperclass()
public class BaseEntity {

    private Long id;
    private Long version;
    ...

    @Id @GeneratedValue(strategy = GenerationType.AUTO)
    public Long getId() {return id;}

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

    @Version
    public Long getVersion() {return version;}
    ...

    // Common properties
    @Temporal(TemporalType.TIMESTAMP)
    public Date creationDate() {return creationDate;}
    ...
}

@Entity
public class Customer extends BaseEntity {
    private String customerName;
    ...
}

Solution

  • This works fine for us. As well as the ID and creation date, we also have a modified date. We also have an intermediate TaggedBaseEntity that implements a Taggable interface, because some of our web application's entities have tags, like questions on Stack Overflow.