【问题标题】:Relationship table mapped as entity in JPA在 JPA 中映射为实体的关系表
【发布时间】:2021-07-26 02:32:47
【问题描述】:

我试图在我的数据库中将一个特定的多对多表映射为 JPA 中的一个实体(因为我的关系表上有一些特定的属性,我想将其作为类属性二检索)。但是在声明 ID 时遇到问题。

@Data
@EqualsAndHashCode(onlyExplicitlyIncluded = true)
@Entity
@Table(name = "user_plan")
public class UserPlan implements Serializable {
    
    private static final long serialVersionUID = 1L;

    @Id
    @OneToOne
    private User user;

    @Id
    @OneToOne
    private Plan plan;
    
    private Integer billingDay;
    
    @Enumerated(EnumType.STRING)
    private BillingType billingType;

    @Enumerated(EnumType.STRING)
    private PlanStatus planStatus;
}

应用程序启动成功,但是当我尝试映射某个存储库来管理此表时,Hibernate 抛出错误:

java.lang.IllegalArgumentException: This class [class com.demo.domain.model.UserPlan] does not define an IdClass

如何使用 JPA 实体注解来管理这个关系表?有可能吗?

我不能简单地在Plan模型的用户类中声明一个属性并将其标记为@ManyToMany,因为计划表没有我需要执行一些操作的属性,这些属性是在UserPlan类上声明的,我也无法将这些属性移动到Plan 类,因为计划表只是计划的模板,UserPlan 具有所有特定数据(billingDay、billingType 和 planStatus)。

JPA 支持将关系表作为 Java 类吗?还是只能映射为属性?

谢谢

【问题讨论】:

  • 请注意,最佳实践在实体类上使用@Data@EAHC,特别是因为定义“实体”的定义不同于任何其数据值。

标签: java jpa


【解决方案1】:

您正在使用多个 @Id 注释。为此,您需要创建 PrimaryKey 类:

public class PrimaryKey implements Serializable {
    private User user;
    private Plan plan;
    
    // Getter and Setter
}

并且你需要在你的实体类中添加@IdClass(PrimaryKey.class)注解。

如果您有Repository,请不要忘记将 id 类型更改为 PrimaryKey:

public interface YourRepository
             extends SomeRepositoryInterface<UserPlan, PrimaryKey> {
    //...
}

也可以查看question

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-02-14
    • 2010-12-28
    • 2011-07-13
    • 2011-07-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-10-03
    相关资源
    最近更新 更多