如何为我的自定义@Query返回的列值创建自定义json对象 [英] How to create a custom json object to columns value returned from my custom @Query
问题描述
我对My SQL数据库有一个查询,我使用Spring Boot将其返回为Json格式. 我的问题是它只返回没有键的值,如:
I have a query to My SQL database and I use Spring Boot to return it to Json format. My problem is it only return value without key like:
[
[
"kermit",
6
]
]
我希望它返回:
[
[
"name":"kermit",
"count" :6
]
]
我尝试将Jackson注释jar文件添加到项目中,并在我的实体模型类中使用@JsonProperty:
I tried add Jackson Annotation jar file to project and use @JsonProperty in my entity model class:
@Entity
@Table(name = "act_id_membership", schema = "activiti", catalog = "")
@IdClass(ActIdMembershipEntityPK.class)
public class ActIdMembershipEntity {
@JsonProperty("name")
private String userId;
@JsonProperty("group")
private String groupId;
@Id
@Column(name = "USER_ID_")
public String getUserId() {
return userId;
}
public void setUserId(String userId) {
this.userId = userId;
}
@Id
@Column(name = "GROUP_ID_")
public String getGroupId() {
return groupId;
}
public void setGroupId(String groupId) {
this.groupId = groupId;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
ActIdMembershipEntity that = (ActIdMembershipEntity) o;
return Objects.equals(userId, that.userId) &&
Objects.equals(groupId, that.groupId);
}
@Override
public int hashCode() {
return Objects.hash(userId, groupId);
}
}
但是它仍然没有密钥返回.我现在该怎么办?请帮我! 非常感谢你!
But it still return without key. What I should do now? Please help me! Thank you very much!
推荐答案
首先,我同意那些评论无效JSON格式的人.您可以在此处查看示例 https://json.org/example.html
First, I'm agree with guy who commented that is not valid JSON format. You can see examples here https://json.org/example.html
第二,您需要创建一个对象JSON,其中包含所需的字段,例如:
Second, You need to create an object JSON which has fields needed for example:
public class UserStat es implements Serializable {
private String name;
private long count;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public long getCount() {
return count;
}
public void setCount(long count) {
this.count = count;
}
}
并在您的自定义查询中.根据这种方式,您的报酬看起来像这样:
And in your custom query. Based your return looks like on this way:
@Query("SELECT u.name, count(u) FROM User u")
public List<UserStat> findUserStat() ;
这篇关于如何为我的自定义@Query返回的列值创建自定义json对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!