问题
What do I need to implement in order to create multiple records in my DB with a single http request?
I have a small Web-Application using SpringDataRest and JPA/Hibernate in which I can create resources with requests like this:
curl -XPUT -H"Content-Type: application/json; charset utf-8"\
-d'{"id":"1","type":"test"}'\
http://localhost:8080/test/items/1
Instead, I would like to do something like:
curl -XPUT -H"Content-Type: application/json; charset utf-8"\
-d'[{"id":"1","type":"test1"},{"id":"2","type":"test2"}]'\
http://localhost:8080/test/items/
The according Repository looks like this:
@RestResource(path = "items", rel = "items")
public interface ItemRepository extends PagingAndSortingRepository<Item, String> {
}
The Bean used:
@Entity
@XmlRootElement(name = "page")
@Table(name="page")
public class Item {
@Id
@Column(name="id")
private String id;
@Column(name="type")
private String type;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
/**
* @return the type
*/
public String getType() {
return type;
}
/**
* @param type the type to set
*/
public void setType(String type) {
this.type = type;
}
}
回答1:
You need a controller.
Essentially you want to override the POST method on the resource to accept a list of items instead of a single one.
You'll have to get reference to your repository inside the controller and insert the objects manually.
来源:https://stackoverflow.com/questions/32053092/how-to-create-multiple-resources-with-one-request-in-spring-data-rest