微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

JPQL 外键查询

如何解决JPQL 外键查询

有两个表 PersonEntity 和 cityentity。数据库中的PersonEntity 通过外部键fk_cityid 链接到cityentity。我需要选择具有给定 CityId 的 PersonEntity 表的所有记录(名称)。为此,Join 无处不在,但在这种情况下,我不需要 cityentity 表中的数据,只需要 PersonEntity 表的 name 字段。以下是类的说明:

@Entity
public class PersonEntity {
    private Long id;
    private String name;
    private CityEntity cityId;
}
@Entity
public class CityEntity {
    private Long id;
    private String name;
}

这是 HQL 查询

@Repository
public interface PersonEntityRepository extends JpaRepository<PersonEntity,Long> {
  @Query("select p.name FROM PersonEntity p where (p.name = :name or :name is null) " +
        "and (p.cityId = :cityId or :cityId is null)")
    List<PersonEntity> findByNameAndCity (
        @Param("name") String name,@Param("cityId") CityEntity cityId);
}

通过 id 尝试:

@Query("select p.name FROM PersonEntity p where (p.name = :name or :name is null) " +
        "and (p.cityId.id = :cityId or :cityId is null)")
    List<PersonEntity> findByNameAndCity (
        @Param("name") String name,@Param("cityId") Long cityId);

在这两种情况下,错误都是:“无法确定数据类型”。

调用函数的选项:

servisPerson.findByNameAndCity (null,cityId);

servisPerson.findByNameAndCity (name,null);

其实参数不止两个。为了简化,我只展示了两个。

servisPerson.findByNameAndCity (name,age,...,cityId);

解决方法

Person 实体应该看起来像这样

@Entity
public class PersonEntity {
     private Long id;
     private String name;

     @OneToOne
     @JoinColumn(name = "city_id")
     private CityEntity city;
}

您可以像这样编写查询

List<PersonEntity> findByNameAndCityOrNameIsNullOrCityIsNull(String name,CityEntity city);

Spring Data JPA 非常聪明,可以在幕后为您生成查询。

顺便说一句,你试图写 JPQL,而不是 HQL

EDIT(对长方法名评论的反应):

我建议避免创建 JPQL 查询,因为它更容易出错。如果你不喜欢冗长的方法名,你可以把它包装成更短的存储库中的默认方法:

@Repository
public interface PersonEntityRepository extends  JpaRepository<PersonEntity,Long> {
     List<PersonEntity> findByNameAndCityOrNameIsNullOrCityIsNull(String name,CityEntity city);
     
     default List<PersonEntity> shortName(String name,CityEntity city) {
         return findByNameAndCityOrNameIsNullOrCityIsNull(name,city);
     }
}

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。