Reputation: 3286
Say I have a class that looks like this:
public class MyClass {
@Id
@Column(name = "ID")
private long Id;
}
I can use a hibernate session to do a get or load on the class like this:
MyClass a = (MyClass)session.get(MyClass.class, new Long(100));
However, assume I have a class with multiple columns as the primary key:
public MyJoinClass implements Serializable {
private static final long serialVersionUID = -5L;
@Id
@Column(name = "ID")
private long id;
@Id
@Column(name = "EMAIL_ADDRESS_ID")
private long emailAddressId;
}
Is it possible to use get or load with such a class?
Upvotes: 6
Views: 16302
Reputation: 1031
In Hibernate yes (documentation):
MyJoinClass a = session.get(MyJoinClass.class, new MyJoinClass(100, 200));
Just make sure to have a constructor with all parts of the composite key (and don't forgot the default public constructor with no parameters):
public MyJoinClass implements Serializable {
private static final long serialVersionUID = -5L;
@Id
@Column(name = "ID")
private long id;
@Id
@Column(name = "EMAIL_ADDRESS_ID")
private long emailAddressId;
public MyJoinClass() {}
public MyJoinClass(long id, long emailAddressId) {
this.id= id;
this.emailAddressId= emailAddressId;
}
}
Upvotes: 1
Reputation: 19533
Try to use and @IdClass
or @EmbeddedId
public MyJoinClass implements Serializable {
private static final long serialVersionUID = -5L;
@EmbeddedId
private MyJoinClassKey key;
}
public MyJoinClassKey implements Serializable{
@Column(name = "ID")
private long id;
@Column(name = "EMAIL_ADDRESS_ID")
private long emailAddressId;
}
Then use
MyJoinClass a = (MyJoinClass )session.get(MyJoinClass .class, new MyJoinClassKey (1, "email"));
Take a look at this question, this is broadly explained. Basically hibernate have a mechanism for compound keys.
Upvotes: 9