簡體   English   中英

org.hibernate.id.IdentifierGenerationException:“試圖從空一對一屬性分配 id”

[英]org.hibernate.id.IdentifierGenerationException: "attempted to assign id from null one-to-one property"

當我嘗試使用 Spring Boot 2.1.6.RELEASE 和 Spring Data JPA 將用戶對象保存到數據庫時遇到問題。

  1. 用戶對象和詳細信息對象具有雙向的一對一關系。
  2. detail 的 id 有一個外鍵指向用戶的 id(用戶的 id 是自動遞增的)。
  3. 用戶信息從 json 格式映射到帶有@RequestBody 的對象。

json:

{"name" : "Jhon",
    "detail":
    {
        "city" : "NY"
    }
}

用戶控制器.java:

...
@PostMapping(value="/user")
public Boolean agregarSolicitiud(@RequestBody User user) throws ClassNotFoundException, InstantiationException, IllegalAccessException
{
    userRepository.save(user);
...

用戶.java:

...
@Entity
public class User {

    @Id
    @Column(updatable=false, nullable=false, unique=true)
    @GeneratedValue(strategy=GenerationType.IDENTITY)
    private Long id;

    @Column
    private String name;

    @OneToOne(mappedBy =     "solicitud",optional=false,cascade=CascadeType.ALL)
    private UserDetail userDetail;
}

用戶詳細信息.java:

...
@Entity
public class UserDetail {

    @Id
    @Column
    private Long id;

    @Column
    private String city;

    @MapsId
    @OneToOne(optional = false,cascade = CascadeType.ALL)
    @JoinColumn(name = "id", nullable = false)
    private User user;
}

用戶存儲庫.java

...
@Repository
public interface UserRepository extends JpaRepository<User, Long> {
}
...

錯誤:

 org.hibernate.id.IdentifierGenerationException: attempted to assign id from null one-to-one property [proyect.model.Detail.user]

我能做什么?

謝謝

通過關注這篇文章,我可以保存這兩個實體。

https://vladmihalcea.com/the-best-way-to-map-a-onetoone-relationship-with-jpa-and-hibernate/

把這看作是在不使用持久化提供程序的情況下設置兩個 java 類之間的關系。這些屬性需要由開發人員手動設置,以便它可以從他想要的方向訪問關系。

需要將此代碼添加到適當綁定用戶詳細信息的用戶實體中

    public void setUserDetail(UserDetail userDetail) {
      if (userDetail == null) {
            if (this.userDetail != null) {
                this.userDetail.setUser(null);
            }
        } else {
            userDetail.setUser(this);
        }
        this.userDetail = userDetail;
    }
````
This code sets the user to the userDetails which is causing the issue.

As mentioned in the comments the deserializer is not able to bind the objects properly.The above code will binds the userDetails.user.


暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM