我有一个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