使用Spring-Data-Rest,如何通过一个REST调用更新OneToOne关系两侧的FK?

问题描述 投票:0回答:1

我有一个带有Spring-Boot的应用程序

  • spring-boot-starter-data-rest
  • spring-boot-starter-data-jpa
  • h2

我有这样的一对一关系的实体:

@Entity
public class Address {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long key;

    @OneToOne(cascade = ALL)
    @JoinColumn(name = "party")
    private Party party;

    @Column
    private String street;

    ....
}
@Entity
public class Party {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long key;

    @Column
    private String name;

    @OneToOne(cascade = ALL)
    @JoinColumn(name  = "address")
    private Address address;

    ...

}

以及每个实体的存储库:

@RepositoryRestResource
public interface AddressRepository extends JpaRepository<Address, Long> { }
@RepositoryRestResource
public interface PartyRepository extends JpaRepository<Party, Long> { }

我创建每个实体的实例:

curl -X POST \
     -H 'Content-Type: application/json' \
     -d '{ "name": "John Smith" }' \
     http://localhost:8080/parties
curl -X POST \
     -H 'Content-Type: application/json' \
     -d '{ "street": "456 main st" }' \
     http://localhost:8080/addresses

在地址实例上,我创建了与聚会的HATEOAS关联:

curl -X PUT \
     -H 'Content-Type: text/uri-list' \
     -d http://localhost:8080/parties/1 \
     http://localhost:8080/addresses/1/party

当我检查地址的关联时:

curl -X GET http://localhost:8080/addresses/1/party -i

我看到正确的聚会:

HTTP/1.1 200 
{
  "key" : 1,
  "name" : "John Smith",
  ....
}

但是,当我检查地址的关联时:

curl -X GET http://localhost:8080/parties/1/address -i

它不存在:

HTTP/1.1 404 

如何使用Spring-Data-Rest通过单个调用创建两个关联?] >>

我有一个带有spring-boot-starter-data-rest的Spring-Boot应用程序spring-boot-starter-data-jpa h2我有这样的一对一关系的实体:@Entity公共类地址{@Id @ ...

java spring-boot spring-data-jpa spring-data-rest spring-hateoas
1个回答
0
投票

您需要像下面那样执行卷曲

curl -X POST \
     -H 'Content-Type: application/json' \
     -d '{ "name": "John Smith" , "address":{ "street": "456 main st" }}' \
     http://localhost:8080/parties
© www.soinside.com 2019 - 2024. All rights reserved.