首先創建一個 model ,寫上本身想要查詢的字段,而後寫上構造函數,這步很重要,由於spring jpa 轉化時會調用這個構造方法java
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 類中寫查詢方法spring
@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 了。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": "沒事先掛了" } ]
注:多表聯合查詢附加額外字段,亦可以使用此方法。例如ui
@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); }
@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/75097682this