JPA @JoinColumn one to many bi-directional relationship with a composite key as FK

自作多情 提交于 2019-12-25 08:23:16

问题


I have been scratching my head over this for weeks now and I have no idea how to work my way around it.

I have two tables:

  • Author (author_code, author_number, author_name) author_code and author_number are primary keys
  • Title (author_code, title_code, sequence, title_desc) title_code and sequence are primary keys

Code:

        @Entity
        @IdClass(AuthorPK.class)
        @Table(name="Author")
        public class Author implements Serializable {

            @Id
            @Column(name="author_code")
            private long authorCode;

            @Id
            @Column(name="author_number")
            private String authorNumber;

            @Column(name="author_name")
            private String authorName;

            //bi-directional many-to-one association to Title
            @OneToMany(mappedBy="author")
            private List<Title> titles;

            //getter setters
        }

        public class AuthorPK implements Serializable {

                private long authorCode;

                private String authorNumber;

                //getter equals() hashCode()
        }



    @Entity
    @IdClass(TitlePK.class)
    @Table(name="Title")
    public class Title implements Serializable {

        @Id
        @Column(name="title_code")
        private long titleCode;

        @Id
        @Column(name="sequence")
        private long sequence;

        @Column(name="title_desc")
        private String titleDesc;

        //bi-directional many-to-one association to Author
        @ManyToOne
        @JoinColumns({
            @JoinColumn(name="author_code", referencedColumnName="author_code"),
            @JoinColumn(name="author_number", referencedColumnName="author_number")
        })
        private Author author;

    //getters setters
    }

public class TitlePK implements Serializable {

    private long titleCode;

    private long sequence;

//getter equals() hashcode()
}

I need to link the two entities via author_code but JPA requires me to include both IDs in the @JoinColumn... it's throwing errors on my application since the source table doesn't have the other column. Is there another way for me to join these entities?

来源:https://stackoverflow.com/questions/42245223/jpa-joincolumn-one-to-many-bi-directional-relationship-with-a-composite-key-as

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