Home > Java, Spring, Spring Data Rest > How to issue a JSON POST request to Spring Data Rest with a JPA relation

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

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

@Entity
@Table(name = "company")
public class Company implements java.io.Serializable {

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

	public Company() {
	}

	@Id
	@GeneratedValue(strategy = IDENTITY)
	@Column(name = "id", unique = true, nullable = false)
	public Long getId() {
		return this.id;
	}

	public void setId(Long id) {
		this.id = id;
	}

	@Column(name = "name", nullable = false, length = 200)
	public String getName() {
		return this.name;
	}

	public void setName(String name) {
		this.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.

Advertisements
Categories: Java, Spring, Spring Data Rest Tags: ,
  1. No comments yet.
  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: