Tomato
Tomato

Reputation: 769

How to create a custom json object to columns value returned from my custom @Query

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
  ]
]

I want it return like:

[
  [
    "name":"kermit",
     "count" :6
  ]
]

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!

Upvotes: 1

Views: 861

Answers (1)

Jonathan JOhx
Jonathan JOhx

Reputation: 5968

First, I'm agree with guy who commented that is not valid JSON format. You can see examples here https://json.org/example.html

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() ;

Upvotes: 1

Related Questions