首页 > 其他 > 详细

Jpa查询部分字段的方法

时间:2021-06-28 19:45:44      阅读:29      评论:0      收藏:0      [点我收藏+]

场景

工作中在查询的时候,表的字段过多,只需要其中部分字段的信息,使用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。
通过创建不同参数的构造方法,使用构造器来接收不同的字段值。

详情可参考

Jpa查询部分字段的方法

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

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!