繁体   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