JPA - 使用复合PK和FK并定义关系 [英] JPA - Using composite PK's and FK's and defining relationships
问题描述
@ javax.persistence.Entity
public class Book {
@ javax.persistence.EmbeddedId
私人BookPK ID;
私有字符串标题;
@ javax.persistence.ManyToOne(fetch = javax.persistence.FetchType.LAZY)
@ javax.persistence.JoinColumns({
@ javax.persistence.JoinColumn(name = LNGCOD,referencedColumnName =LNGCOD),
@ javax.persistence.JoinColumn(name =LIBCOD,referencedColumnName =LIBCOD)})
private语言语言;
@ javax.persistence.Entity
public class Language {
@ javax.persistence.EmbeddedId
private LanguagePK id;
私人字符串名称;
}
带有组成的PK:
@Embeddable
公共类BookPK实现Serializable {
私有Integer bookcod;
private Integer libcod;
}
@Embeddable
public class LanguagePK实现Serializable {
private Integer lngcod;
private Integer libcod;
$ b如果我尝试创建一个新书并坚持它,我会得到一个异常告诉我libcod在插入语句中发现两次(Column'libcod'指定两次)。但是,在定义JoinColumn时,我不能使用insertable = false(在属性中混合插入和不可插入列是不允许的)。
有没有方法来定义这些对象+关系,这样列由Hibernate自动管理? (我特别想到libcod)。
谢谢。
解决方案创建第三个属性Integer libcod;在书上。让该属性管理libcod的db状态。对连接语言中的两个属性使用insertable = false,updatable = false。在你的setLanguage中设置private libcod = language.libcod。不要为私有libcod公开一个getter / setter。
是否在插入时生成任何值?这可能会使事情进一步复杂化,我想。
I got these 2 entities:
@javax.persistence.Entity
public class Book {
@javax.persistence.EmbeddedId
private BookPK id;
private String title;
@javax.persistence.ManyToOne(fetch = javax.persistence.FetchType.LAZY)
@javax.persistence.JoinColumns({
@javax.persistence.JoinColumn(name = "LNGCOD", referencedColumnName = "LNGCOD"),
@javax.persistence.JoinColumn(name = "LIBCOD", referencedColumnName = "LIBCOD") })
private Language language;
}
@javax.persistence.Entity
public class Language {
@javax.persistence.EmbeddedId
private LanguagePK id;
private String name;
}
with composed PK's:
@Embeddable
public class BookPK implements Serializable {
private Integer bookcod;
private Integer libcod;
}
@Embeddable
public class LanguagePK implements Serializable {
private Integer lngcod;
private Integer libcod;
}
If I try to create a new Book and persist it, I get an exception telling me libcod is found twice in the insert statement ("Column 'libcod' specified twice"). But I can't use "insertable = false" when defining the JoinColumn ("Mixing insertable and non insertable columns in a property is not allowed").
Is there any way to define these objects + relationship so the columns are managed automatically by Hibernate ? (I am especially thinking of libcod).
Thank you.
解决方案 Create a third property "Integer libcod;" on the Book. Have that property manage the db state of libcod. Use insertable=false,updatable=false for both properties in the join to Language. in your "setLanguage" set the private libcod = language.libcod. don't expose a getter/setter for the private libcod.
Are any of the values generated at insert time? This could complicate things further, I suppose.
这篇关于JPA - 使用复合PK和FK并定义关系的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!