首页 > 解决方案 > 使用弹簧数据休息在2个实体之间创建关系/一对一链接

问题描述

在本教程https://www.baeldung.com/spring-data-rest-relationships之后,我正在尝试通过 rest put 调用在 2 个实体之间复制链接创建。

但是,当我尝试链接地址/1 和库/1/libraryAddress curl -i -X PUT -d " http://localhost:8080/addresses/1 " -H "Content-Type时,我收到以下错误消息:text/uri-list" http://localhost:8080/libraries/1/libraryAddress

“必须仅发送 1 个链接来更新不是列表或地图的属性引用”

细节 :

// Data model
// Master library class which have one address
@Entity
public class Library {

    @Id
    @GeneratedValue
    private long id;

    @Column
    private String name;

    @OneToOne
    @JoinColumn(name = "address_id")
    @RestResource(path = "libraryAddress", rel="address")
    private Address address;

    // standard constructor, getters, setters
}

// Address linked with a onetoone relation with library
@Entity
public class Address {

    @Id
    @GeneratedValue
    private long id;

    @Column(nullable = false)
    private String location;

    @OneToOne(mappedBy = "address")
    private Library library;

    // standard constructor, getters, setters
}

// Repositories
public interface LibraryRepository extends CrudRepository<Library, Long> {}
public interface AddressRepository extends CrudRepository<Address, Long> {}

使用其余 api 进行的查询:

创建一个库

curl -i -X POST -H "Content-Type:application/json"
  -d '{"name":"My Library"}' http://localhost:8080/libraries

创建地址

curl -i -X POST -H "Content-Type:application/json"
  -d '{"location":"Main Street nr 5"}' http://localhost:8080/addresses

创建协会

curl -i -X PUT -d "http://localhost:8080/addresses/1"
  -H "Content-Type:text/uri-list" http://localhost:8080/libraries/1/libraryAddress

--> 错误 {"cause":null,"message":"必须仅发送 1 个链接来更新不是 List 或 Map 的属性引用。"}

你有解决这个问题的任何线索吗?

问候,模糊。

标签: restspring-bootjpaspring-data-resthateoas

解决方案


这实际上是 Spring Boot 2.2.0org.springframework.data.rest.webmvc.RepositoryPropertyReferenceController类中的一个错误,位于第 321 行:

if (source.getLinks().hasSingleLink()) {
        throw new IllegalArgumentException(
            "Must send only 1 link to update a property reference that isn't a List or a Map.");
}

它应该是:

if (!source.getLinks().hasSingleLink()) {
        throw new IllegalArgumentException(
            "Must send only 1 link to update a property reference that isn't a List or a Map.");
}

这是 String Boot 2.1.7 的代码

if (source.getLinks().size() != 1) {
        throw new IllegalArgumentException(
            "Must send only 1 link to update a property reference that isn't a List or a Map.");
}

推荐阅读