Spring Data R2DBC:使用空员工列表保存部门(不支持的数组类型)

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

我在使用 Spring Data R2DBC 保存 Department 对象时遇到错误。我的 Department 模型有一个雇员属性,可以保存 Employee 对象的列表。但是,当我尝试创建一个具有空员工列表的新部门时,出现以下错误:

java.lang.IllegalArgumentException: Unsupported array type: io.spring.graphql.employeedemo2.model.Employee

代码片段:

系.班级

@Data
@NoArgsConstructor
@Table(name = "department_tbl")
public class Department {

    @Id
    @Column("department_name")
    private int id;

    @Column("department_name")
    private String name;

    private List<Employee> employees;

    public Department(int id, String name, List<Employee> employees){
        this.id = id;
        this.name = name;
        this.employees = new ArrayList<>();
    }

添加部门输入.class

@Data
@NoArgsConstructor
@AllArgsConstructor
public class AddDepartmentInput {

    private int id;
    private String name;

}
@MutationMapping
public Mono<Department> createDepartment(@Argument AddDepartmentInput departmentInput) {
    return Mono.just(departmentInput)
        .map(dptInput -> {
            Department department = new Department();
            department.setId(dptInput.getId());
            department.setName(dptInput.getName());
            department.setEmployees(new ArrayList<>()); // Empty list initialization
            return department;
        })
        .flatMap(department -> departmentRepository.save(department));
}

这是我的schema.graphqls

type Employee {
    id: ID!
    name: String
    salary: Float
    departmentId: ID!
}

type Department {
    id: ID!
    name: String
    employees: [Employee]
}

type Mutation {
    createDepartment(departmentInput: AddDepartmentInput ):Department
}

input AddDepartmentInput {
    id:ID!
    name:String
}

上下文:

  • 我使用 Spring Data R2DBC 进行数据持久化。
  • 我想允许最初创建没有任何关联员工的部门。

问题:

如何使用 Spring Data R2DBC 有效地保存具有空

employees
列表的 Department 对象?是否有推荐的方法来处理模型中的空列表?

spring-data-r2dbc r2dbc empty-list spring-graphql r2dbc-postgresql
1个回答
0
投票

Spring Data R2dbc 不支持像 JPA 和 Spring Data JPA 那样的一对多关系,因此您可能必须将 Department 和 Employee 分开在不同的表中。

@Table(name = "department_tbl")
record Department(...) {}

@Table(name = "employee_tbl")
record Employee(@Column Integer departmentId, ....){}

当您使用 Spring GraphQL 时,最好使用不同的模型类来呈现 GraphQL 输入等,不要混合数据模型类。

使用 Spring Webflux/Spring GraphQL/Spring Data R2dbc 检查我的示例:https://github.com/hantsy/spring-graphql-sample/tree/master/spring-graphql-webflux

© www.soinside.com 2019 - 2024. All rights reserved.