我目前正在研究实体映射,并想知道是否有没有主键用法的@OneToMany
映射方法。
所有映射都需要至少一个要映射的实体上的主键。
例如: 我有2张桌子
Table 1
ID(PK),
Name,
Xid
Table 2
ID(PK),
UserName,
userType,
Xid
例如,我不想说
@OnetoMany(mapped by="")
public Table2 t2
@ManyToOne()
public Table1 id;
是否可以使用@JoinTable
将Table1的Xid映射/关联到Table2的Xid?
答案 0 :(得分:0)
是的,您可以将关系映射到主键和外键上。
表1:
@Entity
@Table(name = "Table1")
public class Table1 implements Serializable,Cloneable {
@Id
@Column(name = "id")
private BigInteger id;
@Column(name = "Name")
private String name;
@Column(name = "Xid")
private BigInteger xid;
@OneToOne
@JoinColumn(name = "Xid", nullable = false, insertable = false, updatable = false, referencedColumnName = "Xid")
private Table2 table2;
// Getter and Setters
}
表2:
@Entity
@Table(name = "Table2")
public class Table2 implements Serializable , Cloneable {
public Table2() {
}
@Column(name = "id")
private BigInteger id;
@Column(name = "Xid")
private BigInteger xid;
@Column(name = "UserName")
private String userName;
@Column(name = "userType")
private String userType;
// Getter and Setters
}
在查询中,您将指定
之类的联接 CriteriaBuilder cb = session.getCriteriaBuilder();
CriteriaQuery<Table1> cq = cb.createQuery(Table1.class);
Root<Table1> root = cq.from(Table1.class);
Join<Table1, Table2> join = (Join<Table1, Table2>) root
.fetch(Table1_.table2);
List<Predicate> conditions = new ArrayList<>();
conditions.add(cb.equal(root.get(Table1_.Xid), join.get(
Table2_.Xid)));
cq.where(conditions.toArray(new Predicate[]{}));
Query query= session.createQuery(cq);