spring data jpa查询部分字段
第一种方法:使用 model 查询时转化
首先建立一个 model ,写上自己想要查询的字段,然后写上构造函数,这步很重要,因为spring jpa 转化时会调用这个构造方法
public class MyModel implements Serializable {
private String userName;
private String name;
private String gender;
private String description;
public MyModel() {};
public MyModel(String userName, String name, String gender, String description) {
this.userName = userName;
this.name = name;
this.gender = gender;
this.description = description;
}
}
然后在 dao 类中写查询方法
@Query(value = "select new pers.zhuch.model.MyModel(u.userName, ui.name, ui.gender, ui.description) from UserInfo ui, User u where u.id = ui.userId")
public List<MyModel> getAllRecord();
直接在查询语句中 new model 框架底层会调用它,然后返回这个对象(这里我写了完整的类路径,不写的时候它报错说找不到类型什么的)
然后就可以获得只有指定字段的 model 了。然后就把它转成 JSON 格式就 O 了。
第二种方法:在service 里边转换成 JSON
原理其实和第一种方法差不多,只是处理结果的方式不太一样,只是这种方法我们就不在 hql 中 new Model 了,直接写查询方法
@Query(value = "select new map(u.userName, ui.name, ui.gender, ui.description) from UserInfo ui, User u where u.id = ui.userId")
public List<Map<String, Object>> getCustomField();
直接new map(这里得是小写,不知道大写有木有问题,反正没试,编译器提示是要小写的)
然后返回的结果是这样的
[
{
"0": "admin",
"1": "你猜",
"2": "男",
"3": "一段描述"
}, {
"0": "abc",
"1": "你猜人家",
"2": "女",
"3": "没事先挂了"
}
]
注:多表联合查询附加额外字段,亦可使用此方法。例如
@Query("select new map(u as user,'hello' as ext) from User u where u.id=?1")
List<Map<String,Object>> findExtTest(Long id); @Query(value="select u.*,'hello' as ext from user u where u.id=?1",nativeQuery = true)
List<Object> findExtNativeTest(Long id); List<Map<String,Object>> rows = userRepository.findExtTest(10001l);
for(Map<String,Object> row :rows) {
User user = (User) row.get("user");
String ext = (String) row.get("ext");
System.out.println(user);
System.out.println(ext);
} List<Object> objects = userRepository.findExtNativeTest(10001l);
for(Object obj :objects) {
Object[] row = (Object[])obj;
Long id = ((BigInteger) row[0]).longValue();
String nickName = (String)row[17]; //数据库字段顺序
String ext = (String) row[row.length-1];
System.out.println(id);
System.out.println(nickName);
System.out.println(ext);
}
第三种方法:select语句部分字段使用默认值
@Query(value = "select u.user_name, ui.name, ui.gender,ui.description,'' as headImg from user_info u where u.id = 1",nativeQuery=true)
public List<User> getAllRecord();
参考文章:https://blog.csdn.net/zhu562002124/article/details/75097682