【发布时间】:2021-04-06 00:44:40
【问题描述】:
有两个表 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);
【问题讨论】:
标签: java spring spring-boot spring-data-jpa jpql