Do you have a common base class for Hibernate entities?

cretzel picture cretzel · Oct 1, 2008 · Viewed 8.4k times · Source

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;
    ...
}

Answer

Peter Hilton picture Peter Hilton · Oct 1, 2008

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.