java - Spring Data REST - 检测到具有相同关系类型的多个关联链接

标签 java hibernate orm spring-data-jpa spring-data-rest

我正在尝试做一个简单的 Spring 应用程序。它需要公开 REST 端点并将其保存到关系数据库。

我拿了你的示例项目,http://spring.io/guides/gs/accessing-data-rest/ .我能够执行您的指南中提到的所有操作(POST、PATCH、PUT、GET)。

但是我尝试创建添加关系到 Person 实体类,但事情开始分崩离析。

@Entity
public class Person {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private long id;

    private String firstName;
    private String lastName;

    @OneToOne(cascade = {CascadeType.ALL})
    private PersonDetails personDetails;

    @OneToOne(cascade = {CascadeType.ALL})
    private PersonChildren personChildren;

     ///Getter and setters for everything except id.
}


@Entity
public class PersonChildren {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private long id;

    private String childFirstName;
    private String childLastName;

    @OneToOne(mappedBy="personChildren", optional=false)
    private Person person;

///Getter and setters for everything except id.
}


@Entity
public class PersonDetails {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private long id;

    private String email;
    private String phoneNumber;

    @OneToOne(mappedBy="personDetails",optional=false)
    private Person person;

///Getter and setters for everything except id.
}


@RepositoryRestResource(collectionResourceRel = "people", path = "people")
public interface PersonRepository extends PagingAndSortingRepository<Person, Long> {

    List<Person> findByLastName(@Param("name") String name);

}

build.gradle

buildscript {
    repositories {
        maven { url "http://repo.spring.io/libs-release" }
        mavenLocal()
        mavenCentral()
    }
    dependencies {
        classpath("org.springframework.boot:spring-boot-gradle-plugin:1.1.1.RELEASE")
    }
}

apply plugin: 'java'
apply plugin: 'eclipse'
apply plugin: 'idea'
apply plugin: 'spring-boot'

jar {
    baseName = 'gs-accessing-data-rest'
    version = '0.1.0'
}

repositories {
    mavenLocal()
    mavenCentral()
    maven { url "http://repo.spring.io/libs-release" }
}

dependencies {
    compile("org.springframework.boot:spring-boot-starter-web")
    compile("org.springframework.boot:spring-boot-starter-data-jpa")
    compile("com.h2database:h2")
    compile("org.springframework.data:spring-data-rest-webmvc")
}

task wrapper(type: Wrapper) {
    gradleVersion = '1.11'
}

调用:

$ curl -i -X POST -H "Content-Type:application/json" -d '{ "firstName":"John", "lastName": "Doe", "personDetails": { "email": "john@gmail.com", "phoneNumber": "001-002-0003" }, "personChildren": {"childFirstName": "Mary", "childLastName": "Martin" } }' <code> http://localhost:8080/people </code>

Response: 
HTTP/1.1 201 Created
Server: Apache-Coyote/1.1
<code>
Location: http://localhost:8080/people/1
</code>
Content-Length: 0
Date: Thu, 26 Jun 2014 05:42:45 GMT

$ curl  http://localhost:8080/people

{
  "timestamp" : 1403761371011,
  "status" : 500,
  "error" : "Internal Server Error",
  "exception" : "org.springframework.http.converter.HttpMessageNotWritableException",
  "message" : "Could not write JSON: Detected multiple association links with same relation type! Disambiguate association @javax.persistence.OneToOne(optional=false, targetEntity=void, cascade=[], fetch=EAGER, orphanRemoval=false, mappedBy=personChildren) private com.ds.dao.rest.Person com.ds.dao.rest.PersonChildren.person using @RestResource! (through reference chain: org.springframework.hateoas.PagedResources[\"_embedded\"]->java.util.UnmodifiableMap[\"people\"]->java.util.ArrayList[0]); nested exception is com.fasterxml.jackson.databind.JsonMappingException: Detected multiple association links with same relation type! Disambiguate association @javax.persistence.OneToOne(optional=false, targetEntity=void, cascade=[], fetch=EAGER, orphanRemoval=false, mappedBy=personChildren) private com.ds.dao.rest.Person com.ds.dao.rest.PersonChildren.person using @RestResource! (through reference chain: org.springframework.hateoas.PagedResources[\"_embedded\"]->java.util.UnmodifiableMap[\"people\"]->java.util.ArrayList[0])",
  "path" : "/people"
}

问题 1:我可以发帖,但我的 GET 一直失败。

问题 2:为什么我在 Post 成功时会出现这个错误?

问题 3:是否有对 REST 和 JPA 有帮助的好的 Spring 指南?如果您仍在研究这些模块,我可以查看哪些示例?

问题 4:@RepositoryRestResource 是问题所在吗?除非我将 spring-data-rest-webmvc 添加为依赖项,否则无法识别它。

这类似于未回答的问题 Spring Data Rest Ambiguous Association Exception

更新:

它只使用 Person 类中的一个 OneToOne 映射。如果我使用 OneToOne 映射在 Person 中添加这两个类,personDetailspersonChildren。它不工作。

我还尝试将 @JointColumn(name="person_details")@JointColumn(name="person_children") 添加到 personDetailspersonChildren。它也不起作用。

最佳答案

原因很简单:关联实体的关系名称派生自包含类的属性名称。所以 PersonDetailsPersonChildren 都想创建一个指向名为 personPerson 的出站链接。如果我们渲染它,它看起来像这样

{ _links : { 
   person : { href : … }, <- the one from PersonDetails
   person : { href : … }  <- the one from PersonChildren
}

这当然是无效的。此外,将两个链接排列在一个数组中将不再允许您区分这两个链接(哪个来自 PersonDetails,哪个来自 PersonChildren

所以这里有几个选项:

  1. 手动命名这些类型的关系。您可以使用 @RestResource 注释 Person 属性,并将注释的 rel 属性配置为不同于 person 的属性.
  2. 您希望两个中的任何一个都不导出。完全相同的注释可用于完全阻止呈现链接。只需将 @RestResource 中的 exported 标志设置为 false,链接将不会呈现。如果指针例如from PersonDetails 仅与代码相关,但实际上与 JSON 表示无关。

关于java - Spring Data REST - 检测到具有相同关系类型的多个关联链接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24426644/

相关文章:

CSV 与 TXT 文件中的 Java BufferedReader 行为

Java 嵌入式应用程序 - 设备需要什么

java - StandardServiceRegistry 在 Hibernate 4 中的重要性是什么?

python - 对象关系数据库中的联接表继承映射与组合

c# - 让 BLToolkit 与 MySQL 一起工作

php - 学说 2.2 ORM : find extended entity

java - 将 char 数组从 java 返回到 C - JNI

java - 简单类 - 是内存泄漏吗?

java - 在嵌入式 HSQL 数据库中创建模式的最佳方式

java - Spring Data JPA 规范 - 不同 + 连接中按列排序