简体   繁体   English

一对多关系,如何在 spring 引导中保存或更新数据

[英]One to Many relationship, how to save or update data in spring boot

I'm building an API for the company where I work and it is my first time using Spring Boot, so I'm having some problems.我正在为我工作的公司构建一个 API,这是我第一次使用 Spring Boot,所以我遇到了一些问题。

I have 2 classes, Compania (parent) and Office (Child).我有 2 个班级,Compania(父母)和办公室(孩子)。 The class Compania has a OneToMany relationship with Office, and Office has a ManyToOne, and I'm struggling to find how could I add some children or edit one of them. class Compania 与 Office 具有 OneToMany 关系,而 Office 具有 ManyToOne,我正在努力寻找如何添加一些孩子或编辑其中一个。 Right now my classes are the following:现在我的课程如下:

Compania (Parent)公司(父)

@Entity(name = "Compania")
@Table(
    name = "compania"
)
public class Compania {
    @Id
    @SequenceGenerator(
        name = "compania_sequence",
        sequenceName = "compania_sequence",
        allocationSize = 1
    )
    @GeneratedValue(
        strategy = GenerationType.SEQUENCE,
        generator = "compania_sequence"
    )
    @Column(
        nullable = false
    )
    private Long id;


    @Column(
        name = "name",
        nullable = false,
        unique = true
    )
    private String name;

    @Column(
        name = "dominio",
        nullable = true
    )
    private String dominio;

    @Column(
        name = "altas"
    )
    private String altas;

    @Column(
        name = "bajas"
    )
    private String bajas;

    @OneToMany(
        mappedBy = "compania",
        cascade = CascadeType.ALL,
        fetch = FetchType.LAZY,
        orphanRemoval = true
    )
    private List<Office> office;

...Constructors...
... Getters and Setters...

Office (Child)办公室(儿童)

@Entity()
@Table()
public class Office {
    @Id
    @SequenceGenerator(
        name = "office_sequence",
        sequenceName = "office_sequence",
        allocationSize = 1
    )
    @GeneratedValue(
        strategy = GenerationType.SEQUENCE,
        generator = "office_sequence"
    )
    @Column(
        nullable = false
    )
    @JsonIgnore
    private Long id;

    @Column(
        name = "idRef",
        nullable = false
    )
    private int idRef;

    @Column(
        name = "title",
        nullable = false
    )
    private String title;

    @Column(
        name = "name"
    )
    private String name;
    @Column(
        name = "path"
    )
    private String path;

    @ManyToOne(
        fetch = FetchType.LAZY
    )
    @JoinColumn(
        name = "compania_id",
        referencedColumnName = "id"
    )
    private Compania compania;

    ...Constructors...
    ... Getters and Setters...

I would like to save data or edit it in my parent object (the one that has the OneToMany relationship) In order to achieve this, I thought of 2 methods but I have problems with both of them.我想在我的父 object(具有 OneToMany 关系的那个)中保存或编辑数据为了实现这一点,我想到了 2 种方法,但我都遇到了问题。

The first one would be saving everything in the Compania (Parent) class.第一个是将所有内容保存在 Compania (父)class 中。 Something like this, I pass the id of the Compania class and the JSON object as an Office object:像这样,我将 Compania class 和 JSON object 的 ID 作为办公室 ZA8CFDE6331194EB26ZC96F8

public void addOfficeTest(Long companiaId, Office office) {
        // OPTION 1 - Add directly the office to the office list of the Compania Object (parent), then save it using Compania repository
        if (office.getId() != null) {
            office.setId(null);
        }
        Compania companiaFound = companiaRepository.findById(companiaId).get();
        List<Office> listaOffice = companiaFound.getOffice();
        listaOffice.add(office);
        companiaFound.setOffice(listaOffice);
        // method to set references id for user use...
        setIdReferencia(companiaEnc, true, false);
        companiaRepository.save(companiaEnc);

With this method, my problem is that is like I'm not being able to save my entities, when I make a GET to obtain my Companias I get the Office as an empty string.使用这种方法,我的问题是我无法保存我的实体,当我通过 GET 获取我的 Companias 时,我将 Office 作为一个空字符串。 like this:像这样:

{
        "id": 1,
        "name": "Test Compania",
        "dominio": "domain",
        "altas": "OU=nn",
        "bajas": "none",
        "office": []
}

The other method I thought was this one, saving the Office with the Office repository, but that returned an infinite recursion error when I tried to fetch my Compania (as I'm saving the compania in office)...我认为的另一种方法是使用 Office 存储库保存 Office,但是当我尝试获取我的 Compania 时返回了无限递归错误(因为我正在将公司保存在办公室中)......

public void addOfficeTest(Long companiaId, Office office) {
        // OPTION 2 - Save Office with the repository office
        if (office.getId() != null) {
            office.setId(null);
        }
        Compania companiaEnc = companiaRepository.findById(companiaId).get();
        office.setCompania(companiaEnc); // This causes recursion
        officeRepository.save(office); 

So I'm stuck here because I don't know how to do a PUT or a POST for my child objects.所以我被困在这里,因为我不知道如何为我的子对象做 PUT 或 POST。 I don't know if something is wrong with my code or what.我不知道我的代码是否有问题或什么。 Maybe it has an easy solution, but I really can't find it.也许它有一个简单的解决方案,但我真的找不到。 If someone could help giving me an example of how to do a POST and a PUT I would be very grateful...如果有人可以帮助给我一个如何进行 POST 和 PUT 的示例,我将非常感激......

Thanks谢谢

Given that you have a bi-directional relationship I think you are missing setting the Compania object in the new Office .鉴于您具有双向关系,我认为您缺少在新Office中设置Compania object 。 Something allong the following lines:大致如下:

public void addOfficeTest(Long companiaId, Office office) {
    // OPTION 1 - Add directly the office to the office list of the Compania Object (parent), then save it using Compania repository
    if (office.getId() != null) {
        office.setId(null);
    }
    Compania companiaFound = companiaRepository.findById(companiaId).get();
    office.setCompania(companiaFound); // The new line
    List<Office> listaOffice = companiaFound.getOffice();
    listaOffice.add(office);
    companiaFound.setOffice(listaOffice); // You actually don't need this because you've changed the List already
    // method to set references id for user use...
    setIdReferencia(companiaEnc, true, false);
    companiaRepository.save(companiaEnc);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM