Spring JPA REST一对多

时间:2016-01-04 01:11:40

标签: java rest spring-data-jpa spring-data-rest

我想通过向Person实体添加地址列表来扩展示例Accessing JPA Data with REST。因此,我添加了一个带addresses注释的列表@OneToMany

@Entity
public class Person {
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private long id;

    private String firstName;
    private String lastName;

    @OneToMany(fetch = FetchType.EAGER, cascade = CascadeType.ALL)
    private List<Address> addresses = new ArrayList<>();

   // get and set methods...
}

Address类非常简单:

@Entity
public class Address {
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private long id;
    private String street;
    private String number;
    // get and set methods...
}

最后我添加了AddressRepository界面:

public interface AddressRepository extends PagingAndSortingRepository<Address, Long> {}

然后我尝试用一​​些地址发帖:

curl -i -X POST -H "Content-Type:application/json" -d '{  "firstName" : "Frodo",  "lastName" : "Baggins", "addresses": [{"street": "somewhere", "number": 1},{"street": "anywhere", "number": 0}]}' http://localhost:8080/people

我得到的错误是:

Could not read document: Failed to convert from type [java.net.URI] to type [ws.model.Address] for value 'street';
nested exception is java.lang.IllegalArgumentException: Cannot resolve URI street. Is it local or remote? Only local URIs are resolvable. (through reference chain: ws.model.Person[\"addresses\"]->java.util.ArrayList[1]);
nested exception is com.fasterxml.jackson.databind.JsonMappingException: Failed to convert from type [java.net.URI] to type [ws.model.Address] for value 'street'; nested exception is java.lang.IllegalArgumentException: Cannot resolve URI street. Is it local or remote? Only local URIs are resolvable. (through reference chain: ws.model.Person[\"addresses\"]->java.util.ArrayList[1])

创建一对多和多对多关系并将json对象发布给它们的正确方法是什么?

3 个答案:

答案 0 :(得分:8)

您应该首先发布这两个地址,然后在您的Person POST中使用他们返回的网址(例如http://localhost:8080/addresses/1http://localhost:8080/addresses/2):

curl -i -X POST -H "Content-Type:application/json" -d '{  "firstName" : "Frodo",  "lastName" : "Baggins", "addresses": ["http://localhost:8080/addresses/1","http://localhost:8080/addresses/2"]}' http://localhost:8080/people

如果您想首先保存此人,然后添加其地址,您可以这样做:

curl -i -X POST -H "Content-Type:application/json" -d '{  "firstName" : "Frodo",  "lastName" : "Baggins"}' http://localhost:8080/people
curl -i -X POST -H "Content-Type:application/json" -d '{"street": "somewhere", "number": 1}' http://localhost:8080/addresses
curl -i -X POST -H "Content-Type:application/json" -d '{"street": "anywhere", "number": 0}' http://localhost:8080/addresses
curl -i -X PATCH -H "Content-Type: text/uri-list" -d "http://localhost:8080/addresses/1
http://localhost:8080/addresses/2" http://localhost:8080/people/1/addresses

答案 1 :(得分:1)

我设法通过不导出引用的存储库来解决此问题。这是在界面顶部添加注释。在您的示例中,它将是这样的:

@RepositoryRestResource(exported = false)
public interface AddressRepository extends CrudRepository<Address, Long> {
}

这部分解决了问题,因为Spring Data仍然不会为您传播外键。但是,它会持久保存您的人员和地址(不提及属于该人员)。然后,如果我们再次调用API来更新这些丢失的外键,您将能够通过API获取所有链接地址的人 - 正如@Francesco Pitzalis所提到的那样

我希望它有所帮助。只是最后一点。我仍然在努力,因为我认为Hibernate不能为我们传播外键是荒谬的(以及基本的和需要的)。应该可能以某种方式。

编辑:确实有可能。下面的实现能够持久化实体及其子项将外键传播给它们,用于基于Spring Data的架构(Rest - 因为我们公开存储库),Hibernate 5.0.12Final和MySQL与存储引擎InnoDB(不在内存中)数据库)。

@Entity
public class Producto implements Serializable {

    private static final long serialVersionUID = 1L;

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
    private String nombre;
    @OneToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER)
    @JoinColumn(name = "producto_id")
    private List<Formato> listaFormatos;
    //Constructor, getters and setters
}

https://docs.jboss.org/hibernate/jpa/2.1/api/javax/persistence/JoinColumn.html - 这很重要。

@Entity
public class Formato implements Serializable {

    private static final long serialVersionUID = 1L;

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
    private Integer cantidad;
    private String unidadMedida;
    @ManyToOne
    private Producto producto;
    //Constructor, getters and setters
}

@RepositoryRestResource
public interface ProductoRepository extends CrudRepository<Producto, Long> {
}

@RepositoryRestResource
public interface FormatoRepository extends CrudRepository<Formato, Long> {
}

spring.datasource.url=jdbc:mysql://localhost:3306/(database name)
spring.datasource.username=(username)
spring.datasource.password=(password)
spring.jpa.show-sql=true

spring.jpa.hibernate.ddl-auto=create-drop
spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.MySQL5InnoDBDialect

这非常重要。您需要知道Hibernate在哪里运行SQL语句才能正确设置方言。对我来说,我的表的存储引擎是InnoDB。下一个链接有所帮助。 What mysql driver do I use with spring/hibernate?

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-rest</artifactId>
</dependency>
<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
    <scope>runtime</scope>
</dependency>

我唯一无法解释的是,现在,我可以导出“子”存储库,它仍然可以正常工作。任何想法,伙计们?

答案 2 :(得分:0)

你的休息服务不应该接受一个人而不是一个地址吗?

public interface PersonRepository extends PagingAndSortingRepository<Person, Long> {}

或者,也许你正在尝试制作两种不同的休息服务,我不明白。你应该只有一个休息服务,它接受一个包含地址条目的人。