場景
工作中在查詢的時候,表的字段過多,只需要其中部分字段的信息,使用Springboot + jpa
查詢數據。
表數據如下:
我需要查詢其中的username
,nickname
字段
解決方法
方法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。
通過創建不同參數的構造方法,使用構造器來接收不同的字段值。