Spring Data Jpa 无法< Entity>使用Java Spring在另一个实体中设置List?

dgiusagp  于 2023-11-19  发布在  Spring
关注(0)|答案(1)|浏览(168)

我想创建一个树结构,如;

istanbul fleet
        europe group
            a
            b
            c
            europe courier
                d
                e
        asia group
            f
            g
    ankara fleet
        h
        ı

字符串
我有仓库,服务,控制器结构,我有4个模型舰队,集团和Corrier,层次结构将如树中所示。我已经Map了实体作为OneToMany,你可以看到在实体类。
我有服务作为;

public void createCourierForGroup(CourierRequest request, Integer id) {
        Courier courier = Courier.builder()
                .courierName(request.getCourierName())
                .build();

        GroupResponse groupToAdd = getGroupById(id);

        List<Courier> courierList = groupToAdd.getCouriers();

        if (courierList.isEmpty()) {
            groupToAdd.setCouriers(List.of(courier));
        } else {
            courierList.add(courier);
            groupToAdd.setCouriers(courierList);
        }

        groupRepository.save(mapToGroup(groupToAdd));
        log.info("Group with name: {} is updated with inner groups of: {}", groupToAdd.getGroupName(),groupToAdd.getCouriers());
    }


舰队实体;

@Entity
@Getter
@Setter
@AllArgsConstructor
@NoArgsConstructor
@Builder
public class Fleet{

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Integer id;
    
    private String fleetName;
    
    @ManyToMany(cascade = CascadeType.REMOVE)
    private List<CarRegistry> carRegistries;
    
    @OneToMany(mappedBy = "fleet",fetch = FetchType.EAGER, cascade = CascadeType.REMOVE)
    private List<Group> groups;

}


集团实体;

@Entity(name = "group_table")
@Getter
@Setter
@Builder
@AllArgsConstructor
@NoArgsConstructor
public class Group {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Integer id;

    private String groupName;

    @ManyToMany(cascade = CascadeType.REMOVE)
    private List<CarRegistry> carRegistries;

    @ManyToOne
    private Fleet fleet;

    @OneToMany(mappedBy = "group",fetch = FetchType.EAGER, cascade = CascadeType.REMOVE)
    private List<Courier> couriers;

}


和应对

{
    "data": [
        {
            "id": 1,
            "fleetName": "Avrupa fleet",
            "carRegistries": [],
            "groups": []
        }
    ],
    "message": "Fleets are listed successfully.",
    "status": 200
}


我的仓库是这样的,没有什么花哨的只是数据jpa。

@Repository
public interface GroupRepository extends JpaRepository<Group, Integer> {
}


正如你所看到的,组是空的,这可能是错的吗?
我确实尝试了List.Of()方法或者创建新的List并将其传递给保存方法,但它不起作用。

jtjikinw

jtjikinw1#

你有没有试过在将快递添加到列表之前先保存它?
List.of()也创建了一个不可变的列表。https://www.baeldung.com/java-9-collections-factory-methods
如果快递员列表为空,您可以将新快递员添加到其中并将其设置为组。
附注:我猜这行GroupResponse groupToAdd = getGroupById(id);是将Group实体转换为GroupResponse,mapToGroup(groupToAdd)是在保存之前将GroupResponseMap到Group实体。

相关问题