Jpa hibernate and Table_Per_class inheritance - java

I have an entity that is super class
#Entity
#Inheritance(strategy = InheritanceType.TABLE_PER_CLASS)
#Table(name = "super_class")
public abstract class SuperClass implements Serializable {
#Transient
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.TABLE)
private long id;
public abstract void initDefaultValues();
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
}
and some subclasses that extend the SuperClass.
#Entity
#Table(name = "Subclass1")
public class Subclass1 extends SuperClass{
private static final Logger log = LogManager
.getLogger(Subclass1.class);
#Transient
private static final long serialVersionUID = 1L;
// testcase configuration tab
private String configurationTabTestServer;
private String umtsRelease;
}
The other classes look the same.
I used to have them SINGLE_TABLE for inheritance type but we wanted each concrete class to have each own table. Because of TABLE_PER_CLASS I had to use GenerationType.TABLE.
I also have an entity class that has a foreign key to the super class
#Entity
#Table(name="myother_entity")
class Entity1{
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private int id;
#OneToOne(cascade = CascadeType.ALL)
private SuperClass superclass;
//more fields
}
I used an abstract class because I have one Entity1 class that could have different type of Superclass. We didn't want to create different Entity1 and Entity2 and Entity3 etc classes for each subclass. So we created one Entity1 class that can have a field of type SuperClass, that could point to any of the subclasses.
On my program I create many Entity1 intances that some of them that have different type of superclass as field value. Each could be of type subclass1 or subclass2 etc. At first we used to have one single table for all subclasses. Everything worked fine. But after we decided to split our tables this is what it happens. When I edit any Entity1 instance, that has already SuperClass field set(using one of the sub classes), and save it (merging it) then it creates a new instance of my Subclass associated with my Entity1 instance, and then saves it to the database. So I have two records now on the table of the subclass. This didn't happen when we used a SINGLE_TABLE inheritance type. Is this normal behaviour for JPA and hibernate?

Please, first consider this: DiscriminatorColumn and DiscriminatorValue annotations are specific to single-table approach. So they aren't to be used in table-per-class mappings.
Now, let's go to the issue:
In table-per-class mapping, there will be two records with same ID: one in a parent table, other in a child table.
As I understood, in your case, two records are being written in the child table, right? If so, the problem must be when you load the Entity1 data from the database. The property "superclass" must have its ID set. You can use eager or lazy loading for this. And check if that property is properly loaded (in debug mode) with its correct ID set before saving it.
Another way is to disable "cascade persist/merge" and to save the entities separately. It can provide more security to your data.
You can find more information here: http://docs.oracle.com/javaee/6/tutorial/doc/bnbqn.html

Related

I am trying to extend a base class which has Id in two different subclass to hit JPA query [duplicate]

I am creating entities that are the same for two different tables. In order do table mappings etc. different for the two entities but only have the rest of the code in one place - an abstract superclass. The best thing would be to be able to annotate generic stuff such as column names (since the will be identical) in the super class but that does not work because JPA annotations are not inherited by child classes. Here is an example:
public abstract class MyAbstractEntity {
#Column(name="PROPERTY") //This will not be inherited and is therefore useless here
protected String property;
public String getProperty() {
return this.property;
}
//setters, hashCode, equals etc. methods
}
Which I would like to inherit and only specify the child-specific stuff, like annotations:
#Entity
#Table(name="MY_ENTITY_TABLE")
public class MyEntity extends MyAbstractEntity {
//This will not work since this field does not override the super class field, thus the setters and getters break.
#Column(name="PROPERTY")
protected String property;
}
Any ideas or will I have to create fields, getters and setters in the child classes?
Thanks,
Kris
You might want to annotate MyAbstractEntity with #MappedSuperclass class so that hibernate will import the configuration of MyAbstractEntity in the child and you won't have to override the field, just use the parent's. That annotation is the signal to hibernate that it has to examine the parent class too. Otherwise it assumes it can ignore it.
Here is an example with some explanations that may help.
#MappedSuperclass:
Is a convenience class
Is used to store shared state & behavior available to child classes
Is not persistable
Only child classes are persistable
#Inheritance specifies one of three mapping strategies:
Single-Table
Joined
Table per Class
#DiscriminatorColumn is used to define which column will be used to distinguish between child objects.
#DiscriminatorValue is used to specify a value that is used to distinguish a child object.
The following code results in the following:
You can see that the id field is in both tables, but is only specified in the AbstractEntityId #MappedSuperclass.
Also, the #DisciminatorColumn is shown as PARTY_TYPE in the Party table.
The #DiscriminatorValue is shown as Person as a record in the PARTY_TYPE column of the Party table.
Very importantly, the AbstractEntityId class does not get persisted at all.
I have not specified #Column annotations and instead are just relying on the default values.
If you added an Organisation entity that extended Party and if that was persisted next, then the Party table would have:
id = 2
PARTY_TYPE = "Organisation"
The Organisation table first entry would have:
id = 2
other attribute value associated specifically with organisations
#MappedSuperclass
#SequenceGenerator(name = "sequenceGenerator",
initialValue = 1, allocationSize = 1)
public class AbstractEntityId implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(generator = "sequenceGenerator")
protected Long id;
public AbstractEntityId() {}
public Long getId() {
return id;
}
}
#Entity
#Inheritance(strategy = InheritanceType.JOINED)
#DiscriminatorColumn(name = "PARTY_TYPE",
discriminatorType = DiscriminatorType.STRING)
public class Party extends AbstractEntityId {
public Party() {}
}
#Entity
#DiscriminatorValue("Person")
public class Person extends Party {
private String givenName;
private String familyName;
private String preferredName;
#Temporal(TemporalType.DATE)
private Date dateOfBirth;
private String gender;
public Person() {}
// getter & setters etc.
}
Hope this helps :)
Mark the superclass as
#MappedSuperclass
and remove the property from the child class.
Annotating your base class with #MappedSuperclass should do exactly what you want.
This is old, but I recently dealt with this and would like to share my solution. You can add annotations to an overridden getter.
#MappedSuperclass
public abstract class AbstractEntity<ID extends Serializable> implements Serializable {
#Column(name = "id", nullable = false, updatable = false)
#Id
private ID id;
public ID getId() {
return id;
}
...
}
#Entity
#Table(name = "address")
public final class Address extends AbstractEntity<UUID> implements Serializable {
...
#Override
#GeneratedValue(generator = "UUID")
#GenericGenerator(name = "UUID", strategy = "org.hibernate.id.UUIDGenerator")
public final UUID getId() {
return super.getId();
}
...
}

Hibernate and #AttributeOverride

I have 3 classes:
#MappedSuperclass
public class BaseEntity {
#Id
#GeneratedValue
private Long id;
...
}
#Entity
public class Person extends BaseEntity {
private String name;
...
}
#Entity
#AttributeOverride(name = "id", #Column = (name = "idStudent"))
public class Student extends Person {
private float avgGrades;
...
}
I would like to override ID property so in Student table there would be a idStudent column instead of id. Unfortunately, the code above doesn't work. It looks like #AttributeOverride only works for the class you extending (and no one step further). Is there any way to override attribute name in situation I've descried (override attribute in class which exteds our class being extended) ?
Your problem is very easy to understand, if you know what the default inheritance type is: SINGLE_TABLE.
That means all entities that extending Person are in the same table. And thus Person already defines the ID column. Because you would otherwise violate the contract of the primary key column of your Person table.
I cite the JavaDoc of #AttributeOverride as well:
May be applied to an entity that extends a mapped superclass or to an embedded field or property to override a basic mapping or id mapping defined by the mapped superclass or embeddable class (or embeddable class of one of its attributes).
It always helps to read the JavaDoc first, before asking questions here.
What can you do about it? Make your Person a #MappedSuperclass (or create a BasePerson that is one).

Objectify - should I create an entity super class?

Is there any reason why shouldn't all my entities be subclasses of one generic ModelEntity object?
#Entity
public class ModelEntity {
#Id Long id;
}
#Subclass
public class User extends ModelEntity {
#Index
String username;
}
The advantages are clear: there is code common to all entities (like id, date, getKey)
Can you think of disadvantages?
It can be helpful to have a common base class, but you almost certainly do not want to make it part of a polymorphic entity hierarchy. Don't use #Subclass for this purpose; you don't need it:
public class ModelEntity {
#Id Long id;
}
#Entity
public class User extends ModelEntity {
#Index
String username;
}
Well, one of the great advantages of the jpa abstractions is to have insulation between the persistence layer and business logic. If you use an hidden id for all your entities you are giving up on that.
For example you could have a value object with your implementation so that you are actually hiding the #Id part of your entity. You could the use a completely different #Id for "real" entities.

Understanding of TABLE_PER_CLASS with keys in eclipselink

I have a simple Java EE 7 Web App with Eclipselink and the TABLE_PER_CLASS inheritance strategy.
Following classes:
#Inheritance(strategy = InheritanceType.TABLE_PER_CLASS)
#Entity
public abstract class AbstractService implements Serializable {
private static final long serialVersionUID = 7041207658121699813L;
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
#ManyToOne
#JoinColumn
private PersonGroup personGroup;
}
#Entity
public class Service extends AbstractService implements Serializable {
private static final long serialVersionUID = 3817106074951672799L;
}
#Entity
public class PersonGroup implements Serializable {
private static final long serialVersionUID = 3205092801888510996L;
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
#OneToMany(cascade = CascadeType.ALL, mappedBy = "personGroup")
private List<AbstractService> services;
}
In persistence.xml I do Drop&Create.
After creating the database, I have this tables:
abstractservice, service, persongroup
The point is now, that eclipselink creates the table abstractservice with (only(!)) the attribute persongroup_id (no "id" attribute). Why?
My understanding from TABLE_PER_CLASS is, that every attribute and key is going "down", so abstractservice should have no more attributes and should not exist.
My businesscase is, that I have a lot of subservice from AbstractService. I want to get all subservices from AbstractService with a special persongroup.
The AbstractServicetable has no entries, because everything is in Service.
With CriteriaBuilder I say:
Select from AbstractService where persongroup_id = 123;
The Criteria Api should build this (with some union, if more subservices would exist), because I have TABLE_PER_CLASS:
Select from Service where persongroup_id = 123;
Why is eclipselink creating persongroup_id in abstractService and how can I solve my case?
At the end the result of the query is always empty, because abstractService is empty...
Same question was asked here: http://www.eclipse.org/forums/index.php/t/406338/
and seems to be related to bug https://bugs.eclipse.org/bugs/show_bug.cgi?id=265702 which was fixed but regressed. A new bug should be filed for it if you are seeing this in the latest version.
If you are only using a single Servide subclass, you might want to make it a mappedSuperclass instead. If not, a different inheritance type such as joined or single table is usually recommended. This bug seems to only affect DDL generation, so you can switch to have JPA create a script that you can then edit to remove the AbstractService table entries.

#embeddable vs #entity for a mapping a collection

This must be quite naive but I have a doubt on when to use #Entity and #Embeddable.
Say I have a User and Notification class.
#Entity
public class User{
//other properties
#onetomany
private List<Notification> notifications;
}
#Entity
public class Notification{
//properties
}
I understand that there will be tables for class User and Notification, and a third table for mapping.
What if I do it like this?
#Entity
public class User {
//other properties
#ElementCollection
private List<Notification> notifications;
}
#Embeddable
public class Notification{
//properties
}
I know this won't create a table for Notification. But I can still store my notification objects. I went through the documentation, but couple of doubts:
Is it based on whether I want to see class B as a seperate table?
Is there a performance difference b/w creating a table and an embeddable object?
What can I not do with embeddable object that I can do with a table other than directly querying the table?
NOTES
For anyone reading this question, this question too might help you.
Is it based on whether I want to see class B as a separate table?
Yes, when you use #Embedded, You embed that #Embeddable entity in #Entity class, which makes it to add columns for embedded entity in same table of #Entity class.
Is there a performance difference b/w creating a table and an embeddable object?
When you use #Embedded, for table creation, one query is required, also for inserting and selecting a row. But if you don't use it, multiple queries are required, hence, use of #Embedded yields more performance, we can say.
What can I not do with embeddable object that I can do with a table other than directly querying the table?
Removing the respective embedded entity may be, but there may be integrity constraint violations for this.
In JPA, there’s a couple ways to create composite key fields. Lets see the method using the #Embeddable annotation.
Let’s start with the Entity class.
#Entity
#Table
public class TraceRecord {
#Id
private TraceRecordPk id;
#Version
#Transient
private int version;
#Column(columnDefinition = "char")
private String durationOfCall;
#Column(columnDefinition = "char")
private String digitsDialed;
#Column(columnDefinition = "char")
private String prefixCalled;
#Column(columnDefinition = "char")
private String areaCodeCalled;
#Column(columnDefinition = "char")
private String numberCalled;
}
This is a pretty simple Entity class with an #Id and #Version field and a few #Column definitions. Without going into too much detail, you’ll see that the #Version field is also annotated #Transient. I’ve done this simply because my table also doesn’t have a column for tracking versions, but my database is journaled, so I’m not too concerned about versioning. You’ll also notice that the #Column fields have a value of “char” set on the columnDefinition attribute. This is because the fields in my table are defined as char and not varchar. If they were varchar, I wouldn’t need to do this since a String maps to a varchar field by default.
The #Id field is what I’m interested in right now. It’s not a standard Java type, but a class I’ve defined myself. Here is that class.
#Embeddable
public class TraceRecordPk implements Serializable {
private static final long serialVersionUID = 1L;
#Temporal(TemporalType.DATE)
#Column
private Date dateOfCall;
#Column(columnDefinition="char")
private String timeOfCall;
#Column(columnDefinition="char")
private String callingParty;
/**
* Constructor that takes values for all 3 members.
*
* #param dateOfCall Date the call was made
* #param timeOfCall Time the call was made
* #param callingParty Extension from which the call originated
*/
public TraceRecordPk(Date dateOfCall, String timeOfCall, String callingParty) {
this.dateOfCall = dateOfCall;
this.timeOfCall = timeOfCall;
this.callingParty = callingParty;
}
}
To make this class capable of being an #Id field on an Entity class, it needs to be annotated with #Embeddable like I mentioned earlier. The 3 fields I’ve selected for my composite key are just normal #Column definitions. Rather than create getters/setters for each field, I’ve simply implemented a constructor that takes values for all 3 fields, making any instance immutable. When annotating a class with #Embeddable, that class will need to implement Serializable. So I’ve added a default serialVersionUID to accomodate.
Now that you have a class created and annotated with #Embeddable, you can now use it as the type for an #Id field in your Entity class. Simple stuff eh.

Categories

Resources