一对多关系支持阅读但不插入 [英] One To Many Relationship Supporting Reads but not INSERTS
问题描述
我正在使用Spring Boot(2.1.1版)来创建需要一对多&具有以下要求的两个模型类之间的多对一关系
模型类是
@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;
//…
}
要求
- 两个组织和部门均应由各自独立的rest api创建.
- 通过POST/organizations api,我们应该能够创建一个组织,而无需在同一api调用中创建部门.实际上,api应该失败,因为我尝试将部门的json元素作为POST/organizations调用的一部分传递.
- 在致电POST/部门时,我应该能够传递组织ID,以将新创建的部门与组织相关联.
- GET/organizations api调用应将Collection作为组织对象的一部分返回
问题是
-
如何关联两个模型对象?是否在组织中添加@OneToMany?我将哪些属性传递给@OneToMany?我是否需要在部门另一侧使用类似的@ManyToOne?
-
我在REST控制器上是否需要任何特殊注意事项?
您仅需要@ManyToOne
即可将其保留在Department
中,但很可能需要@OneToMany
在Organization
中才能进行GET请求.>
在保存部门时,只需确保您需要:
- 从db获取组织
- 在部门对象上设置获取的组织
- 将部门添加到Organization.departments列表中
- 坚持部门
对于错误处理,请返回BAD_REQUEST
响应:
return new ResponseEntity<>(HttpStatus.BAD_REQUEST);
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?
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);
这篇关于一对多关系支持阅读但不插入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!