java—将对象插入到已创建的实体(manytone和onetomany)

agyaoht7  于 2021-06-26  发布在  Java
关注(0)|答案(1)|浏览(248)

我有下面的问题,我已经有两天了,因为我试图解决通过阅读和观看教程,但仍然是我做错了。
我有以下两门课:建筑课和小组课。每个建筑都属于一个组,并且只有一个,一个组可以有多个建筑。所以我有:

public class Building {

    @Id
    @GeneratedValue(generator = "UUID")
    @GenericGenerator(
            name = "UUID",
            strategy = "org.hibernate.id.UUIDGenerator"
    )
    @Column(name = "id", updatable = false, nullable = false)
    private UUID id;

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "group_id")
    private Group group;
}

public class Group {

    @Id
    @GeneratedValue(generator = "UUID")
    @GenericGenerator(
            name = "UUID",
            strategy = "org.hibernate.id.UUIDGenerator"
    )
    @Column(name = "id", updatable = false, nullable = false)
    private UUID id;

    @OneToMany(mappedBy = "group", cascade = CascadeType.ALL, orphanRemoval = true)
    private List<Building> buildings = new ArrayList<>();

首先我要创建一个组,json是这样的:

{
    "id": "be489e30-ebde-4cb4-bef3-5ff9b4463e4d",
    "officialName": "official",
    "shortName": "short",
    "email": "emai@example.com",
    "groupAddress": {
      "id": "15eea366-e2f0-4b38-a7b1-a9a006ef1284",
      "street": "street example",
      "number": "55",
      "town": "example town",
      "country": "example country"
    },
    "administrator": {
      "id": "0bfee30b-96d7-4e5d-9fcc-3a4f82c31301",
      "firstName": null,
      "lastName": null,
      "phone": null,
      "email": "emai@example.com",
      "password": "administrator"
    },
    "president": {
      "id": "293e5efe-d07e-428e-9147-87510c7255f1",
      "firstName": null,
      "lastName": null,
      "phone": null,
      "email": "emai@example.com",
      "password": "president"
    },
    "censor": {
      "id": "34faca46-7ce9-4842-9ddd-3116ed05e9ab",
      "firstName": null,
      "lastName": null,
      "phone": null,
      "email": "emai@example.com",
      "password": "censor"
    },
    "picture": "picture.jpg",
    "buildings": [

    ],
    "iban": "1111 0000 5555 6666 9999"
  }

如您所见,这个组有一个地址(object)、总裁、管理员、审查员,所有的object我都会在稍后的阶段插入,这是有效的,因为是@onetoone关系,我觉得很容易。
在以后的阶段,我有可能添加一个建筑到某个群体。这是通过使用react从前端执行的。所以我有:

const [group, setGroup] = useState({});

    const [building, setBuilding] = useState({
        address : {
            street : "",
            number : "",
            town : "",
            country : "",
            buildingName : "",
            entrance : ""
        }
    })

   useEffect(() =>{
        axios.get(`http://localhost:8080/api/group/${groupId}`)
            .then(response => {
                setGroup(response.data);
            })
    }, [groupId])

首先我获取组信息。一直到现在都很好。
我有一些意见,我正在填写大楼的地址

address : {
            street : "",
            number : "",
            town : "",
            country : "",
            buildingName : "",
            entrance : ""
        }

然后我处理提交:

const handleSubmit =(e) => {
        e.preventDefault();
        axios.post(`/api/building`, building)
            .then(() => {
                alert("Successfully added a new building")
            })
    }

然后我得到了当前建筑的json:

{
    "id": "56b1d638-1fda-493e-95b4-9c6c86595552",
    "group": null,
    "address": {
      "id": "4ab5d267-f5a5-4830-bf60-fd688b893a5c",
      "street": "Example Street",
      "number": "15",
      "town": "example town",
      "country": "country",
      "buildingName": "1A",
      "entrance": "5"
    },
    "noticeBoard": null
  }

到目前为止还不错,我有一栋全新的大楼,大楼有地址。
问题是,考虑到我已经有了组信息,我如何才能将此组插入到当前建筑中?
我试过这样的方法:
第一次尝试:我在react钩子中添加了一个空的“group:{}”,用已知的信息填充它。结果将生成一个具有新id的新组,我不希望这样。

const [building, setBuilding] = useState({
        group : {
          },
        address : {
            street : "",
            number : "",
            town : "",
            country : "",
            buildingName : "",
            entrance : ""
        }
    })
    const s = {...building}
    s.group = group
    setBuilding(s);

第二次尝试:我已转到后端并尝试添加新的休息路线:
我有来自id的组信息(路径中的id)我正在创建一个新的建筑对象我正在使用建筑的setter将组添加到存储库我正在尝试保存新创建的建筑
这将产生一个无限循环

@GetMapping("/update/{id}")
    public List<Building> update(@PathVariable UUID id){

        Group group = groupRepository.getOne(id);
        Building building = new Building();

        building.setGroup(group);

        buildingRepository.save(building);

        return buildingRepository.findAll();
    }

以及json响应:

{
        "id": "516f5caf-b869-4a1c-863d-adc6e9ec1e56",
        "group": {
            "id": "b083c3b9-df18-4444-a815-52150ca911b8",
            "officialName": "example name",
            "shortName": "example name",
            "email": "example@yahoo.com",
            "groupAddress": {
                "id": "ec12742a-2c2f-4c74-a30e-5d096a4478cb",
                "street": "street name",
                "number": "15",
                "town": "example town",
                "country": "example country"
            },
            "administrator": {
                "id": "18275548-a7b5-4e20-bdad-52887c0ea28f",
                "firstName": null,
                "lastName": null,
                "phone": null,
                "email": "example@yahoo.com",
                "password": "administrator"
            },
            "president": {
                "id": "8d26060e-43a5-4a8c-a4f2-4164627dda0e",
                "firstName": null,
                "lastName": null,
                "phone": null,
                "email": "example@yahoo.com",
                "password": "president"
            },
            "censor": {
                "id": "5d4dffaa-54d3-4d52-86e1-55df2160f32b",
                "firstName": null,
                "lastName": null,
                "phone": null,
                "email": "example@yahoo.com",
                "password": "censor"
            },
            "picture": "jpeg",
            "buildings": [
                {
                    "id": "516f5caf-b869-4a1c-863d-adc6e9ec1e56",
                    "group": {
                        "id": "b083c3b9-df18-4444-a815-52150ca911b8",
                        "officialName": "example name",
                        "shortName": "example name",
                        "email": "example@yahoo.com",
                        "groupAddress": {
                            "id": "ec12742a-2c2f-4c74-a30e-5d096a4478cb",
                            "street": "street name",
                            "number": "15",
                            "town": "example town",
                            "country": "example country"
                        },
                        "administrator": {
                            "id": "18275548-a7b5-4e20-bdad-52887c0ea28f",
                            "firstName": null,
                            "lastName": null,
                            "phone": null,
                            "email": "example@yahoo.com",
                            "password": "administrator"
                        },
                        "president": {
                            "id": "8d26060e-43a5-4a8c-a4f2-4164627dda0e",
                            "firstName": null,
                            "lastName": null,
                            "phone": null,
                            "email": "example@yahoo.com",
                            "password": "president"
                        },
                        "censor": {
                            "id": "5d4dffaa-54d3-4d52-86e1-55df2160f32b",
                            "firstName": null,
                            "lastName": null,
                            "phone": null,
                            "email": "example@yahoo.com",
                            "password": "censor"
                        },
                        "picture": "jpeg",
                        "buildings": [
                            {
                                "id": "516f5caf-b869-4a1c-863d-adc6e9ec1e56",
                                "group": {
                                    "id": "b083c3b9-df18-4444-a815-52150ca911b8",
                                    "officialName": "example name",
                                    "shortName": "example name",
                                    "email": "example@yahoo.com",
                                    "groupAddress": {
                                        "id": "ec12742a-2c2f-4c74-a30e-5d096a4478cb",
                                        "street": "street name",
                                        "number": "15",
                                        "town": "example town",
                                        "country": "example country"
                                    },etc

第三次尝试:我尝试从前端(@requestbody building building)请求建筑物的主体,在那里我已经有了地址,只想将组添加到其中

@GetMapping("/update/{id}")
    public List<Building> update(@PathVariable UUID id, @RequestBody Building building){

        Group group = groupRepository.getOne(id);

        building.setGroup(group);

        List<Building> buildings = Collections.singletonList(building);
        group.setBuildings(buildings);
        groupRepository.save(group);

        return buildingRepository.findAll();
    }

是一个错误。
在这一刻我很困惑,我尝试了很多,但我不知道在哪里寻找了。
谢谢

ogsagwnx

ogsagwnx1#

我认为你的解决方案2的方向是对的。
你只需要加上 @JsonBackReference 在您的 buildings 字段:

@OneToMany(mappedBy = "group", cascade = CascadeType.ALL, orphanRemoval = true)
@JsonBackReference
private List<Building> buildings = new ArrayList<>();

以及 @JsonManagedReference 在您的 group 字段:

@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "group_id")
@JsonManagedReference
private Group group;
``` `@JsonManagedReference` 是引用的前向部分—正常序列化的部分。 `@JsonBackReference` 是引用的后面部分–它将从序列化中省略。使用这些注解可以在序列化过程中处理循环依赖关系,并防止发生stackoverflow错误(无限循环)。

相关问题