不管是nativequery仍是hql的query,均可以指定須要查詢的字段,只是必須定義這些字段所對應的實體,並且須要一個構造函數,構造函數的參數就是查詢的字段列表。舉個栗子:安全
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
複製代碼 |
@Entity
@Table(name="tcHuman")
@JsonInclude(JsonInclude.Include.NON_NULL)
public class Human {
@Id
@GeneratedValue(strategy = GenerationType.TABLE, generator = "tableKeyGenerator")
@TableGenerator(name = "tableKeyGenerator", table = "tcTableKeyGenerator",
pkColumnName = "pk_key", valueColumnName = "pk_value", pkColumnValue = "humanID",
initialValue = 1, allocationSize = 1)
private Integer humanID;
private String humanName;
//人員代碼
private String humanCode;
private String humanPassword;
private String description;
//所屬單位
private Integer unitID;
private Integer displayOrder;
private Integer identifyType;
private Integer activeFlag;
public Human() {
}
public Human(String humanName) {
this.humanName = humanName;
}
public Integer getHumanID() {
return humanID;
}
public void setHumanID(Integer humanID) {
this.humanID = humanID;
}
public String getHumanName() {
return humanName;
}
public void setHumanName(String humanName) {
this.humanName = humanName;
}
public String getHumanCode() {
return humanCode;
}
public void setHumanCode(String humanCode) {
this.humanCode = humanCode;
}
public String getHumanPassword() {
return humanPassword;
}
public void setHumanPassword(String humanPassword) {
this.humanPassword = humanPassword;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public Integer getUnitID() {
return unitID;
}
public void setUnitID(Integer unitID) {
this.unitID = unitID;
}
public Integer getDisplayOrder() {
return displayOrder;
}
public void setDisplayOrder(Integer displayOrder) {
this.displayOrder = displayOrder;
}
public Integer getIdentifyType() {
return identifyType;
}
public void setIdentifyType(Integer identifyType) {
this.identifyType = identifyType;
}
public Integer getActiveFlag() {
return activeFlag;
}
public void setActiveFlag(Integer activeFlag) {
this.activeFlag = activeFlag;
}
}
複製代碼 |
查詢人員的實體,我須要返回全部人員的名字。查詢以下:
bash
1
2
複製代碼 |
@Query("select new Human (h.humanName) from Human h ")
List<Human> getHumanList();
複製代碼 |
咱們須要查詢humanName,因此必需要有public Human(String humanName)這個構造函數,並且必須提供默認的構造函數,不然entity沒法構造。ide
這樣雖然方便,可是若是返回的字段偏多,那麼這個構造函數就參數列表就很長。這種狀況最好仍是用nativequery,定義的接口其返回類型爲List。函數
對於Object[]返回結果的處理若是想作成通用的,能夠參考下GSON的反序列化,經過傳遞T.class,經過反射去構造對象並設置字段。ui