2017-03-03 34 views
2

我有兩個類學生和Address.I使用休眠作爲一個ORM tool.I映射了許多對一個關係 學生和地址像許多學生可以有相同的address.My地址等級是:如何插入JSON數據到子表與春天mvc和休眠父表連接子表中

@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"}]} 

但問題是,當我想增加學生與現有address.I要插入新的學生有 地址,但沒有鏈接在地址表中插入新行。

我的地址類控制器:

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"} 

回答

0

然後,你需要另一個REST端點,以一個學生添加到地址。例如 POST http://localhost:8080/address/1/student與json學生請求正文。

您錯過的鏈接是您想更新的地址的標識。


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 

} 
+0

我沒有得到it.Please闡述 – pravin

+0

這沒有意義指向本地主機何時更新地址資源:8080 /學生。此外,您必須傳遞您想要更新的地址標識,因爲您還可以知道應更新哪個地址? –