0

Hola tengo un problema al recuperar un registro de la bd, al hacerlo desde una clase que extiende de JpaRepository me devuelve el objeto pero con los datos a null y los datos estan dentro de un atributo target al que no se acceder.

Pongo capturas del repository:

Clase repository

Cuando ejecuto un simple select

Obtengo un $_hibernate_intercepto en vez del objeto y en el atributo target obtiene todos los atributos que tendria que tener el objeto

introducir la descripción de la imagen aquí

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

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

@Data
@Entity
@AllArgsConstructor
@NoArgsConstructor
@Table(name = "company")
public class Company implements Serializable {
    private static final long serialVersionUID = -1;

    @Id
    @SequenceGenerator(name = "pk_sequence_company", sequenceName = "id_company_seq", allocationSize = 1)
    @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "pk_sequence_company")
    @Column(name = "id", nullable = false)
    private Long id;

    @JoinColumn(name = "id_identifier_type", referencedColumnName = "id", nullable = false)
    @ManyToOne(optional = false, cascade = CascadeType.MERGE, fetch = FetchType.LAZY)
    private IdentifierType identifierType;

    @JoinColumn(name = "id_city", referencedColumnName = "id", nullable = false)
    @ManyToOne(optional = false, cascade = CascadeType.MERGE, fetch = FetchType.EAGER)
    private City city;

    @Column(name = "name", length = 50)
    private String name;

    @Column(name = "business_name", length = 50)
    private String businessName;

    @Column(name = "identifier", nullable = false, length = 12)
    private String identifier;

    @Column(name = "address", length = 50)
    private String address;

    @JoinColumn(name = "id_user", referencedColumnName = "id", nullable = false)
    @ManyToOne(optional = false, cascade = CascadeType.MERGE, fetch = FetchType.LAZY)
    private User user;

    @Column(name = "email", length = 500)
    private String email;

    @Column (name = "deprecated", nullable = false)
    private boolean deprecated;


}

Clase city


import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

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

@Data
@Entity
@AllArgsConstructor
@NoArgsConstructor
@Table(name = "city")
public class City implements Serializable {
    private static final long serialVersionUID = -1;

    @Id
    @SequenceGenerator(name = "pk_sequence_city", sequenceName = "id_city_seq", allocationSize = 1)
    @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "pk_sequence_city")
    @Column(name = "id", nullable = false)
    private Long id;

    @Column(name = "code", nullable = false, length = 66)
    private String code;

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

    @JoinColumn(name = "id_country", referencedColumnName = "id", nullable = false)
    @ManyToOne(optional = false, cascade = CascadeType.MERGE, fetch = FetchType.LAZY)
    private Country country;

    @Column (name = "deprecated", nullable = false)
    private boolean deprecated;


}

Clase Country

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

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

@Data
@Entity
@AllArgsConstructor
@NoArgsConstructor
@Table(name = "country")
public class Country implements Serializable {
    private static final long serialVersionUID = -1;

    @Id
    @SequenceGenerator(name = "pk_sequence_country", sequenceName = "id_country_seq", allocationSize = 1)
    @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "pk_sequence_country")
    @Column(name = "id", nullable = false)
    private Long id;

    @Column(name = "code", nullable = false, length = 66)
    private String code;

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

    @Column (name = "deprecated", nullable = false)
    private boolean deprecated;


}

En las sentencias SQL que tengo son estas:

      -- Create sequence:
    CREATE SEQUENCE id_company_seq
        INCREMENT 1
        START 1
        MINVALUE 1
        MAXVALUE 9223372036854775807
        CACHE 1;
    -- Create table: "company" definition
    CREATE TABLE "company" (
        "id" bigint NOT NULL DEFAULT nextval('id_company_seq'::regclass),
        "id_identifier_type" integer NOT NULL,
        "id_city" bigint,
        "name" character varying (66),
        "business_name" character varying (66),
        "identifier" character varying (12) NOT NULL,
        "address" character varying (500),
        "id_user" bigint NOT NULL,
        "email" character varying (80),
        "deprecated" boolean NOT NULL,
        CONSTRAINT pk_company PRIMARY KEY ("id"),
        CONSTRAINT fk_company_fk_id_identifier_type FOREIGN KEY ("id_identifier_type") REFERENCES "identifier_type"("id"),
        CONSTRAINT fk_company_fk_id_city FOREIGN KEY ("id_city") REFERENCES "city"("id"),
        CONSTRAINT fk_company_fk_id_user FOREIGN KEY ("id_user") REFERENCES "user"("id")
    
    
    
    
    );
    -- Create sequence:
CREATE SEQUENCE id_city_seq
    INCREMENT 1
    START 1
    MINVALUE 1
    MAXVALUE 9223372036854775807
    CACHE 1;
    -- Create table: "city" definition
    CREATE TABLE "city" (
        "id" bigint NOT NULL DEFAULT nextval('id_city_seq'::regclass),
        "code" character varying (66) NOT NULL,
        "name" character varying (20) NOT NULL,
        "id_country" bigint NOT NULL,
        "deprecated" boolean NOT NULL,
        CONSTRAINT pk_city PRIMARY KEY ("id"),
        CONSTRAINT fk_city_fk_id_country FOREIGN KEY ("id_country") REFERENCES "country"("id")
    
    );

-- Create sequence:
CREATE SEQUENCE id_country_seq
    INCREMENT 1
    START 1
    MINVALUE 1
    MAXVALUE 9223372036854775807
    CACHE 1;
-- Create table: "country" definition
CREATE TABLE "country" (
    "id" bigint NOT NULL DEFAULT nextval('id_country_seq'::regclass),
    "code" character varying (66) NOT NULL,
    "name" character varying (100) NOT NULL,
    "deprecated" boolean NOT NULL,
    CONSTRAINT pk_country PRIMARY KEY ("id")

);
-- Create sequence:
CREATE SEQUENCE id_country_seq
    INCREMENT 1
    START 1
    MINVALUE 1
    MAXVALUE 9223372036854775807
    CACHE 1;
-- Create table: "country" definition
CREATE TABLE "country" (
    "id" bigint NOT NULL DEFAULT nextval('id_country_seq'::regclass),
    "code" character varying (66) NOT NULL,
    "name" character varying (100) NOT NULL,
    "deprecated" boolean NOT NULL,
    CONSTRAINT pk_country PRIMARY KEY ("id")

);

Gracias a todos de antemano

3 respuestas 3

1

Ahí el problema está en la entidad Documento, seguramente está mal el mapeo jpa con la base de datos. Si puedes comparte el código de esa entidad para decirte con más detalles.

2
  • he editado la pregunta con otro ejemplo que me pasa lo mismo y he puesto la sentencias que ejecuto para generar las tablas, espero que sea todo lo que necesitamos para ver el problemas, muchisimas gracias ;) el 21 abr. 2022 a las 15:30
  • Pero dónde está la entidad Documento ??? Tienes la interfaz DocumentoRepository que hereda de JpaRepository usando la Entidad Documento con id de tipo Long <br/> public interface DocumentoRepository extends JpaRepository<Documento, Long> pero la entidad Documento no la pones y esa es clave porque tu pregunta va enficada a un findByDocumentos(...) de esa interfaz el 27 abr. 2022 a las 22:03
1

Yo manejo Springboot con JPA,

para consultas que no quiero que me devuelva nullos de mi parte yo utilizo consultas nativas de SQL

y coloco pues ya sea

(CASE WHEN xVariable is null then '' else xVariable end) as xVariable

Esto igual es cosa mia pero igual te dejo el manual de consultas de JPA por si te sirve de algo,

Spring Data JPA

y pues lo mio va enfocado a hacer consultas tipo:

@Query(value = "SELECT idcoleccionadordeprecios, CASE WHEN c.idPartida!=null then (SELECT componente FROM listadeprecios as l where l.idPartida=c.idPartida) else componente end as nombre,c.cantidad, CONCAT( \"$\",FORMAT(CASE WHEN \"MXP\"!=:moneda then c.precioUnitario*c.cantidad else c.precioUnitario*:dolar*c.cantidad END, 2)) as importe, CONCAT( \"$\", FORMAT(CASE WHEN \"MXP\"!=:moneda then c.precioUnitario else c.precioUnitario*:dolar END, 2)) as preciounitario, (case when unidad is null then '' else unidad end) as unidad FROM coleccionadordeprecios as c WHERE c.idMinicotizacion=:id AND c.cantidad>0", nativeQuery = true)
List<coleccionadordeprecios > findAllByIdMinicotizacion(@Param("id") MiniCotizacionBase mb,@Param("moneda") String moneda,@Param("dolar") float precioDolar);

Eso por mi parte, si te das cuenta estoy haciendo una consulta y recibo en una lista de objetos, mietras mantengan su nombre tu modelo no va a fallar y asi filtras tus nulos

0

Mi error fue que si tengo un objeto dentro de otro y al hacer una consulta quiero traerme también al hijo tengo que poner en jpa @ManyToOne(optional = false, cascade = CascadeType.MERGE, fetch = FetchType.EAGER)

Tu Respuesta

By clicking “Publica tu respuesta”, you agree to our terms of service and acknowledge you have read our privacy policy.

¿No es la respuesta que buscas? Examina otras preguntas con la etiqueta o formula tu propia pregunta.