繁体   English   中英

JPQL 外键查询

[英]JPQL query by foreign key

有两个表 PersonEntity 和 cityentity。 数据库中的 PersonEntity 通过外部键 fk_cityid 链接到 cityentity。 我需要 select 具有给定 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);

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

调用 function 的选项:

servisPerson.findByNameAndCity (null, cityId);

或者

servisPerson.findByNameAndCity (name, null);

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

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

人实体应该看起来像这样

@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 数据 JPA 非常聪明,可以在后台为您生成查询。

顺便说一句,您尝试编写JPQL ,而不是HQL

编辑(对长方法名称的评论的反应):

我建议避免创建 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);
     }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM