How to make multi-headed connection in JPA?

I need 3 entities: User, Contract (many to large) and middle object: UserContract (this is necessary to store some fields).

What I want to know is the correct way to define the relationships between these objects in JPA / EJB 3.0 so that operations (persist, delete, etc.) are in order.

For example, I want to create a user and his contracts and save them in a simple form.

I currently have the following: In User.java:

@OneToMany(mappedBy = "user", fetch = FetchType.LAZY)
    private List<UserContract> userContract;

In Contract.java:

@OneToMany(mappedBy = "contract", fetch = FetchType.LAZY)
private Collection<UserContract> userContract;

And my UserContract.java:

@Entity
public class UserContract {
@EmbeddedId
private UserContractPK userContractPK;

@ManyToOne(optional = false)
private User user;

@ManyToOne(optional = false)
private Contract contract;

And my UserContractPK:

@Embeddable
public class UserContractPK implements Serializable {
@Column(nullable = false)
private long idContract;

@Column(nullable = false)
private String email;

Is this the best way to achieve my goals?

+3
source share
1 answer

. - @MappedSuperclass @EmbeddedId:

@MappedSuperclass
public abstract class ModelBaseRelationship implements Serializable {

@Embeddable
public static class Id implements Serializable {

    public Long entityId1;
    public Long entityId2;

    @Column(name = "ENTITY1_ID")
    public Long getEntityId1() {
        return entityId1;
    }

    @Column(name = "ENTITY2_ID")
    public Long getEntityId2() {
        return entityId2;
    }

    public Id() {
    }

    public Id(Long entityId1, Long entityId2) {
        this.entityId1 = entityId1;
        this.entityId2 = entityId2;
    }

   }

   protected Id id = new Id();

   @EmbeddedId
   public Id getId() {
        return id;
   }

   protected void setId(Id theId) {
        id = theId;
   }

 }

/ . UserContract

@Entity
@AttributeOverrides( {
        @AttributeOverride(name = "entityId1", column = @Column(name = "user_id")),
        @AttributeOverride(name = "entityId2", column = @Column(name = "contract_id"))
})
public class UserContract extends ModelBaseRelationship {

, "--", UserContract.

+2

Source: https://habr.com/ru/post/1705215/


All Articles