I started developing in Java quite recently, and my client is also a developer who is developing in Java since it was released.
So when he says "we have a good reason why don't we use transient fields in our project", I didn't ask what those reasons are. But, back to the question:
I have two classes:
public class BaseSector implements Serializable {
private String id;
private String name;
private String parentId;
public class Sector {
@Column(length = 36)
private String id;
@Column(length = 40)
private String name;
@Column(length = 36)
private String parentId;
// ... Bunch of other fields
Is there any way for an Entity class to extend this POJO, and add Column annotations dynamically? Or have POJO as an interface? Or use entity class in POJO constructor?
Earlier we had something like this:
for (Sector sector : sectors) {
BaseSector baseSector = new BaseSector();
baseSector.setId(sector.getId());
baseSector.setName(sector.getName());
baseSector.setParentId(sector.getParentId());
}
But I changed that by using BaseSector in HQL constructor... Btw, we also have SectorInfo and SimpleSectorInfo which also extend BaseSector, but that's a different subject..
A TRANSIENT field tells your ENTITY class that this particular field should not be persisted in the DB. @Transient
annotation is used to ignore a field to not persist in database in JPA, where as transient
key word used to ignore a field from serialization. The field annotated with @Transient
still can be serialized, but the field declared with transient
keyword not to be persisted and not to be serialized.
A POJO can be extended by an ENTITY and vice-versa. This is stated in JPA specification.You can find more examples at the below links :
Link:1 : JPA Non-Entity SuperClass
You can achieve this by using an annotation : @javax.persistence.MappedSuperclass
It states : A superclass is treated as non-entity class if no mapping related annotations such as @Entity or @MappedSuperclass are used on the class level.
This means your superclass will be treated as a non-entity class here if you do not use the above annotations in your superclass.
How to Construct the classes :
SUPERCLASS which also a POJO for your JSON object
@MappedSuperclass
public class BaseSector implements Serializable {
private String id;
private String name;
private String parentId;
}
ENTITY class :
@Entity
@Table(name = "sector")
public class Sector extends BaseSector {
@Column(length = 36)
private String id;
@Column(length = 40)
private String name;
@Column(length = 36)
private String parentId;
// ... Bunch of other field
}
You can also override some property defined by BaseSector in your ENTITY - Sector You need to use
@AttributeOverride // for single property
@AttributeOverrides // override more than one property