Java 将对象插入到已创建的实体(多通和一通)

Java 将对象插入到已创建的实体(多通和一通),java,reactjs,spring-boot,hibernate,Java,Reactjs,Spring Boot,Hibernate,我有以下问题,我已经有两天了,因为我试图通过阅读和观看教程来解决,但我仍然做错了 我有以下两门课:建筑课和团体课。每个建筑都属于一个组,并且只有一个,一个组可以有多个建筑。因此,我: public class Building { @Id @GeneratedValue(generator = "UUID") @GenericGenerator( name = "UUID", str

我有以下问题,我已经有两天了,因为我试图通过阅读和观看教程来解决,但我仍然做错了

我有以下两门课:建筑课和团体课。每个建筑都属于一个组,并且只有一个,一个组可以有多个建筑。因此,我:

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

如您所见,该组有一个地址(对象)、主席、管理员、审查员,所有对象我将在稍后阶段插入,这是有效的,因为是@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
  }
到目前为止还不错,我有一栋全新的大楼,大楼有一个地址

问题是,考虑到我已经有了组信息,我如何将此组插入到当前建筑中

我试过这样的方法:

{
    "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"
  }
  • 第一次尝试:我在React钩子中添加了一个空的“group:{}”,目的是用已知的信息填充它。结果将生成一个具有新id的新组,我不希望出现这种情况
  • 第二次尝试:我已转到后端并尝试添加新的休息路线:
  • 我有来自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();
        }
    
  • 第三次尝试:我尝试从前端(@RequestBody building building)请求建筑物的主体,在那里我已经有了地址,只是想将组添加到其中
  • @GetMapping(“/update/{id}”)
    公共列表更新(@PathVariable UUID,@RequestBody Building){
    groupgroup=groupRepository.getOne(id);
    建筑。setGroup(集团);
    列表建筑=集合。单音列表(建筑);
    建筑(建筑物)组;
    groupRepository.save(组);
    返回buildingRepository.findAll();
    }
    
    这是一个错误

    在这一刻,我感到困惑,我尝试了很多,但我不知道在哪里寻找了


    谢谢

    我认为您的解决方案2的方向是正确的

    您只需在
    建筑物
    字段中添加
    @JsonBackReference
    注释:

    @OneToMany(mappedBy = "group", cascade = CascadeType.ALL, orphanRemoval = true)
    @JsonBackReference
    private List<Building> buildings = new ArrayList<>();
    
    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "group_id")
    @JsonManagedReference
    private Group group;
    
    @JsonManagedReference
    是引用的前向部分–正常序列化的部分
    @JsonBackReference
    是引用的后面部分–它将从序列化中省略。使用这些注释可以在序列化过程中处理循环依赖关系,并可以防止发生堆栈溢出错误(无限循环)

    {
            "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
    
        @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();
        }
    
    @OneToMany(mappedBy = "group", cascade = CascadeType.ALL, orphanRemoval = true)
    @JsonBackReference
    private List<Building> buildings = new ArrayList<>();
    
    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "group_id")
    @JsonManagedReference
    private Group group;