3

User、Contract (多対多の関係) と中間エンティティの 3 つのエンティティが必要です: UserContract (これはいくつかのフィールドを格納するために必要です)。

私が知りたいのは、JPA/EJB 3.0 でこれらのエンティティ間の関係を定義して、操作 (永続化、削除など) が正常に行われるようにする正しい方法です。

たとえば、ユーザーとそのコントラクトを作成し、それらを簡単な方法で保持したいと考えています。

現在私が持っているのはこれです: User.java:

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

Contract.java で:

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

そして私の UserContract.java:

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

@ManyToOne(optional = false)
private User user;

@ManyToOne(optional = false)
private Contract contract;

そして私のUserContractPK:

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

@Column(nullable = false)
private String email;

これは私の目標を達成するための最良の方法ですか?

4

1 に答える 1

2

すべてが正しく見えます。私のアドバイスは、@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 などの他の多対多結合エンティティの主キー実装を共有できます。

于 2009-03-25T21:41:02.633 に答える