Home > database >  Not correct list @OneToMany and @ManyToOne Jpa
Not correct list @OneToMany and @ManyToOne Jpa

Time:05-03

I am trying to list from child(Person/Person) to parent(Company/Company).

Previously it had infinite loop problems, but @JsonIdentityInfo(generator = ObjectIdGenerators.PropertyGenerator.class, property = "id") fixed it.

Here is the code:

Empresa.class

package com.demo.clase7.Entity;

import com.fasterxml.jackson.annotation.*;
import com.sun.istack.NotNull;
import lombok.*;

import javax.persistence.*;
import java.io.Serializable;
import java.util.Date;
import java.util.List;
import java.util.Set;

@Data
@NoArgsConstructor
@AllArgsConstructor
@Entity(name = "empresa")
@JsonIdentityInfo(generator = ObjectIdGenerators.PropertyGenerator.class, property = "id")
public class Empresa {

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

    @Column(name = "razon_social")
    private String razonSocial;

    private String ruc, representante;

    @Column(name = "fecha_creacion")
    private Date fechaCreacion;

    @OneToMany(mappedBy = "empresa", cascade = CascadeType.ALL, fetch = FetchType.EAGER)
    private List<Persona> personaList;
}

Persona.class

package com.demo.clase7.Entity;

import com.demo.clase7.Entity.Empresa;

import com.fasterxml.jackson.annotation.*;
import lombok.*;

import javax.persistence.*;
import java.io.Serializable;

@Data
@NoArgsConstructor
@AllArgsConstructor
@Entity(name = "persona")
@JsonIdentityInfo(generator = ObjectIdGenerators.PropertyGenerator.class, property = "id")
public class Persona {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
    private String nombre, email, direccion, telefono;

    @ManyToOne()
    @JoinColumn(name = "empresa_id")
    private Empresa empresa;
}

so when list Empresa (Company's), it gives me this result, which is correct

[
    {
        "id": 1,
        "razonSocial": "oswaldo",
        "ruc": "23aaasd2424",
        "representante": "silviopd222",
        "fechaCreacion": "1995-01-01T00:00:00.000 00:00",
        "personaList": [
            {
                "id": 4,
                "nombre": "oswal peña diaz",
                "email": "[email protected]",
                "direccion": "las viñas 149",
                "telefono": "234982734",
                "empresa": 1
            },
            {
                "id": 5,
                "nombre": "oswal peña diaz",
                "email": "[email protected]",
                "direccion": "las viñas 149",
                "telefono": "234982734",
                "empresa": 1
            }
        ]
    },
    {
        "id": 2,
        "razonSocial": "oswaldo",
        "ruc": "23aaasd2424",
        "representante": null,
        "fechaCreacion": null,
        "personaList": []
    },
    {
        "id": 4,
        "razonSocial": "silviopd",
        "ruc": "232424",
        "representante": "silviopd2",
        "fechaCreacion": "1992-01-01T00:00:00.000 00:00",
        "personaList": []
    }
]

so when I list Persona (people), it gives me this result which is wrong.

If you realize in the array it is made up of numbers

[
    {
        "id": 1,
        "nombre": "oswal peña diaz",
        "email": "[email protected]",
        "direccion": "las viñas 149",
        "telefono": "234982734",
        "empresa": null
    },
    {
        "id": 4,
        "nombre": "oswal peña diaz",
        "email": "[email protected]",
        "direccion": "las viñas 149",
        "telefono": "234982734",
        "empresa": {
            "id": 1,
            "razonSocial": "oswaldo",
            "ruc": "23aaasd2424",
            "representante": "silviopd222",
            "fechaCreacion": "1995-01-01T00:00:00.000 00:00",
            "personaList": [
                4,
                {
                    "id": 5,
                    "nombre": "oswal peña diaz",
                    "email": "[email protected]",
                    "direccion": "las viñas 149",
                    "telefono": "234982734",
                    "empresa": 1
                }
            ]
        }
    },
    5
]

database

CREATE SCHEMA clase7;


CREATE TABLE clase7.empresa
(
    id             bigint NOT NULL AUTO_INCREMENT PRIMARY KEY,
    fecha_creacion datetime,
    razon_social   varchar(255),
    representante  varchar(255),
    ruc            varchar(255)
) ENGINE = InnoDB
  AUTO_INCREMENT = 5
  DEFAULT CHARSET = utf8mb4;

CREATE TABLE clase7.persona
(
    id              bigint NOT NULL AUTO_INCREMENT PRIMARY KEY,
    direccion       varchar(255),
    email           varchar(255),
    nombre          varchar(255),
    telefono        varchar(255),
    empresa_id      bigint,
    id_persona      bigint NOT NULL,
    persona_list_id bigint
) ENGINE = InnoDB
  AUTO_INCREMENT = 6
  DEFAULT CHARSET = utf8mb4;

CREATE TABLE clase7.rol
(
    id     bigint NOT NULL AUTO_INCREMENT PRIMARY KEY,
    nombre varchar(255)
) ENGINE = InnoDB
  AUTO_INCREMENT = 5
  DEFAULT CHARSET = utf8mb4;

CREATE TABLE clase7.usuario
(
    id          bigint NOT NULL AUTO_INCREMENT PRIMARY KEY,
    password    varchar(255),
    username    varchar(255),
    empleado_id bigint
) ENGINE = InnoDB
  AUTO_INCREMENT = 5
  DEFAULT CHARSET = utf8mb4;

CREATE INDEX `FKrvl5v1dpvx13a46b6wxo0qx0j` ON clase7.persona (empresa_id);

CREATE INDEX `FKgot3jq0eng9lvyja174qoe1a5` ON clase7.persona (persona_list_id);

CREATE INDEX `FK44o5rsj3cs2hsw2gkg3056ivm` ON clase7.usuario (empleado_id);

CREATE INDEX `FK3hkcdmd3tnvqg683r4cf0mgpn` ON clase7.empresa_persona_list (empresa_id);

ALTER TABLE clase7.empresa_persona_list
    ADD CONSTRAINT `FK3hkcdmd3tnvqg683r4cf0mgpn` FOREIGN KEY (empresa_id) REFERENCES clase7.empresa (id) ON DELETE NO ACTION ON UPDATE NO ACTION;

ALTER TABLE clase7.empresa_persona_list
    ADD CONSTRAINT `FK90f46adsww2o9oq1gf4100wdd` FOREIGN KEY (persona_list_id) REFERENCES clase7.persona (id) ON DELETE NO ACTION ON UPDATE NO ACTION;

ALTER TABLE clase7.persona
    ADD CONSTRAINT `FKgot3jq0eng9lvyja174qoe1a5` FOREIGN KEY (persona_list_id) REFERENCES clase7.empresa (id) ON DELETE NO ACTION ON UPDATE NO ACTION;

ALTER TABLE clase7.persona
    ADD CONSTRAINT `FKrvl5v1dpvx13a46b6wxo0qx0j` FOREIGN KEY (empresa_id) REFERENCES clase7.empresa (id) ON DELETE NO ACTION ON UPDATE NO ACTION;

ALTER TABLE clase7.usuario
    ADD CONSTRAINT `FK44o5rsj3cs2hsw2gkg3056ivm` FOREIGN KEY (empleado_id) REFERENCES clase7.persona (id) ON DELETE NO ACTION ON UPDATE NO ACTION;

INSERT INTO clase7.empresa(id, fecha_creacion, razon_social, representante, ruc)
VALUES (1, '1994-12-31', 'oswaldo', 'silviopd222', '23aaasd2424');
INSERT INTO clase7.empresa(id, fecha_creacion, razon_social, representante, ruc)
VALUES (2, null, 'oswaldo', null, '23aaasd2424');
INSERT INTO clase7.empresa(id, fecha_creacion, razon_social, representante, ruc)
VALUES (4, '1991-12-31', 'silviopd', 'silviopd2', '232424');
INSERT INTO clase7.persona(id, direccion, email, nombre, telefono, empresa_id, id_persona, persona_list_id)
VALUES (1, 'las viñas 149', '[email protected]', 'oswal peña diaz', '234982734', null, 0, null);
INSERT INTO clase7.persona(id, direccion, email, nombre, telefono, empresa_id, id_persona, persona_list_id)
VALUES (4, 'las viñas 149', '[email protected]', 'oswal peña diaz', '234982734', 1, 0, null);
INSERT INTO clase7.persona(id, direccion, email, nombre, telefono, empresa_id, id_persona, persona_list_id)
VALUES (5, 'las viñas 149', '[email protected]', 'oswal peña diaz', '234982734', 1, 0, null);
INSERT INTO clase7.rol(id, nombre)
VALUES (1, 'silviopd2');
INSERT INTO clase7.rol(id, nombre)
VALUES (2, 'oswal');
INSERT INTO clase7.rol(id, nombre)
VALUES (4, 'silviopd2');
INSERT INTO clase7.usuario(id, password, username, empleado_id)
VALUES (1, '232424', 'oswal', null);
INSERT INTO clase7.usuario(id, password, username, empleado_id)
VALUES (2, '232424ss', 'silviopd2', 1);
INSERT INTO clase7.usuario(id, password, username, empleado_id)
VALUES (4, '232424ss', 'silviopd2', 4);

CodePudding user response:

I found the solution, apparently the code @JsonIdentityInfo(generator = ObjectIdGenerators.PropertyGenerator.class, property = "id") allowed me not to generate infinite loops, but when making the list from person it was not listed very well.

There is an infinite loop when listing by company which is generated by the "company" object found in the Persona.class and at the same time there is an infinite loop when listing person that is generated by the list "personList" that is in Empresa.class.

To solve both loops do the following:

For the Empresa class we add @JsonIgnoreProperties("empresa")

For the Persona class we add @JsonIgnoreProperties("personaList")

I leave here the final code

Entity

Persona.class

package com.demo.clase7.Entity;


import com.fasterxml.jackson.annotation.*;
import lombok.*;

import javax.persistence.*;

@Data
@NoArgsConstructor
@AllArgsConstructor
@Entity(name = "persona")
//@JsonIdentityInfo(generator = ObjectIdGenerators.PropertyGenerator.class, property = "id")
public class Persona {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
    private String nombre, email, direccion, telefono;

    @ManyToOne(cascade = CascadeType.ALL)
    @JoinColumn(name = "empresa_id", referencedColumnName = "id")
    @JsonIgnoreProperties("personaList")
    private Empresa empresa;

}

Empresa.class

package com.demo.clase7.Entity;

import com.fasterxml.jackson.annotation.*;
import lombok.*;

import javax.persistence.*;
import java.util.*;

@Data
@NoArgsConstructor
@AllArgsConstructor
@Entity(name = "empresa")
//@JsonIdentityInfo(generator = ObjectIdGenerators.PropertyGenerator.class, property = "id")
public class Empresa {

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

    @Column(name = "razon_social")
    private String razonSocial;

    private String ruc, representante;

    @Column(name = "fecha_creacion")
    private Date fechaCreacion;

    @OneToMany(mappedBy = "empresa")
    @JsonIgnoreProperties("empresa")
    private List<Persona> personaList;
} 
  • Related