使用具有多列主键的 Hibernate Get
Using Hibernate Get with Multi-Column Primary Key
假设我有一个 class 看起来像这样:
public class MyClass {
@Id
@Column(name = "ID")
private long Id;
}
我可以使用休眠会话在 class 上执行获取或加载,如下所示:
MyClass a = (MyClass)session.get(MyClass.class, new Long(100));
但是,假设我有一个 class 多列作为主键:
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;
}
是否可以使用 get 或 load 这样的 class?
尝试使用和@IdClass
或@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;
}
然后使用
MyJoinClass a = (MyJoinClass )session.get(MyJoinClass .class, new MyJoinClassKey (1, "email"));
看看这个问题,this解释的很笼统。基本上 hibernate 有一个复合键机制。
在 Hibernate 中是 (documentation):
MyJoinClass a = session.get(MyJoinClass.class, new MyJoinClass(100, 200));
只要确保有一个包含复合键所有部分的构造函数(不要忘记没有参数的默认 public 构造函数):
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;
}
}
假设我有一个 class 看起来像这样:
public class MyClass {
@Id
@Column(name = "ID")
private long Id;
}
我可以使用休眠会话在 class 上执行获取或加载,如下所示:
MyClass a = (MyClass)session.get(MyClass.class, new Long(100));
但是,假设我有一个 class 多列作为主键:
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;
}
是否可以使用 get 或 load 这样的 class?
尝试使用和@IdClass
或@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;
}
然后使用
MyJoinClass a = (MyJoinClass )session.get(MyJoinClass .class, new MyJoinClassKey (1, "email"));
看看这个问题,this解释的很笼统。基本上 hibernate 有一个复合键机制。
在 Hibernate 中是 (documentation):
MyJoinClass a = session.get(MyJoinClass.class, new MyJoinClass(100, 200));
只要确保有一个包含复合键所有部分的构造函数(不要忘记没有参数的默认 public 构造函数):
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;
}
}