簡體   English   中英

Spring Boot / Hibernate:如何定義一對一的單向關系

[英]Spring Boot/Hibernate: How to define one-to-one unidirectional relationship

我有具有nameparent People實體,其中parentPeople

@Entity
public class People {

    @Id
    private Long id;

    @Column
    @NotNull(message = "error.name.type.null")
    private String name;

    @OneToOne(cascade=CascadeType.ALL,fetch = FetchType.EAGER)
    private People parent;

    // getters and setters
}

當我使用PUT存儲數據時,我將id 1指定為路徑變量,並提供name作為數據輸入,並且沒有像下面那樣傳遞parent

curl -i -X PUT -H "Content-Type:application/json" -d '{"name":"John"}'

響應

http://localhost:8080/people/1
HTTP/1.1 200 
Content-Type: application/json;charset=UTF-8
Transfer-Encoding: chunked
Date: Wed, 12 Oct 2016 13:51:52 GMT

當我檢索存儲的內容時,盡管我在發出curl請求時傳遞了null ,但parent已經具有指向對象本身的鏈接。

休眠One-to-One關系在做什么?

curl -i -X GET http://localhost:8080/people
HTTP/1.1 200 
Content-Type: application/hal+json;charset=UTF-8
Transfer-Encoding: chunked
Date: Wed, 12 Oct 2016 13:53:10 GMT

{
  "_embedded" : {
    "people" : [ {
      "name" : "John",
      "_links" : {
        "self" : {
          "href" : "http://localhost:8080/people/1"
        },
        "people" : {
          "href" : "http://localhost:8080/people/1"
        },
        "parent" : {
          "href" : "http://localhost:8080/people/1/parent"
        }
      }
    } ]
  },
  "_links" : {
    "self" : {
      "href" : "http://localhost:8080/people"
    },
    "profile" : {
      "href" : "http://localhost:8080/profile/people"
    },
    "search" : {
      "href" : "http://localhost:8080/people/search"
    }
  }
}

您缺少@JoinColumn(name="parent_id")@OneToOne(mappedBy="id", cascade=CascadeType.ALL,fetch = FetchType.EAGER)

通過閱讀您的代碼,我認為您需要@JoinColumn

請參見Hibernate自引用一對一關系-映射/擁有的一面

暫無
暫無

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

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