One To Many Relationship Supporting Reads but not INSERTS

杀马特。学长 韩版系。学妹 提交于 2019-12-13 03:59:54

问题


I am using spring boot (verson 2.1.1) to create an application that needs to one-to-many & many-to-one relationship between two model classes with below requirements

The model classes are

@Entity
@Table(name="ORGANIZATIONS")
public class Organization{

    @Id
    @GeneratedValue
    Private long id;

    @Column(unique=true)
    Private String name;
}

@Entity
@Table(name="DEPARTMENTS")
Public class Department{

   @Id
   @GeneratedValue
   Private long id;

   @Column(unique=true)
   Private String name;


//…

}

Requirements

  1. Both organizations and departments should be created by separate respective rest api's.
    • Through the POST /organizations api we should be able to create an organization without creating departments in the same api call. In fact the api should fail I tried to pass the json element for department as part of the POST /organizations call.
    • When calling POST /departments I should be able to pass the organization id to associate the newly created department with the organization.
  2. The GET /organizations api call should return the Collection as part of the organization object

The questions are

  1. How do I associate the two model objects ? Do I add @OneToMany in Organization? What attributes do I pass to @OneToMany? Do I need a similar @ManyToOne on the other side - department?

  2. Do I need any special considerations on the REST controllers?


回答1:


You will need @ManyToOne for persisting in Department only but you most likely will need @OneToMany in Organization for the GET request.

Just make sure, when saving the Department, that you need to:

  • Fetch from db the organization
  • Set the fetched organization on the department object
  • Add the department to the Organization.departments list
  • Persist the department

For the error handling return a BAD_REQUEST response:

return new ResponseEntity<>(HttpStatus.BAD_REQUEST);


来源:https://stackoverflow.com/questions/54309296/one-to-many-relationship-supporting-reads-but-not-inserts

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!