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。
通過創建不同參數的構造方法,使用構造器來接收不同的字段值。

詳情可參考


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM