@OneToMany JPA 关系指向相同 Class

@OneToMany JPA Relationships toward the same Class

我正在构建一个简单的 Spring 应用程序,我需要帮助来为某些 JPA 实体找到正确的设计,这是我遇到的情况:

My goal : I want to be able to add actions to a specific resource, or list all the actions done on a resource for example.

4个实体是(FirstResource、SecondResource、ThirdResource、Action),它们应该是这样的吗? :

@Entity
public class Action implements Serializable {

    @Id @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long idAction;
    private String nameAction; // + gettes & setters...
}

@Entity
public class FirstResource implements Serializable {

    @Id @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long idFirstResource;
    private int unitNumber; // + gettes & setters...
}

@Entity
public class SecondResource implements Serializable {

    @Id @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long idSecondResource;
    private String nameSecondResource; // + gettes & setters...
}

@Entity
public class ThirdResource implements Serializable {

    @Id @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long idThirdResource;
    private boolean Confirmed; // + gettes & setters...
}

那么 class Action 是否应该对每个 Resources 都使用 @ManyToOne 注释的引用?如果是,是否有更好的方法来做到这一点?

您可以使用继承。

将抽象 class AbstractResource 定义为实体:

@Entity
public abstract class AbstractResource implements Serializable {
  @Id @GeneratedValue
  private long id;

  @OneToMany
  private List<Action> actions;
...
}

然后确保您的资源 class 扩展 AbstractResource :

@Entity
public class FirstResource extends AbstractResource

然后您可以在 Action 实体中引用您的资源:

@Entity
public class Action implements Serializable {

    @Id @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long idAction;

    @ManyToOne
    private AbstractResource resource;
 ...
}

由于您不能将 MappedSuperClass 与 ManyToOne 关系一起使用,因此您不能在您的情况下使用 @MappedSuperClass。