将从父方获取的ID-休眠一对一关系

时间:2018-09-30 10:11:06

标签: java jpa

我有一个UserAccountEntity类,它与UserEntity一一对应:

@Entity
@Table(name = "user_entity")
public class UserEntity implements Serializable {

    private static final long serialVersionUID = 2059380022311094257L;

    @Id
    @GeneratedValue(generator = RandomAlphanumericIdGenerator.generatorName)
    @GenericGenerator(name = RandomAlphanumericIdGenerator.generatorName, strategy = "com.myproject.project.core.utils.RandomAlphanumericIdGenerator")
    private String id;

    public UserEntity() {}

}

@Entity
@Table(name="user_account_entity")
public class UserAccountEntity implements UserDetails {

    @Id
    private String id;

    @MapsId
    @OneToOne(cascade = CascadeType.ALL, fetch = FetchType.LAZY)
    private UserEntity user;
}

现在,我想添加另一个类UserAccountActivityCode,该类应该与UserAccountEntity一一对应。我感到困惑的是UserAccountEntity的ID是在UserEntity中生成的。我想知道应该如何定义其ID?

我创建了一个课程UserAccountActivityCode

@Entity
@Table(name = "User_account_activity_code")
public class UserAccountActivityCode implements Serializable {

    @Id
    @GeneratedValue(generator = RandomAlphanumericIdGenerator.generatorName)
    @GenericGenerator(name = RandomAlphanumericIdGenerator.generatorName, strategy = "com.myproject.project.core.utils.RandomAlphanumericIdGenerator")
    private String id;

    public UserAccountActivityCode() {}

}

但是我应该如何在UserAccountEntity类中引用它?在这种情况下,UserAccountEntity从何处获取ID?

更新1: 我从GeneratedValue中取出了UserAccountActivityCodeEntity,并添加了setUserId来进行保存:

@Entity
@Table(name="user_account_activity_code_entity")
public class UserAccountActivityCodeEntity {

    private final static int ACTIVITY_CODE_LENGTH = 6;

    @Id
    private String userId;

    private String acitivityCode;
    public UserAccountActivityCodeEntity(String id) {
        this.acitivityCode = RandomStringUtils.randomAlphanumeric(ACTIVITY_CODE_LENGTH);
        this.userId = id;
    }

    public String getUserId() {
        return userId;
    }
    public void setUserId(String userId) {
        this.userId = userId;
    }
    public String getAcitivityCode() {
        return acitivityCode;
    }
    public void setAcitivityCode(String acitivityCode) {
        this.acitivityCode = acitivityCode;
    }

}

在服务层中有以下代码:

    userAccount = new UserAccountEntity(username,
            passwordEncoder.encode(password));
    userAccount.setUser(new UserEntity());
    UserAccountActivityCodeEntity activityCode = new UserAccountActivityCodeEntity(userAccount.getId());
    userAccount.setActivityCode(activityCode);
    userAccountRepository.save(userAccount);

哪个会导致此错误:

org.hibernate.id.IdentifierGenerationException: ids for this class must be manually assigned before calling save(): com.myproject.project.core.entity.useraccount.UserAccountActivityCodeEntity

0 个答案:

没有答案