Home JPA: Unidirectional one-to-many relationship with composite semi-shared primary key without join table
Reply: 1

JPA: Unidirectional one-to-many relationship with composite semi-shared primary key without join table

ronin667
1#
ronin667 Published in 2017-12-05 15:21:55Z

JPA:

How can I model the following in JPA:

  • a uni-directional one-to-many relationship
  • where the owning entity has a single-column application-determined primary key AND
  • where the child entity has a composite primary key AND
  • where one part of the child's primary key is the parent's primary key AND
  • avoiding JPA generating a join table.

Any ideas?

ronin667
2#
ronin667 Reply to 2017-12-09 15:35:31Z

I figured out myself how to do this.

  • You need to annotate the foreign key in the owning entity with

    @OneToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER)
    @JoinColumn(name = "myId", referencedColumnName = "parentId")
    private List<ChildEntity> childEntity;
    
  • The primary key part in the child entity that is also the foreign key referencing the owning entity must not be annotated as being a foreign key, so e.g.:

    @Id
    private String parentId;
    
  • The usual rules concerning composite primary keys apply for the child class (primary key class annotated with @Embeddable etc.)

  • As user DN1 commented, the @JoinColumn annotation must be used, but it must be specified at the foreign reference in the owning class.

  • For some reason, you also must not use @PrimaryKeyJoinColumn instead of @JoinColumn, otherwise JPA will generate join tables.

Another challenge would be that the owning class's primary is also composite, but I haven't tried that.

You need to login account before you can post.

About| Privacy statement| Terms of Service| Advertising| Contact us| Help| Sitemap|
Processed in 0.322253 second(s) , Gzip On .

© 2016 Powered by mzan.com design MATCHINFO