我正在执行一个查询,但它返回null
,但是当我在 sql 行 cmd 中尝试时,它返回结果。
这是我的实体:
@Entity
@Table(name = "appel_offre", catalog = "ao")
public class AppelOffre implements java.io.Serializable {
private Integer idAppelOffre;
...
private Admin userValidation;
private Admin userSaisie;
private Admin userControle;
....
public AppelOffre(Integer idAppelOffre,Admin userSaisie,Admin userControle,Admin userValidation) {
System.out.println("users"); // <-- code not executed
this.idAppelOffre = idAppelOffre;
this.userSaisie = userSaisie;
this.userControle = userControle;
this.userValidation = userValidation;
}
我的查询是:
@Query(" select new AppelOffre( ao.idAppelOffre , ao.userSaisie , ao.userControle , ao.userValidation ) from AppelOffre ao "
AppelOffre FindAOwithUsers(@Param("idao") Integer idao);
生成的查询是:
select appeloffre0_.ID_APPEL_OFFRE as col_0_0_, appeloffre0_.USER_SAISIE as col_1_0_, appeloffre0_.USER_CONTROLE as col_2_0_, appeloffre0_.USER_VALIDATION as col_3_0_
from ao.appel_offre appeloffre0_
inner join ao.admin admin1_ on appeloffre0_.USER_SAISIE=admin1_.ID
inner join ao.admin admin2_ on appeloffre0_.USER_CONTROLE=admin2_.ID
inner join ao.admin admin3_ on appeloffre0_.USER_VALIDATION=admin3_.ID
where appeloffre0_.ID_APPEL_OFFRE=?
我知道问题出在内部联接上,它们必须是左联接,因为在我的数据库中只有USER_SAISIE
,它不是null
。
我尝试用左连接这样:
@Query(" select new AppelOffre( ao.idAppelOffre , ao.userSaisie , ao.userControle , ao.userValidation ) from AppelOffre ao "
+ " left join ao.userSaisie "
+ " left join ao.userControle "
+ " left join ao.userValidation "
+ " where ao.idAppelOffre = :idao ")
AppelOffre FindAOwithUsers(@Param("idao") Integer idao);
但它在查询中生成了双倍:
Hibernate: select appeloffre0_.ID_APPEL_OFFRE as col_0_0_, appeloffre0_.USER_SAISIE as col_1_0_, appeloffre0_.USER_CONTROLE as col_2_0_, appeloffre0_.USER_VALIDATION as col_3_0_
from ao.appel_offre appeloffre0_
left outer join ao.admin admin1_ on appeloffre0_.USER_SAISIE=admin1_.ID
left outer join ao.admin admin2_ on appeloffre0_.USER_CONTROLE=admin2_.ID
left outer join ao.admin admin3_ on appeloffre0_.USER_VALIDATION=admin3_.ID
inner join ao.admin admin4_ on appeloffre0_.USER_SAISIE=admin4_.ID
inner join ao.admin admin5_ on appeloffre0_.USER_CONTROLE=admin5_.ID
inner join ao.admin admin6_ on appeloffre0_.USER_VALIDATION=admin6_.ID
where appeloffre0_.ID_APPEL_OFFRE=?
而且我的构造函数中的 System.out.println("users");
也没有显示。
为什么这不起作用以及如何解决这个问题
最佳答案
由于查询未返回任何结果,因此未调用构造函数。由于使用了内部联接,它没有返回任何结果,你是对的。要使其工作,请使用左连接,如下所示
@Query(" select new AppelOffre(ao.idAppelOffre, us, uc, uv) from AppelOffre ao left join ao.userSaisie us left join ao.userControle uc left join ao.userValidation uv "
关于mysql - JPA/Hibernate 中查询返回 null,但 mysql 中不返回 null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29630611/