@OneToMany and composite primary keys?

前端 未结 9 1696
温柔的废话
温柔的废话 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条回答
  •  -上瘾入骨i
    2020-12-01 04:18

    Found this question searching for the answer to it's problem, but it's answers didn't solve my problem, because I was looking for @OneToMany which isn't as good of a fit for the table structure I was going after. @ElementCollection is the right fit in my case. One of the gotchas of it I believe though is that it looks at the entire row of relations as being unique, not just the rows id.

    @Entity
    public class ParentObject {
    @Column(nullable=false, updatable=false)
    @Id @GeneratedValue(generator="...")
    private String id;
    
    @ElementCollection
    @CollectionTable( name = "chidren", joinColumns = @JoinColumn( name = "parent_id" ) )
    private List attrs;
    
    ...
    }
    
    @Embeddable
    public static class ObjectChild implements Serializable {
        @Column(nullable=false, updatable=false)
        private String parentId;
    
        @Column(nullable=false, updatable=false)
        private String name;
    
        @Column(nullable=false, updatable=false)
        private int pos;
    
        @Override
        public String toString() {
            return new Formatter().format("%s.%s[%d]", parentId, name, pos).toString();
        }
    
        ... getters and setters REQUIRED (at least they were for me)
    }
    

提交回复
热议问题