使用Hibernate获取多列主键 [英] Using Hibernate Get with Multi-Column Primary Key
本文介绍了使用Hibernate获取多列主键的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
public class MyClass {
@Id
@Column(name =ID)
私人长ID;
}
我可以使用hibernate会话来获取或加载类这个:
MyClass a =(MyClass)session.get(MyClass.class,new Long(100));
然而,假设我有一个包含多个列的类作为主键:
public MyJoinClass implements Serializable {
private static final long serialVersionUID = -5L;
@Id
@Column(name =ID)
私人长ID;
@Id
@Column(name =EMAIL_ADDRESS_ID)
private private emailAddressId;
}
是否可以使用get或load这样的类?
解决方案
尝试使用和 @IdClass
或 @EmbeddedId
public MyJoinClass implements Serializable {
private static final long serialVersionUID = -5L;
@EmbeddedId
私人MyJoinClassKey键;
$ b $ public MyJoinClassKey实现Serializable {
@Column(name =ID)
私有长ID;
@Column(name =EMAIL_ADDRESS_ID)
private private emailAddressId;
}
然后使用
<$ MyJoinClass a =(MyJoinClass)session.get(MyJoinClass .class,new MyJoinClassKey(1,email));
看看这个问题,这个被广义解释。基本上hibernate有一个复合键的机制。
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?
解决方案
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.
这篇关于使用Hibernate获取多列主键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文