Spring Data JDBC - 多对一关系

问题描述 投票:0回答:2

我似乎无法在网上找到任何有关在 Spring JDBC 中使用多对一映射的参考。我刚刚在文档中看到不支持,但我不确定是否是这种情况。

我的例子是我想将我的 AppUser 映射到特定部门。

仅供参考,AppUser 使用 DEPARTMENT_ID 连接到 Department 表

@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;
    }

但是,似乎无法正确映射。

@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

[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" = ?];

谢谢

java db2 many-to-one db2-luw spring-data-jdbc
2个回答
2
投票

我刚刚在文档中看到不支持,但我不确定是否是这种情况。

我可以确认它不受支持。 多对一关系跨越聚合的边界。 跨聚合的引用必须建模为所引用聚合的 id。

如果您不这样做,Spring Data JDBC 将认为引用是一对一关系,并且是同一聚合的一部分,这将产生您不希望对多对一关系产生的影响,例如引用的实体当引用的实体被删除时被删除。这对于同一聚合内的一对一关系是正确的。

这在https://spring.io/blog/2018/09/24/spring-data-jdbc-references-and-aggregates

中有更详细的解释

0
投票

您可以尝试使用AfterConvertEvent来设置字段

    @Bean
public ApplicationListener<AfterConvertEvent> afterLoad() {
    return event -> {
        var entity = event.getEntity();
        if (entity instanceof AppUserProjectionTwo) {
            AppUserProjectionTwo object = (AppUserProjectionTwo) entity;
            object.setDepartmenProjection(
                departmenProjectionRepository.findById(
                    appUserProjectionTwo.getDepartmenProjectionId()
                ).orElse(null)
            );
        }
    };
}
© www.soinside.com 2019 - 2024. All rights reserved.