【问题标题】:IdentifierGenerationException: attempted to assign id from null one-to-one property + @MapsId + OneToOne bidirectionalIdentifierGenerationException:试图从 null 一对一属性 + @MapsId + OneToOne 双向分配 id
【发布时间】:2021-10-14 08:03:07
【问题描述】:

我遇到了错误

org.hibernate.id.IdentifierGenerationException: 试图从空的一对一属性分配 id。

代码sn-ps:

用户.java

@Entity
@Table(schema = "public", name = "user_01")
public class User {

    @Id
    @GeneratedValue(generator = "UUID")
    @GenericGenerator(name = "UUID", strategy = "org.hibernate.id.UUIDGenerator")
    @Column(name = "id", updatable = false, nullable = false)
    private UUID id;    
    
    @OneToOne(cascade = CascadeType.ALL)
    @PrimaryKeyJoinColumn
    @JoinColumn(name = "user")
    private UserInformation userInformation;

用户信息.java

@Entity
@Table(schema = "public", name = "user_information_06")
public class UserInformation {

    @Id
    @Column(name = "id")
    private UUID id;    
    
    @MapsId
    @OneToOne(mappedBy = "userInformation")
    private User user;

用户信息服务.java

// CREATE
public UserInformationBean createUserInformation(UserInformationBean userInformationBean) {
    if(userInformationBean == null || userInformationBean.getUserId() == null)
        return null;

    User user = userRepository.findById(userInformationBean.getUserId()).orElse(null);
    if(user == null)
        return null;
    
    UserInformation userInformation = user.getUserInformation();
    if(userInformation != null) {
        System.err.println("User Information exists !! " + userInformation.getId());
        return null;
    }
    
    userInformation = new UserInformation();        
    userInformation.setFirstname(userInformationBean.getFirstname());
    userInformation.setLastname(userInformationBean.getLastname());
    userInformation.setGender(userInformationBean.getGender());
    userInformation.setDateOfBirth(userInformationBean.getDateOfBirth());
    userInformation.setProfession(userInformationBean.getProfession());
    userInformation.setUpdatedOn(Timestamp.valueOf(LocalDateTime.now()));
    
    user.setUserInformation(userInformation);
    userInformation.setUser(user);
    
    user = userRepository.save(user);
    
    return userInformation.toBean();
}

【问题讨论】:

    标签: jpa-2.0 one-to-one bidirectional


    【解决方案1】:

    更改以下内容后:

    user = userRepository.save(user);
    

    收件人:

    userInformation = userInformationRepository.save(userInformation);
    

    效果很好!还是想知道不能通过User实体持久化的原因和原因。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-06-21
      • 1970-01-01
      • 1970-01-01
      • 2021-01-16
      • 2021-12-25
      • 2021-01-23
      • 2019-11-28
      • 1970-01-01
      相关资源
      最近更新 更多