Sunday, 13 August 2017

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

Lets say we have a class Company which has a relation to a class User
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
@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:
1
2
3
4
5
6
7
8
@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:
1
2
3
4
{
"name" : "a company name",
}
The “user” variable should be the URL that is pointing to the user repository.

No comments:

Post a Comment