如何将json数据插入到spring mvc和hibernate中与父表链接的子表中

时间:2017-03-03 07:02:47

标签: java spring hibernate rest

我有两个类Student和Address。我使用hibernate作为ORM工具。我已经映射了多个到一个关系 像许多学生一样的学生和地址可以有相同的地址。我的地址类是:

@Entity
Class Address {
@Id
@GeneratedValue
private int aid;
private String address;

@OneToMany(cascade = CascadeType.ALL)
@JoinColumn(name = "sid")
List<Student> students;
//getter and setter,constructor
}

我的学生班是:

@Entity
public class Student {
@Id
@GeneratedValue
private int sid;
private String sname;
//getter and setter,constructor
}

我的Address类的控制器类是:

public class AddressController {
@RequestMapping(value = "/address",method = RequestMethod.POST)
@ResponseBody
public String insertCategory(@RequestBody Address address) throws        SQLException {
    session=sessionFactory.getCurrentSession();
    session.save(address);
    return "succesful";
}

我将json数据插入: 本地主机:8080 /地址

{"address":"kathmandu","students":[{"sname":"Pravin"},{"sname":"biplav"}]}

但问题是我想添加现有地址的学生。我想插入一个新的学生链接 地址,但没有在地址表中插入新行。

我的地址类控制器是:

public class StudentController{
@RequestMapping(value = "/student",method = RequestMethod.POST)
@ResponseBody
public String insertCategory(@RequestBody Student student) throws   SQLException {
    session=sessionFactory.getCurrentSession();
    session.save(student);
    return "succesful";
}

我想插入: 本地主机:8080 /学生

{"sname":"pravin","aid":"1"}

1 个答案:

答案 0 :(得分:0)

然后,您需要另一个REST端点将学生添加到地址。例如 使用json学生申请机构发布http://localhost:8080/address/1/student

您错过的链接是您要更新的地址的ID。

POST http://localhost:8080/address/1/student

请求正文:{"sname":"pravin"}

@POST
@Path("address/{addressId}/student")
public Response addStudentToAddress(@PathParam("addressId") Integer addressId, Student student)) {

   // Fetch address by id
   // Add student to list
   // Save updated address

}

正如您所看到的,我现在正在使用POST来“创建”新学生并将其添加到现有地址实体。

您拥有的其他选项是使用PUT更新地址(整个地址对象必须存在于请求正文中)或PATCH,您还可以更新资源,但只能使用您传递的字段(您必须自己写这个逻辑,显然)

PUT http://localhost:8080/address/1

请求正文:{"aid":"1","address":"kathmandu","students":[{"sid":"1","sname":"Pravin"},{"sid":"2", "sname":"biplav"}, {"sname":"Nico"}]}

@PUT
@Path("address/{addressId}")
public Response updateAddress(@PathParam("addressId") Integer addressId, Address address)) {

   // match addressId with address body id. throw exception if it does not match
   // Save updated address

}

PATCH http://localhost:8080/address/1

请求正文:{"aid":"1", "students":[{"sid":"1", "sname":"Pravin"},{"sid":"2", "sname":"biplav"}, {"sname":"Nico"}]}

我不会在此请求正文中传递"address":"katmandu",因为我不想更新此字段。

@PATCH
@Path("address/{addressId}")
public Response updateAddress(@PathParam("addressId") Integer addressId, Address address)) {

   // match addressId with address body id. throw exception if it does not match
   // merge updated fields
   // Save updated address

}