問題描述
我似乎在網上找不到任何關于在 Spring JDBC 中使用多對一映射的參考資料.我剛剛在不支持的文檔中看到了,但我不確定是否是這種情況.
I can't seem to find any reference online with regards to using a Many-To-One mapping in Spring JDBC. I just saw in the documentation that is not supported but I'm not sure if this is the case.
我的示例是我想將我的 AppUser 映射到特定部門.
My example is that I want to map my AppUser to a particular Department.
作為參考,AppUser 使用 DEPARTMENT_ID 加入 Department 表
For reference, AppUser joins to Department table using DEPARTMENT_ID
@Table(value="m_appuser")
public class AppUserProjectionTwo {
@Id
private Long id;
private String firstname;
private String middlename;
private String lastname;
@Column("DEPARTMENT_ID")
private DepartmentProjection departmenProjection;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
但是,它似乎無法正確映射.
However, it seems that it won't map properly.
@Table("M_DEPARTMENT")
public class DepartmentProjection {
@Id
private Long id;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
創建的查詢如下所示.我正在尋找更多相反的東西,其中 M_APPUSER.department_ID = Department.id
The created query looks like this. I was looking for something more of the opposite in which M_APPUSER.department_ID = Department.id
[SELECT "m_appuser"."ID" AS "ID", "m_appuser"."LASTNAME" AS "LASTNAME", "m_appuser"."FIRSTNAME" AS "FIRSTNAME", "m_appuser"."MIDDLENAME" AS "MIDDLENAME", "departmenProjection"."ID" AS "DEPARTMENPROJECTION_ID" FROM "m_appuser" LEFT OUTER JOIN "M_DEPARTMENT" AS "departmenProjection" ON "departmenProjection"."DEPARTMENT_ID" = "m_appuser"."ID" WHERE "m_appuser"."FIRSTNAME" = ?];
謝謝
推薦答案
我剛剛在文檔中看到不支持,但我不確定是否是這種情況.
I just saw in the documentation that is not supported but I'm not sure if this is the case.
我可以確認它不受支持.多對一關系跨越聚合的邊界.跨聚合的引用必須建模為被引用聚合的 id.
I can confirm it is not supported. Many-To-One relationships cross the boundaries of aggregates. References across aggregates must be modelled as ids of the referenced aggregate.
如果你不這樣做,Spring Data JDBC 將把引用視為一對一關系和同一聚合的一部分,這將對多對一關系產生你不想要的影響,例如當被引用的實體被刪除時,被引用的實體被刪除.這對于同一聚合中的一對一關系是正確的.
If you don't do this Spring Data JDBC will consider the reference a One-To-One relationship and part of the same aggregate which will have effects you don't want for a Many-To-One relationship, like the referenced entity getting deleted when the referenced entity gets deleted. Which would be correct for a One-To-One relationship within the same aggregate.
這在 中有更詳細的解釋https://spring.io/blog/2018/09/24/spring-data-jdbc-references-and-aggregates
這篇關于Spring Data JDBC - 多對一關系的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!