Exception in thread "main" javax.persistence.EntityNotFoundException: Unable to find CNPJ with id 00001388000307
我正在阅读jpa文档,我读到当它尝试访问(通过EntityManger接口(interface)的getReference方法)并且实体不存在时会抛出此异常
我有这个实体: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 来,我认为这就是问题所在。我不这么认为。
最佳答案
尝试使用<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/