I am a newbie to Hibernate and have to support an existing application that uses Hibernate It is a pure reporting application - no insert / update / delete - only selects
I can see existing POJO objects which have the @Id annotation used in more than one field in the same class
My understanding was that for a composite primary key - you need to use @Embeddable and @EmbeddedId
However this is not defined in my class and the strange thing is code compiles and runs just fine
Here is an example of my code :
package com.xyz.vo;
import java.io.Serializable;
import javax.persistence.*;
import org.hibernate.annotations.GenericGenerator;
@Entity(name="com.xyz.vo.Emp")
@Table(name = "TEmployee")
public class Emp implements Serializable {
private java.lang.Integer empId;
@Id
@Column(name = "EMP_ID")
public java.lang.Integer getEmpId(){
return this.empId;
}
public void setEmpId(java.lang.Integer empId){
this.empId=empId;
}
private java.lang.Integer empAge;
@Id
@Column(name = "EMP_AGE")
public java.lang.Integer getEmpAge(){
return this.empAge;
}
public void setEmpAge(java.lang.Integer empAge){
this.empAge=empAge;
}
private String empName;
@Column(name = "EMP_NAME")
public String getEmpName(){
return this.empName;
}
public void setEmpName(String empName){
this.empName=empName;
}
and many more fields in the pojo - which do not have the @Id defined
NOTE - here two fields have the @Id annotation
I am confused why this compiles and works ? Thanks akila
So yes, you can have more than one @Id.
The most straightforward way to define an identifier is by using the @Id annotation. Simple ids are mapped using @Id to a single property of one of these types: Java primitive and primitive wrapper types, String, Date, BigDecimal and BigInteger.
Every JPA entity must have a primary key. You can specify a primary key as a single primitive, or JDK object type entity field (see "Configuring a JPA Entity Simple Primary Key Field").
When you define an entity object, it must have a primary key or use a RowID attribute (based on the table's ROWID). To do so, you must create a new attribute while you are defining your entity object in the Entity Object Wizard.
According to the Hibernate docs, Hibernate seems to allow this but it is not however JPA compliant.
5.1.2.1.2. Multiple id properties without identifier type
Another, arguably more natural, approach is to place @Id on multiple properties of your entity. This approach is only supported by Hibernate (not JPA compliant) but does not require an extra embeddable component.
http://docs.jboss.org/hibernate/core/3.6/reference/en-US/html_single/#d0e4819
For a JPA compliant solution you would have to specify an additional @IDClass for this set-up (or use an EmbeddedId):
http://www.objectdb.com/java/jpa/entity/id
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With