如何使用Spring repo映射到自定义对象的本机查询?

时间:2016-04-16 20:42:50

标签: mysql sql spring-data spring-data-jpa

我有桌子t1:

id | title
1  | title1
2  | title2

我有以下春季回购方法:

 @Query(nativeQuery = true, value = "select id, title from t1")
public List<T1> getAll();

自定义类是:

public class T1 {

@JsonProperty("id")
private Integer id;

@JsonProperty("title")
private String title;

public T1(Integer id, String title) {
    this.id = id;
    this.title = title;
}

public Integer getId() {
    return id;
}

public void setId(Integer id) {
    this.id = id;
}

public String getTitle() {
    return title;
}

public void setTitle(String title) {
    this.title = title;
}

}

我希望得到以下json回复:

{[{"id":1, "title":"titl1"}, {"id":2, "title":"titl2"}]}

但是我得到了这个:

[[1,"title1"],[2,"title2"]]

我正在使用@RestController

 @RequestMapping(method = RequestMethod.GET, value = "/test", produces = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntityTestResponse> test() {

    List<T1> list = testRepository.getAll();
    TestResponse response = new TestResponse(list);
    return new ResponseEntity<TestResponse>(response, HttpStatus.OK);
}

TestResponse类是:

public class TestResponse implements Serializable {

private TreeSet<T1> list = new TreeSet<>();

public TestResponse(TreeSet<T1> list) {
    this.list = list;
}
....

你可以帮忙吗?

2 个答案:

答案 0 :(得分:0)

这个响应是经典的Java List,如果你需要它作为JSON对象,你必须使用例如GSON然后你应该写这样的东西:

sonBuilder builder = new GsonBuilder();
Gson gson = builder.create();
System.out.println(gson.toJson(YOUR_LIST_OF_T1));

Here是示例(包括我写的)和here是GitHub回购。

答案 1 :(得分:0)

你可以通过覆盖 T1 类中的 toString()方法手动完成,如果你需要特定的签名,你没有任何API做你做的事情想。 所以,如果你尝试这样的事情

    List<T1> list = testRepository.getAll();
    StringBuilder strBuilder = new StringBuilder();
    for(T1 t : list){
        strBuilder.append(t.toString() + ", ");
    }
    String result = "";
    if(strBuilder.length()!=0){
        result = "{[" + strBuilder.substring(0, strBuilder.length()-2) + "]}";
    }
    System.out.println(result);

和类应该覆盖toString()方法

class T1{

@JsonProperty("id")
private Integer id;

@JsonProperty("title")
private String title;

public T1(Integer id, String title) {
    this.id = id;
    this.title = title;
}

public Integer getId() {
    return id;
}

public void setId(Integer id) {
    this.id = id;
}

public String getTitle() {
    return title;
}

public void setTitle(String title) {
    this.title = title;
}

@Override
public String toString() {
    return "{\"id:\"" + id + ", \"title:\"" + title + "}";
}

}

此外,如果您想使用纯Java标准库,您可以像下一个代码那样使用,但您需要下载 javax.json-xxxx.jar (例如&gt;&gt; javax.json-1.0.4.jar )(包括提供程序或实现)到您的库项目路径 但是下一个代码会生成类似

的内容
  

[{ “ID”:1, “标题”: “标题1”},{ “ID”:2 “标题”: “标题2”},{ “ID”:3 “标题”: “TITLE3” }]

    List<T1> list = testRepository.getAll();

    JsonArrayBuilder jsonArray = Json.createArrayBuilder();
    for(T1 t : list) {
        jsonArray.add(Json.createObjectBuilder()
            .add("id", t.getId())
            .add("title", t.getTitle()));
    }
    System.out.println(jsonArray.build());