我有单个JPA实体,我想在这个表上添加自联接。表看起来像是。
@Entity
@Table(name = "TABLE_A")
@IdClass(TableAPk.class)
public class TableA implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@Column(name = "COLUMN_1", nullable = false, length = 64)
private String column_1;
@Id
@Column(name = "COLUMN_2", nullable = false, precision = 10, scale = 2)
private BigDecimal column_2;
@ManyToOne
@JoinColumn(name = "COLUMN_1", insertable = false, updatable = false)
//@ManyToOne(optional = true, fetch = FetchType.LAZY)
//@JoinTable(name = "KEY_MAPPING",
// joinColumns = { @JoinColumn(name = "J_COLUMN_1", referencedColumnName = "COLUMN_1", insertable = false, updatable = false) } )
private TableA tableA;
@OneToMany(mappedBy="tableA", fetch = FetchType.LAZY)
private Set<TableA> tableASet;
IdClass看起来像:
public class TableAPk implements Serializable {
// default serial version id, required for serializable classes.
/** The Constant serialVersionUID. */
private static final long serialVersionUID = 1L;
private String column_1;
private BigDecimal column_2;
根据我的业务逻辑,我只需要在单列
上添加自联接final Join<TableA, TableA> joinASelf = joinX.join("tableA", JoinType.INNER);
但是table具有复合主键,因此使用@Id注释了多个字段。我得到例外:
引起:org.hibernate.AnnotationException:从com.data.TableA引用com.data.TableA的外键具有错误的列数。应该是2。
如何在此处仅在单列上添加自联接?我是JPA的新手,所以如果我错过了什么,请告诉我。
2015年2月21日更新: 我添加了注释@AssociationOverride来覆盖关联:
@ManyToOne
@AssociationOverride(name="tableA",
joinColumns=@JoinColumn(name="COLUMN_1"))
private TableA tableA;
生成的列名称显示为“TABLE_A_COLUMN_2”。我无法找出原因。任何线索?
答案 0 :(得分:6)
你可以使用@JoinColumns
注释(注意复数而不是单数),从而加入:
@Entity
@Table(name = "TABLE_A")
@IdClass(TableAPk.class)
public class TableA implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@Column(name = "COLUMN_1", nullable = false, length = 64)
private String column1;
@Id
@Column(name = "COLUMN_2", nullable = false, precision = 10, scale = 2)
private BigDecimal column2;
@ManyToOne
@JoinColumns({
@JoinColumn(name = "FK_COL1", referencedColumnName="COLUMN_1"),
@JoinColumn(name = "FK_COL2", referencedColumnName="COLUMN_2")
})
private TableA tableA;
@OneToMany(mappedBy="tableA", fetch = FetchType.LAZY)
private Set<TableA> tableASet;
删除这些@ManyToOne
/ @OneToMany
关系并添加一个private String refCol1;
。然后,为JPQL编写相应的Criteria Query:SELECT t1 FROM TableA t1, TableA t2 WHERE t2.refCol1 = t1.column1
使用CriteriyQuqeries
解决方案如下:
final CriteriaBuilder criteriaBuilder = entityManagerMds.getCriteriaBuilder();
// This Pojo is used to fetch only selected fields
final CriteriaQuery<DummyPojo> createQuery = criteriaBuilder.createQuery(DummyPojo.class);
final Root<TableX> tableX = createQuery.from(TableX.class);
final Join<TableX, TableA> joinTableA = tableX.join("tableAs", JoinType.INNER);
// Every time you want to add a self join, create new root
final Root<TableA> tableA = createQuery.from(TableA.class);
final Predicate predicateSelfJoin = criteriaBuilder.equal(joinTableA.<String>get("column_1"), tableA.<String>get("column_1"));