我必须使用JPA将两个表与ManyToOne关系连接起来。
表1-> manF
@Entity
@Table(name = "manf")
public class ManF {
@EmbeddedId
private ManFCompositeKey manFCompositeKey;
@Column(name = "name", length = 10)
private String manFName;
@Column(name = "desc", length = 150)
private String manFDesc;
}
@Embeddable
public class ManFCompositeKey {
@Column(name = "man_code", length = 20, nullable = false)
private String manCode;
@Column(name = "update_time", nullable = false)
private Date updTime;
}
表2->产品
@Entity
@Table(name = "products")
public class Prod {
@EmbeddedId
private ProdCompositeKey prodCompositeKey;
@Column(name = "name", length = 10)
private String prodName;
@Column(name = "prod_desc", length = 150)
private String prodDesc;
// -> JoinColumn here.
@Column(name = "man_code", length = 20, nullable = false)
private String manCode;
}
@Embeddable
public class ProdCompositeKey {
@Column(name = "prod_code", length = 20, nullable = false)
private String prodCode;
@Column(name = "update_time", nullable = false)
private Date updTime;
}
现在,manF(表1)可以有很多产品(表2)。因此,对于产品表中的每一行,可以有相同的manFCode。
我打算建立一个连接b / w T1和T2,以使产品中的manCode列充当该表的FK,引用了表1的man_code。
下面是我写的联接条件:
@ManyToOne(fetch = FetchType.LAZY, optional = false)
@JoinColumns({
@JoinColumn(name = "man_code", referencedColumnName = "man_code")
})
@Column(name = "man_code", length = 20, nullable = false)
private ManF manF;
这应该是有道理的(我认为),但是抛出一个错误,指出:ManF没有映射到单个属性。
现在,我可以这样做:
@ManyToOne(fetch = FetchType.LAZY, optional = false)
@JoinColumns({
@JoinColumn(name = "man_code", referencedColumnName = "man_code")
@JoinColumn(name = "update_time", referencedColumnName = "update_time")
})
@Column(name = "man_code", length = 20, nullable = false)
private ManF manF;
但是随后,我将保留插入ManF的时间的FK参考。
我需要知道如何在这里连接两个表,以便可以在ManF表的man_code和product(子)表中的man_code上创建FK引用。
最佳答案
您可以使用休眠native query并编写连接条件。如果这不是一个选择,我会特别将Manf上的EmbeddedId更改为常规ID,并在您的数据库中创建约束,以使用常规joincolumn条件维护完整性。像这样:
SQL:ALTER TABLE'manf'添加唯一的'UNIQUE_CONSTRAINT'('man_code','update_time');
@Entity
@Table(name = "manf")
public class ManF {
@Id
@SequenceGenerator(name = "SEQUENCE_NAME", sequenceName = "SEQUENCE_NAME", allocationSize = 1, initialValue = 1)
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "SEQUENCE_NAME")
@Column(name = "man_code", length = 20, nullable = false)
private String manCode;
@Column(name = "update_time", nullable = false)
private Date updTime;
@Column(name = "name", length = 10)
private String manFName;
@Column(name = "desc", length = 150)
private String manFDesc;
}
@Entity
@Table(name = "products")
public class Prod {
@EmbeddedId
private ProdCompositeKey prodCompositeKey;
@Column(name = "name", length = 10)
private String prodName;
@Column(name = "prod_desc", length = 150)
private String prodDesc;
@ManyToOne(fetch = FetchType.LAZY, optional = false)
@JoinColumn(name = "man_code")
private ManF manF;
}