Spring Boot / Hibernate:如何定义一对一的单向关系

时间:2016-10-12 14:13:12

标签: java hibernate curl spring-boot

我的People实体有nameparent,其中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,如:< / p>

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

当我检索存储的内容时,parent已经有一个指向对象本身的链接,尽管我在发出null请求时已通过curl

我对Hibernate 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"
    }
  }
}

1 个答案:

答案 0 :(得分:0)

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

通过阅读您的代码,我认为您需要@JoinColumn

请参阅Hibernate self-referencing one-to-one relationship - mapped/owned side