JPA查询实体的部分属性值

发布时间 2023-06-15 19:00:47作者: sunny123456

JPA查询实体的部分属性值
https://blog.csdn.net/mojiewangday/article/details/128255531

背景

需要根据指定条件查询数据的部分字段,因此就不能使用jpa的findAll()方法了,因此选择利用@Query注解写sql实现,踩了几个坑,以此留作记录。

实现

1. 根据唯一id查询指定单个字段

	// 根据ou_code查询某一状态,nativeQuery的作用,指明value字段所写为sql语法
    @Query(value = "select escrow_status from tf_user where ou_code = ?1", nativeQuery = true)
    String findEscrowStatusByOuCode(String ouCode);
  • 1
  • 2
  • 3

2. 根据id集合查询多个字段合集

P.S: 必须指定别名,别名自动映射为map中的key

	// 根据ou_code查询ou_code和bizName属性并返回,需要注意必须写as指定别名
	@Query(value = "select  t.ouCode as ouCode, t.bizName as bizName  from com.uniev.thomas.dal.entity.TfOrganization t where t.ouCode in (?1)")
    List<Map<String, String>> listOuCodeAndBizNameInOuCode(Set<String> ouCodeSet);
  • 1
  • 2
  • 3