Home > Software engineering >  Can't access a property of a Embedded class via JPA
Can't access a property of a Embedded class via JPA

Time:12-01

@Entity
@EntityListeners(AuditingEntityListener.class)
@Inheritance(strategy = InheritanceType.SINGLE_TABLE)
@DiscriminatorColumn(name = "TIPO_CONTRATO", discriminatorType = DiscriminatorType.STRING)
@JsonIgnoreProperties({ "hibernateLazyInitializer", "handler" })
public class Contrato extends AuditorEntity implements Serializable, Clonable {
   
   @Column(name = "CIF_NIF")
   @JsonView(Views.Buscador.class)
   @JsonProperty("cifNif")
   private String cifNif;

   @Column(name = "NOMBRE_SOCIEDAD_PERSONA")
   @JsonView(Views.Buscador.class)
   private String nombreSociedadPersona;
}

And i have this Embeddable class called CuentaBancaria from Contrato table:

@Embeddable
public class CuentaBancaria implements Serializable {
    
    private static final long serialVersionUID = 6835775213299596371L;

    @Column(name = "TITULAR_CUENTA")
    @JsonView(Views.Completo.class)
    private String titularCuenta;
}

In ContratoRepository i'm trying doing a JPA Query finding the "titularCuenta" field of Cuenta Bancaria finding by the cifNif field of Contrato. But it's not working. What can i do to solve this?

@Query(value="SELECT c.CuentaBancaria.titularCuenta FROM Contrato c WHERE c.cifNif= ?1 AND c.nombreSociedadPersona IS NOT NULL AND ROWNUM = 1")
    public String getNombreLegalCliente(String cifNif);

The error which is throwing:

Caused by: org.hibernate.QueryException: could not resolve property: CuentaBancaria of: com.xxxx.Contrato

CodePudding user response:

You're missing CuentaBancaria field in Contrato class. That's why JQL complains.

Add the field in the class with @Embedded annotation:

public class Contrato extends AuditorEntity implements Serializable, Clonable {
    @Embedded
    private CuentaBancaria cuentaBancaria;
}

And fix the JQL expression to:

@Query(value="SELECT c.cuentaBancaria.titularCuenta FROM Contrato c WHERE c.cifNif= ?1 AND c.nombreSociedadPersona IS NOT NULL AND ROWNUM = 1")
    public String getNombreLegalCliente(String cifNif);
  • Related