jpa - 如何在 JPA 中正确执行多对多连接表?

标签 jpa jakarta-ee ejb

我需要 3 个实体:User、Contract(它们是多对多关系)和一个中间实体:UserContract(需要它来存储一些字段)。

我想知道的是在 JPA/EJB 3.0 中定义这些实体之间关系的正确方法,以便操作(持久化、删除等)正常进行。

例如,我想创建一个用户及其契约(Contract),并以一种简单的方式持久化它们。

目前我拥有的是: 在 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;

这是实现我目标的最佳方式吗?

最佳答案

一切看起来都很好。我的建议是在 @EmbeddedId 之上使用 @MappedSuperclass:

@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;
   }

 }

为了可读性,我省略了明显的构造函数/setter。然后你可以定义 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)共享主键实现。

关于jpa - 如何在 JPA 中正确执行多对多连接表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/675519/

相关文章:

java - 如何使用JSP/Servlet将文件上传到服务器?

mysql - 获取应用程序必须提供 JDBC 连接异常

java - 使用 JNA 和 Windows sendMessage API 从基于 java 的 Web 应用程序更改 Windows XP 中的焦点窗口

java - cdi 生产者是否具有类范围

java - EJB 中如何实现事务概念

jakarta-ee - 如何为嵌入式 EJB 容器定义测试数据源

singleton - EJB-@Singleton 管理查询结果

java - Spring数据存储库查询包含的集合

java - 与 JPA 注释的双向 @OneToMany 关系似乎不起作用

java - JPA 使用 SELECT 连接表