当前位置: 首页 > 知识库问答 >
问题:

Spring数据JPA-查询返回null-EmbeddedId

潘俊楚
2023-03-14

我有一个带有嵌入Id的类。当我尝试使用Jpa存储库进行搜索时,它只返回一个空对象。问题似乎出在嵌入式Id中,因为我用一个没有这个Id的类进行了测试,结果很好。

当我针对数据库进行测试时,JPA在控制台中输出的查询工作正常。

并且没有输出错误。

编辑:数据库中有数据

EDIT2:添加了equals和hashcode。

编辑3:findAll方法有效。

实体

import java.io.Serializable;

import javax.persistence.Column;
import javax.persistence.EmbeddedId;
import javax.persistence.Entity;
import javax.persistence.Table;

import org.joda.time.DateTime;

@Entity
@Table(name="C_INFO_CADASTRO")
public class Cliente implements Serializable {
    private static final long serialVersionUID = 1L;

    @EmbeddedId
    private ClienteId id;

    @Column(name="DAT_NASC")
    private DateTime dataNascimento;

    @Column(name="TXT_EMAIL")
    private String email;

    @Column(name="NOM_CLIENTE")
    private String nomeCliente;

    @Column(name="NUM_CPF")
    private Long numeroCpf;

    public ClienteId getId() {
        return id;
    }
    public void setId(ClienteId id) {
        this.id = id;
    }
    public DateTime getDataNascimento() {
        return dataNascimento;
    }
    public void setDataNascimento(DateTime dataNascimento) {
        this.dataNascimento = dataNascimento;
    }
    public String getEmail() {
        return email;
    }
    public void setEmail(String email) {
        this.email = email;
    }
    public String getNomeCliente() {
        return nomeCliente;
    }
    public void setNomeCliente(String nomeCliente) {
        this.nomeCliente = nomeCliente;
    }
    public Long getNumeroCpf() {
        return numeroCpf;
    }
    public void setNumeroCpf(Long numeroCpf) {
        this.numeroCpf = numeroCpf;
    }

@Override
    public int hashCode() {
        final int prime = 31;
        int result = 1;
        result = prime * result + ((email == null) ? 0 : email.hashCode());
        result = prime * result + ((id == null) ? 0 : id.hashCode());
        result = prime * result + ((numeroCpf == null) ? 0 : numeroCpf.hashCode());
        return result;
    }
    @Override
    public boolean equals(Object obj) {
        if (this == obj)
            return true;
        if (obj == null)
            return false;
        if (getClass() != obj.getClass())
            return false;
        Cliente other = (Cliente) obj;
        if (email == null) {
            if (other.email != null)
                return false;
        } else if (!email.equals(other.email))
            return false;
        if (id == null) {
            if (other.id != null)
                return false;
        } else if (!id.equals(other.id))
            return false;
        if (numeroCpf == null) {
            if (other.numeroCpf != null)
                return false;
        } else if (!numeroCpf.equals(other.numeroCpf))
            return false;
        return true;
    }
}

嵌入ID

import java.io.Serializable;

import javax.persistence.Column;
import javax.persistence.Embeddable;

@Embeddable
public class ClienteId implements Serializable{
    private static final long serialVersionUID = 1L;

    @Column(name="COD_EMP")
    private Long codigoEmpresa;

    @Column(name="COD_FIL")
    private Long codigoFilial;

    @Column(name="NUM_CLI")
    private Long numeroCliente;


    public Long getCodigoEmpresa() {
        return codigoEmpresa;
    }

    public void setCodigoEmpresa(Long codigoEmpresa) {
        this.codigoEmpresa = codigoEmpresa;
    }

    public Long getCodigoFilial() {
        return codigoFilial;
    }

    public void setCodigoFilial(Long codigoFilial) {
        this.codigoFilial = codigoFilial;
    }

    public Long getNumeroCliente() {
        return numeroCliente;
    }

    public void setNumeroCliente(Long numeroCliente) {
        this.numeroCliente = numeroCliente;
    }

@Override
    public int hashCode() {
        final int prime = 31;
        int result = 1;
        result = prime * result + ((codigoEmpresa == null) ? 0 : codigoEmpresa.hashCode());
        result = prime * result + ((codigoFilial == null) ? 0 : codigoFilial.hashCode());
        result = prime * result + ((numeroCliente == null) ? 0 : numeroCliente.hashCode());
        return result;
    }

    @Override
    public boolean equals(Object obj) {
        if (this == obj)
            return true;
        if (obj == null)
            return false;
        if (getClass() != obj.getClass())
            return false;
        ClienteId other = (ClienteId) obj;
        if (codigoEmpresa == null) {
            if (other.codigoEmpresa != null)
                return false;
        } else if (!codigoEmpresa.equals(other.codigoEmpresa))
            return false;
        if (codigoFilial == null) {
            if (other.codigoFilial != null)
                return false;
        } else if (!codigoFilial.equals(other.codigoFilial))
            return false;
        if (numeroCliente == null) {
            if (other.numeroCliente != null)
                return false;
        } else if (!numeroCliente.equals(other.numeroCliente))
            return false;
        return true;
    }
}

存储库

import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Component;

import io.swagger.annotations.Api;


    @Api
    @Component
    public interface ClienteRepository extends JpaRepository<Cliente, ClienteId> {

        Cliente findByNumeroCpf(@Param("numeroCpf") Long numeroCpf);

        Cliente findByEmail(@Param("email") String email);  
    }

服务

import javax.inject.Inject;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;

import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

@Component
@Path("/cliente")
@Transactional
public class ClienteService {

    @Inject
    private ClienteRepository repository;

    @Inject
    private CodMarcaRepository marcaRepository;

    @GET
    @Path("/cpf/{numeroCpf}")
    @Produces(MediaType.APPLICATION_JSON)
    @Transactional(readOnly=true)
    public Response findByCpf(@PathParam("numeroCpf") Long numeroCpf){
        Cliente cliente = repository.findByNumeroCpf(numeroCpf);

        if(cliente != null){
            return Response.ok().entity(cliente).build();
        } else {
            return Response.status(404).entity(new Cliente()).build();
        }
    }

    @GET
    @Path("/email/{email}")
    @Produces(MediaType.APPLICATION_JSON)
    public Response findByEmail(@PathParam("email") String email){
        Cliente cliente = repository.findByEmail(email);

        if(cliente != null){
            return Response.ok().entity(cliente).build();
        } else {
            return Response.status(404).entity(new Cliente()).build();
        }
    }
}

正如你所看到的,我的服务中有两种方法,一种是通过cpf查找,另一种是通过电子邮件查找,但都不起作用。我还尝试创建一个方法来通过组合主键进行查找,但它也不起作用。

任何帮助都将被感激,因为我不知道还能做什么。

共有1个答案

魏宸
2023-03-14

我不确定这是否是您遇到的问题的根源,但您没有重写可嵌入类的hashCode()。如果要将该类用作嵌入ID,则必须使用该类。

 类似资料:
  • 我们使用1.3.5版本创建了一个spring boot项目。我们的应用程序与Mysql数据库交互。我们创建了一组JPA存储库,在其中我们使用了findAll、findOne和其他自定义查询方法。 我们正面临一个随机出现的问题。以下是复制它的步骤: > 使用spring启动应用程序在数据库上启动读取查询。 现在,使用mysql-console手动更改上面读取查询返回的记录的Mysql中的数据。 再次

  • 问题内容: 我的查询如下所示: 到目前为止,一切都很好。即使playerShips为空,我也正在获得Pilot实例。 现在,我只想获取不活动的船只,因此我将查询修改为如下所示: 而且我作为飞行员变得空无一人,所以它显然行不通。 如果有人可以向我解释如何使用适用于子元素的WHERE子句创建JOIN FETCH查询,我将感到非常高兴。提前致谢。 问题答案: 经过大量研究,我决定实现一个自定义存储库,以

  • 我正在使用JDBC创建一个数据库,其中包含表和。两者都有一个名为 以下是我创建和填充表的SQL语句: 我试图运行以下查询: 或 或 使用 但是我没有得到任何结果。 这两个问题都可以解决。 SQLite数据库服务器显示相同的问题: 它与Firefox中的SQLite Manager一起工作。

  • 我有3个实体在我的数据库。实体A具有主密钥PK-A,实体B具有主密钥PK-B,实体C具有主密钥PK-C。 实体A与实体B具有1对多关系,实体B与实体C具有1对多关系 我想在Spring Data JPA中基于PK-A(实际上是实体B中的外键)查询实体C。有可能吗? 但这行不通。还有什么建议我可以试试吗?

  • 我有一个遗留数据库(实际上是Cobol文件),我正在使用Hibernate/JPA的专有JDBC驱动程序访问它。 实体有一个包含2列的复合主键:和。 在遗留数据中有相同的记录,这些记录可以具有的特定值,也可以在表示'All Sites'的列中具有NULL的记录。该文件的理论是,如果您找不到特定的SITE的,那么您可以在中使用NULL查找记录(the'catk-all')。 我不能改变这个“表”的结

  • 我正在用jpa处理spring boot,我尝试使用onetomany,由于某种原因,当我尝试在postman上发送请求时,它创建了我的父对象,但没有使用子外键,因此我得到了null。 还有一件事:有一次我玩了我的代码,不知怎么的,我让它工作了,但它只成功了一次,现在它不再工作了。我试图在网上学习很多教程,但没有一个帮助我解决这个问题。