Rob Rob - 5 months ago 37
JSON Question

add item to the collection with foreign key via REST call

I have 2 jpa entities with bidirectional associasion.

Entity

Container
that holds collection of items (oneToMany)
Ommiting getter/setters

@javax.persistence.Entity
@Table(name = "CONTAINER")
public class Container implements Serializable {
private static final long serialVersionUID = -3288335692695653843L;

@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "ID")
private Long id;

@OneToMany(fetch = FetchType.LAZY, mappedBy = "container", cascade = CascadeType.ALL)
private List<Item> items;

}


Entity
Item
contains reference back to the container (ManyToOne), with attributes value and date.
Ommiting setter/getters

@javax.persistence.Entity
@Table(name = "ITEM")
public class Record implements Serializable {

private static final long serialVersionUID = -758343957629274274L;

@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "ID")
private Long id;

@Basic
private Long value;
@Basic
private Date date;

@ManyToOne(fetch = FetchType.EAGER)
@JoinColumn(name = "CONTAINER_ID")
private Container container;
}


Also i am using spring-data repositories to expose data.

My Interface repositories just extends
CrudRepository<Container, Long>
and
CrudRepository<Item, Long>


@RepositoryRestResource
public interface ItemRepository extends CrudRepository<Item, Long> {
}

@RepositoryRestResource
public interface ContainerRepository extends CrudRepository<Container, Long> {
}


I am trying to create items via REST calls.

First i tried this on items repository
rest/items


POST { "value" : 666, "date" : "2016-01-31T23:00:00.000+0000", "container": {"id":"1"}}


But it just creates item with null reference on container.

When i try to add via container repository
rest/containers/1/items


POST { "value" : 666, "date" : "2016-01-31T23:00:00.000+0000", "container": {"id":"1"}}


I get
HTTP/1.1 204 No Content
and
<Response body is empty>
. No instance is created.

My question is how i can add item via REST call that has reference to the container.

EDIT: To specify my question, i want to add new item for the existing container. I am not sure how to deal with with foreign ID key when creating instance of Item via rest(json)

Rob Rob
Answer

I resolved this issue by using link to the container inside json.

POST { "value" : 666, "date" : "2016-01-31T23:00:00.000+0000","container":"http://localhost:8080/container/1"}

I am not sure if it works without spring-data-rest

Comments