I'm using JPA and getting the following warning. I've researched this, and understand why I need to override it and how Hibernate uses these methods. I still have a question though:
Exception:
Composite-id class does not override equals()
Question:
Why does Hibernate only care about classes that don't have composite IDs? Does it by default compare on the #Id field if there is only one present, or is there something more complex going on here?
Because when entities don't have a composite ID, they have a single one, of one of the basic supported types (Integer, Long, String, etc.), and those classes already have a well-defined equals() (and hashCode()) method.
Using JPA when you use composite key, you should use either IdClass or EmbeddedId using any of them you need to create an own class that act as a composite key, in order to be able to compare objects using this composite key which is required by several operations within the EntityManager that key classes must to override equals and hashCode.
Taking from specs:
A composite primary key must correspond to either a single persistent field or property or to a set of such fields or properties as described below. A primary key class must be defined to represent a composite primary key. Composite primary keys typically arise when mapping from legacy databases when the database key is comprised of several columns. The EmbeddedId or IdClass annotation is used to denote a composite primary key.
And when using composite primary keys must follow.
The primary key class must be public and must have a public no-arg constructor.
The primary key class must be serializable.
The primary key class must define equals and hashCode methods. The semantics of value equality for these methods must be consistent with the database equality for the database types to which the key is mapped.
Related
I have an #Embeddable class with two fields: type and value. Both fields map to the corresponding database columns. The first one is enum and the latter one is an interface that has multiple implementations.
Only certain combinations of type and value are considered valid even if type and value are correct in isolation. How can I perform such validation, when I retrieve the entity that owns the #Embeddable from the database?
I could perform validation inside no-args-constructor of embeddable, but as far as I'm concerned, Hibernate creates new #Embeddable instance with no-args-constructor and then injects the values with Java Reflection API. Therefore, if I access these two fields inside the constructor they will be null.
Is there an approach to register some PostLoad hook for the #Embeddable classes that Hibernate will trigger? I though about declaring PostLoad inside the entity itself and then calling MyEmbeddable.validate directly. But I think it's a dirty approach.
I added the class-level annotation to validate the whole object. It did work. Check out this question for more details.
What is the difference between #Embedded annotation technique and #OneToOne annotation technique because in Embedded the java class contain "Has a" relationship in class and with the help of #Embedded annotation we persist the has a object in database. and in OneToOne relationship we also persist the has a object in database.
#OneToOne is for mapping two DB tables that are related with a one to one relationship. For example a Customer might always have one record in a Name table.
Alternatively if those name fields are on the Customer table (not in a separate table) then you might want an #embedded. On the face of it you could just add the name fields as standard attributes to the Customer entity but it can be useful if those same columns appear on multiple tables (for example you might have the name columns on a Supplier table).
Its the difference between composition and aggregation. #Embedded objects are always managed within the lifecycle of their parents. If the parent is updated or deleted, they are updated or deleted as well. #OneToOne objects may mimic composition via the cascadeType option of their #Join annotation, but by default they are aggregated, aka their lifecycle is separate from that of their parent objects.
#Embedded is used with Value Objects (Objects which have a meaning only when attached to an Object) whereas one to one mapping is between two objects having their own existence and meaning.
For e.g.
Value Object and #Embedded: If we have a User class and this class has an address Object in it, it can be considered as a value object as the address alone does not have any significance until unless associated with a user. Here address object can be annotated with #Embedded.
One to One mapping and #OneToOne: If we have a User class and this class has a 'Father' Object or a 'Mother' object, we would want to annotate the 'Father' or 'Mother' instance as #OneToOne as 'Father' or 'Mother' have their own meaning and existence and are not Value objects to User class.
A closely related difference is between #OneToMany and #ElementCollection. Both are used to save instance variables of Collection type in Java class. The difference being, #ElementCollection is to be used when the elements of Collection being saved are Value Objects whereas #OneToMany is used when the elments and object have well defined meaning and existence.
Use #OneToOne, only if fields can be reused. Otherwise, go for #Embeddable.
A quote from Beginning Hibernte, 3rd Edition:
There is nothing intrinsically wrong with mapping a one-to-one association between two entities where one is not
a component of (i.e., embedded into) the other. The relationship is often somewhat suspect, however. You should
give some thought to using the embedded technique described previously before using the #OneToOne annotation.
#Embeddable:
If the fields in an entity (X) are contained within the same table as another entity (Y), then entity X is called "component" in hibernate terms or "embedded" in JPA terms. In any case, JPA or hibernate do not allow to use 2nd table to store such embedded entities.
Generally, we think of normalizing a table when data is being reused by more than one table. Example: A Customer (id, name, street, city, pin, landmark) can be normalized into Customer(id, name) and CustomerAddress(cust_id, street, city, pin, landmark). In this case, we can reuse CustomerAddress by linking the same using cust_id with other tables. But if this reuse is not required in your application, then we can just keep all columns in one table.
So, a thumb rule is,
If reuse -> #OneToOne,
If no reuse -> #Embeddable
#Embedded is typically to represent a composite primary key as an embeddable class:
#Entity
public class Project {
#EmbeddedId ProjectId id;
:
}
#Embeddable
Class ProjectId {
int departmentId;
long projectId;
}
The primary key fields are defined in an embeddable class. The entity contains a single primary key field that is annotated with #EmbeddedId and contains an instance of that embeddable class. When using this form a separate ID class is not defined because the embeddable class itself can represent complete primary key values.
#OneToOne is for mapping two DB tables that are related with a one to one relationship. #Id will be the primary key.
is it possible to model a reference to "any" (entity) with JPA? Similar to a reference of type Object in Java, which can hold any object.
Thanks for your answer,
Dominik
You should think about representation of the reference in database.
If reference is represented by a single foreign key, then referenced column should be guaranteed to be unique for all possible referenced entities. In JPA it's possible only for entites in inheritance hierarchy, so you'll get a reference to the root of some inheretence hierarchy of entites instead of Object.
Reference may be represented by a pair of values <type of referenced entity, foreign key>. This case is not supported by plain JPA, but supported in Hibernate by Hibernate's own #Any annotation.
According to DataNucleus this is not possible (search in this for java.lang.Object):
http://www.datanucleus.org/products/accessplatform_1_1/jpa/types.html
For JDO we introduced our our Object-like abstract class called Subject which is annotated for persistence and extended all other persistable object from it. That works in JDO and I think it should work in JPA as well.
Using JPA, can we define an enum as id of an entity?
I've tried the following:
public enum AssetType {
....
}
#Entity
#IdClass(AssetType.class)
public class Adkeys {
private AssetType type;
#Id
#Enumerated(EnumType.STRING)
#Column(nullable = false)
public AssetType getType() {
return type;
}
}
Using OpenJPA, it complains:
org.apache.openjpa.persistence.ArgumentException: The id class "class aa.AssetType" specified by type "class aa.Adkeys" does not have a public no-args constructor.
So my questions are:
should we able to use enum as id for an entity on JPA? (i.e. there is a bug in OpenJPA)
or do I make a mistake somewhere?
and is there any workaround for such problem?
The JPA spec doesn't say this is possible:
2.1.4 Primary Keys and Entity Identity
The primary key (or field or property of a composite primary key) should be one of the following types: any Java primitive type; any primitive wrapper type; java.lang.String; java.util.Date; java.sql.Date. In general, however, approximate numeric types (e.g., floating point types) should never be used in primary keys. Entities whose primary keys use types other than these will not be portable.
If you really want to have a compile-time fixed number of records for a given entity, you can use a String or int primary key and assign it AssetType.FOO.name() or AssetType.FOO.ordinal()
And non-portable here means that some persistence provider may support other things, but it might not work for another provider. As with the enum - if the persistence provider has special support for it, that does not try to instantiate it, but rather processes it specially after checking if class.isEnum(), then it might work. But it seems your persistence provider doesn't do this.
No, you can't use enums as ID because JPA doesn't allow to define your own mapping for ID columns (they must be int or long or something that JPA can create with new).
IDs must not be the business key (in your case: the type). Using the business key as an ID is a common mistake in DB designs and should be avoided because it will cause all kinds of problems later.
Add an independent ID column to solve the problem.
OpenJPA is the only JPA provider that does not support this.
See Support Enum as Primary Key Type
Do you really want to do this? This construct doesn't allow changing the database enum keys without updating the enum in the code (fail on load), nor the other way around (constraint failure). Why don't you just create an AssetType table with int pk and name, and make the Adkeys have a foreign key to AssetType.id as pk?
You can load the AssetTypes from the db on startup if you need to enumerate them in your app.
Is it necessary to check all the field in equals method of model class in JPA, or can I use only id?
No, it's not necessary to put all of your fields in the equals method just because you're using JPA. In fact, JPA specific fields you may want to ignore.
You need to decide what makes most sense for your application, but it's quite common to exclude your #Id and #Version fields. Include only those fields that differentiate one instance of an object from another: essentially the fields that form the key.
Not always. You should clearly see which fields form a native (business) key and compare only those fields. Sometimes all fields form the native key, sometimes not.
Read this discussion at hibernate forum about strategies of implementing equals and hashcode.
I would check the id only. In case it's null (not set), which is the case for just created objects, I would rely on standard equals implementation (comparison of references).