我试图在我的数据库中映射一个特定的多对多表作为 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,因为计划表没有我需要执行某些操作的属性,这些操作是在{{上声明的1}} 类,我也不能将这些属性移动到 UserPlan
类,因为计划表只是计划的模板,而 Plan
具有所有特定数据(billingDay、billingType 和 planStatus) .
JPA 支持关系表作为 Java 类?还是只能映射为属性?
谢谢
答案 0 :(得分:2)
您正在使用多个 @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