Jpa查询部分字段的方法

场景

工作中在查询的时候,表的字段过多,只需要其中部分字段的信息,使用Springboot + jpa 查询数据。
表数据如下:
表结构

我需要查询其中的usernamenickname字段

解决方法

方法1:

一个字段的情况
dao层接口定义如下:

    /**
     * 单字段查询, 使用String接收
     */
    @Query(value = "select username from sys_user where id = ?1 ", nativeQuery = true)
    String findUsername(Integer id);

测试类:

@SpringBootTest(classes = Application.class)
@RunWith(SpringRunner.class)
@Slf4j
@ActiveProfiles("dev")
public class SysUserRepositoryTest {

    @Resource
    private SysUserRepository sysUserRepository;

    @Test
    public void findUsername() {
        String username = sysUserRepository.findUsername(1);
        System.out.println(username);
    }
}

运行结果:

多个字段使用map接收:

/**
     * 多个字段查询,使用Map接收
     */
    @Query(value = "select username, nickname from sys_user where id = ?1 ", nativeQuery = true)
    Map<String, Object> findUsernameAndNickName(Integer id);

测试:

@Test
    public void find(){
        Map<String, Object> usernameAndNickName = sysUserRepository.findUsernameAndNickName(1);
        System.out.println(usernameAndNickName.toString());;
    }

测试结果:

方法2:使用 JPQL。
通过创建不同参数的构造方法,使用构造器来接收不同的字段值。

详情可参考

原文地址:https://www.cnblogs.com/hnxbp/p/14945654.html