Archive for the ‘Spring Data Rest’ Category

How to issue a JSON POST request to Spring Data Rest with a JPA relation

25 November 2014 Leave a comment

Lets say we have a class Company which has a relation to a class User

@Table(name = "company")
public class Company implements {

	private static final long serialVersionUID = 1L;
	private Long id;
	private String name;
	private User user;

	public Company() {

	@GeneratedValue(strategy = IDENTITY)
	@Column(name = "id", unique = true, nullable = false)
	public Long getId() {

	public void setId(Long id) { = id;

	@Column(name = "name", nullable = false, length = 200)
	public String getName() {

	public void setName(String name) { = name;

	@ManyToOne(fetch = FetchType.LAZY, optional = false, targetEntity=my.example.User.class)
	@JoinColumn(name = "user_id")
	public User getUser() {
		return user;

	public void setUser(User user) {
		this.user = user;

and their corresponding repositories:

@RepositoryRestResource(collectionResourceRel = "company", path = "company")
public interface CompanyRepository extends JpaRepository<Company, Long>  {

@RepositoryRestResource(collectionResourceRel = "user", path = "user")
public interface UserRepository extends JpaRepository<User, Long> {


In order to add a user to the company (let’s say we want to link this company to the user with id of 2) you will need to issue the following JSON request to the company repository:

"name" : "a company name",
"user" : "http://localhost:8086/user/2"

The “user” variable should be the URL that is pointing to the user repository.

Categories: Java, Spring, Spring Data Rest Tags: ,