我有一个表有复合键'rid'和'sid'。
为此我已经使用hibernate注释制作了以下bean:
WBList.java
============
@Entity
@IdClass(WBListPK.class)
public class WBList {
private int rid;
private int sid;
private String wb;
@Id
@JoinColumn(name="rid")
public int getRid() {
return rid;
}
public void setRid(int rid) {
this.rid = rid;
}
@Id
@JoinColumn(name="sid")
public int getSid() {
return sid;
}
public void setSid(int sid) {
this.sid = sid;
}
@Column(name="wb")
public String getWb() {
return wb;
}
public void setWb(String wb) {
this.wb = wb;
}
}
WBListPK.java有以下代码:
@Embeddable
public class WBListPK implements Serializable {
private int rid;
private int sid;
private String wb;
public int getRid() {
return rid;
}
public void setRid(int rid) {
this.rid = rid;
}
public int getSid() {
return sid;
}
public void setSid(int sid) {
this.sid = sid;
}
public String getWb() {
return wb;
}
public void setWb(String wb) {
this.wb = wb;
}
}
我的WBListDao有以下方法:
//Some other code ...
public WBList getWBListById(WBListPK wbListPK) {
return (WBList) this.hibernateTemplate.get(WBList.class,wbListPK);
}
以下是我的控制器代码:
WBList wbList = new WBList();
WBListPK wbListPK = new WBListPK();
wbListPK.setRid(1);
wbListPK.setSid(7);
wbList = this.wbListSecurityProcessor.getWBListById(wbListPK);
System.out.println("Wblist = "+wbList);
当我执行上面的代码时,wbList获取空值..
如果有人有任何解决方案,请帮助..
提前致谢...
答案 0 :(得分:1)
我不确定分配两个@Id
列是否有效。
更好地了解@EmbeddedId
答案 1 :(得分:1)
获得解决方案,以及在Hibernate中实现Composite Key的其他方式......
以下是说明解决方案的代码:
@Entity
public class WBList {
private WBListPK id;
private String wb;
private Integer rid;
private Integer sid;
@Id
public WBListPK getId() {
return id;
}
public void setId(WBListPK id) {
this.id = id;
}
@Column(name="wb")
public String getWb() {
return wb;
}
public void setWb(String wb) {
this.wb = wb;
}
}
@Embeddable
public class WBListPK implements Serializable {
private int rid;
private int sid;
public WBListPK() {
}
public WBListPK(Integer rid, Integer sid) {
this.rid = rid;
this.sid = sid;
}
public int getRid() {
return rid;
}
public void setRid(int rid) {
this.rid = rid;
}
public int getSid() {
return sid;
}
public void setSid(int sid) {
this.sid = sid;
}
控制器代码:
WBList wbList = new WBList();
wbList.setWb("d");
WBListPK wbListPK = new WBListPK(30,40);
wbList.setId(wbListPK);
this.wbListSecurityProcessor.save(wbList);