@OneToMany and composite primary keys?

前端 未结 9 1739
温柔的废话
温柔的废话 2020-12-01 03:31

I\'m using Hibernate with annotations (in spring), and I have an object which has an ordered, many-to-one relationship which a child object which has a composite primary key

9条回答
  •  陌清茗
    陌清茗 (楼主)
    2020-12-01 04:15

    The Manning book Java Persistence with Hibernate has an example outlining how to do this in Section 7.2. Fortunately, even if you don't own the book, you can see a source code example of this by downloading the JPA version of the Caveat Emptor sample project (direct link here) and examining the classes Category and CategorizedItem in the auction.model package.

    I'll also summarize the key annotations below. Do let me know if it's still a no-go.

    ParentObject:

    @Entity
    public class ParentObject {
       @Id @GeneratedValue
       @Column(name = "parentId", nullable=false, updatable=false)
       private Long id;
    
       @OneToMany(mappedBy="parent", fetch=FetchType.EAGER)
       @IndexColumn(name = "pos", base=0)
       private List attrs;
    
       public Long getId () { return id; }
       public List getAttrs () { return attrs; }
    }
    

    ChildObject:

    @Entity
    public class ChildObject {
       @Embeddable
       public static class Pk implements Serializable {
           @Column(name = "parentId", nullable=false, updatable=false)
           private Long objectId;
    
           @Column(nullable=false, updatable=false)
           private String name;
    
           @Column(nullable=false, updatable=false)
           private int pos;
           ...
       }
    
       @EmbeddedId
       private Pk id;
    
       @ManyToOne
       @JoinColumn(name="parentId", insertable = false, updatable = false)
       @org.hibernate.annotations.ForeignKey(name = "FK_CHILD_OBJECT_PARENTID")
       private ParentObject parent;
    
       public Pk getId () { return id; }
       public ParentObject getParent () { return parent; }
    }
    

提交回复
热议问题