简体   繁体   中英

Relationship table mapped as entity in JPA

I'm trying to map one specific many to many table on my database as an entity in JPA (cause I have some specific attributes on my relationship table and I wanted to retrieve this as the class attributes two). But having issues while declaring the IDs.

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

The application starts successfully but when I try to map some repository to manage this table, Hibernate throws an error:

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

How can I use the JPA entity annotation to manage this relationship table? Is it possible?

I cannot simply declare one property in the user class of Plan model and mark it as @ManyToMany, cause the plan table does not have the property that I need to execute some operations, which are declared on UserPlan class, also I cannot move these properties to Plan class, cause the Plan table is just a template of a plan, and the UserPlan have all the specific data (billingDay, billingType and planStatus).

JPA supports relationship tables as a Java class? Or it can be mapped only as a property?

Thanks

You are using multiple @Id annotations. To do so you need to create PrimaryKey class:

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

And you need to add @IdClass(PrimaryKey.class) annotation to your entity class.

If you have a Repository don't forget to change id type to PrimaryKey:

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

Also check this question

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM