问题
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
- 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.
- The GET /organizations api call should return the Collection as part of the organization object
The questions are
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?
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