I am using the javax.persistence package to map my Java classes.
I have the following entities:
public class UserEntity extends IdEntity { }
which extends the displayed superclass called IdEntity :
@MappedSuperclass public class IdEntity extends VersionEntity { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Integer id;
The IdEntity superclass extends another mapped superclass named VersionEntity so that all objects inherit version properties:
@MappedSuperclass public abstract class VersionEntity { @Version private Integer version;
Why?
Since now I can create general queries in the IdEntity class for all objects, and it will look like this: (example)
CriteriaBuilder builder = JPA.em().getCriteriaBuilder(); CriteriaQuery<IdEntity> criteria = builder.createQuery(IdEntity.class);
Now to the problem.
Some of my entities will have timestamps, such as created_at and deleted_at . But not all entities.
I could provide these properties in my entity classes as follows:
public class UserEntity extends IdEntity { @Basic(optional = false) @Column(name = "updated_at") @Temporal(TemporalType.TIMESTAMP) private Date updatedAt; }
But since I have a lot of entities, this will force me to put a lot of redundant code into all objects that should have timestamps. I would like, somehow, I could make the corresponding classes inherit these fields in some way.
One possible solution is to create an IdEntity parallell superclass, possibly called IdAndTimeStampEntity , and make those objects that should have timestamps inherited from this new superclass, but, unfortunately, this is not true for my fellow developers, because now they have to know which superclass to choose when writing generic queries:
CriteriaBuilder builder = JPA.em().getCriteriaBuilder(); CriteriaQuery<???> criteria = builder.createQuery(???);
And general object queries become less universal ..
My question is: how can I make all my objects inherit id and version , but only part of the subset of all objects inherits timestamp, but keep my queries for one type of object?
Update # 1
Question from Bolzano: "Can you add code that sets the path (contains information about the table) for objects?"
Here is a working example of a UserEntity request, which is IdEntity
CriteriaBuilder builder = JPA.em().getCriteriaBuilder(); CriteriaQuery<IdEntity> criteria = builder.createQuery(IdEntity.class); Root<IdEntity> from = criteria.from(IdEntity.class); criteria.select(from); Path<Integer> idPath = from.get(UserEntity_.id); //generated meta model criteria.where(builder.in(idPath).value(id)); TypedQuery<IdEntity> query = JPA.em().createQuery(criteria); return query.getSingleResult();