java - EntityNotFoundException LEFT JOIN JPA - Hibernate

标签 java hibernate jpa

Exception in thread "main" javax.persistence.EntityNotFoundException: Unable to find CNPJ with id 00001388000307

我正在阅读jpa文档,我读到当它尝试访问(通过EntityManger接口(interface)的getReference方法)并且实体不存在时会抛出此异常

Thrown by the persistence provider when an entity reference obtained by EntityManager.getReference is accessed but the entity does not exist.

我有这个实体:Salesman e CNPJ。可能存在许多具有相同 CNPJ 的销售人员,换句话说,存在关系 @ManyToOne

这种关系正在发挥作用,好吧。

但是,当我尝试执行查询时

select r from Salesman r join fetch r.yearMonth left join fetch r.cnpj

为了给销售人员带来它的yearMonth(它正在工作!)关系和它的CNPJ关系,当我尝试做我提到的LEFT JOIN时,会抛出异常。

当我不执行LEFT JOIN时,效果很好,所有销售人员都有他的CNPJ,没有任何异常,BUUUUT,有些销售人员没有CNPJ,我也必须带上它们,有必要执行LEFT JOIN

@Entity
public class Salesman{

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

    @JoinColumn(name = "year_month")
    @ManyToOne
    private YearMonth yearMonth;

    private String cnpjS;

    @JoinColumn(name = "cnpj")
    @ManyToOne
    private CNPJ cnpj;

    public AnoMes getYearMonth() {
        return yearMonth;
    }

    public CNPJ getCnpj() {
        return cnpj;
    }

}

@Entity
public class CNPJ {

    @Id
    @Column(name = "CCG", length = 14)
    private String ccg;

    public String getCcg() {
        return ccg;
    }
}

Hibernate生成的select:

select *
from salesman s
inner join yearmonth y on s.ano_mes = y.id 
left outer join cnpj c on s.cnpjS = c.CCG

此咨询返回此值,rcnpj 是来自 Salesman 的 cnpj,bcnpj 来自 CNPJ。有些推销员带着 CNPJ NULL 来,我认为这就是问题所在。我不这么认为。

The return of the select

最佳答案

尝试使用<property name="show_sql">true</property>启用hibernate sql日志记录看看真实的查询( native ,在数据库上调用)是什么样子,也许在 hibernate 处理后有一个内部连接。

要更改它,您可以尝试 @Column(nullable=true)您的关系注释或 @Fetch(FetchMode.SELECT)看看真实的查询将如何变化。

<小时/>

原因是您引用了ID为00001388000307的cnpj,但cnpj这一行不存在。

您可以尝试使用@NotFound(action=NotFoundAction.IGNORE)跳过此类错误,但建议修复您的数据库以处理异常。

关于java - EntityNotFoundException LEFT JOIN JPA - Hibernate,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46735709/

相关文章:

java - 在 Hibernate 中,如何仅在序列化期间而不是在反序列化期间忽略属性

使用实体管理器关闭 hibernate session

java - 指定的大小超出了最大可表示大小

java - Spring Boot JPA 使用 Hibernate 在 TABLE 中插入大写名称

java - Spring Hibernate 中实体字段的本地化

java - JPA 将 BigDecimal 作为整数保存在数据库中

java - 我找不到 JAVAC.exe

java.lang.IllegalArgumentException : Illegal character in authority at index 7 while making https request 异常

java - 在 Android 中使用 ion 库将文件(多部分/表单数据)上传到服务器失败

java - Hibernate、OneToMany 关联 - 选择问题