JPA - Using composite PK's and FK's and defining relationships

穿精又带淫゛_ 提交于 2020-01-07 04:58:07

问题


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.


回答1:


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.



来源:https://stackoverflow.com/questions/7995681/jpa-using-composite-pks-and-fks-and-defining-relationships

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!