基础和子类上的多个hibernate @Id注释

时间:2017-05-31 10:53:59

标签: hibernate spring-data-jpa

我正在使用spring boot(1.5.2.RELEASE)和hibernate-core(5.2.9.Final)

我有两个类(getters,setter,构造函数被省略)和DB中的适当表(USERS表有3列,USERS_HISTORY有6列)

  public class User implements Serializable {
    private static final long serialVersionUID = 1L;

    private Long id;
    private String firstName;
    private String lastName;
  }

  public class UserHistory extends User implements Serializable {
    private static final long serialVersionUID = 1L;

    private Long hstId;
    private Instant hstTimestamp;
    private String changedBy;
  }

如何使用@Id注释注释User.id和UserHistory.hstId?

我无法仅注释User.id,因为一个用户可以在历史记录表中拥有多行。

当我调用userRepository.findOne(Long id)时,我想用User.id选择User行,当我调用userHistoryRepository.findOne(Long hstId)时,我想用UserHistory.hstId选择UserHistory行。

UserHistoryRepository和UserRepository都扩展了Spring Data JPA CrudRepository。

我目前的解决方案基于三个类,但我试图仅根据两个类找到解决方案。

我目前的解决方案如下:

  public class UserBase implements Serializable {
    private static final long serialVersionUID = 1L;

    private String firstName;
    private String lastName;
  }

  public class User extends UserBase implements Serializable {
    private static final long serialVersionUID = 1L;

    @Id
    Long id;
  }

  public class UserHistory extends UserBase implements Serializable {
    private static final long serialVersionUID = 1L;

    @Id
    private Long hstId;
    private Instant hstTimestamp;
    private String changedBy;
    private Long id;

    //constructor sets this.id = User.id
    public UserHistory(Long hstId, Instant hstTimestamp, String changedBy, User user) {
      //other lines omitted
      this.id = user.id;
    }
  }

1 个答案:

答案 0 :(得分:0)

在您的情况下,UserHistory不应延伸User

使用One to Many关系,因为一个用户可以在历史记录表中拥有多行