答覆ajax請求時存在一些小問題。最初,我有最簡單的寧靜服務,基於春季啓動MVC。Spring mvc restful - 錯誤的json回覆格式
模型:
import javax.persistence.*;
import java.util.*;
@Entity
@Table(name = "testmodel")
public class TestModel
{
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)//Postgresql sequence generator
private long id;
@Column(name = "name")
private String name;
@Column(name = "content")
private String content;
//Constructor
public TestModel()
{
}
//Id getter
public long getId()
{
return this.id;
}
//Name getter-setter
public String getName()
{
return this.name;
}
public void setName(String name)
{
this.name = name;
}
//Content getter-setter
public String getContent()
{
return this.content;
}
public void setContent(String content)
{
this.content = content;
}
}
DAO爲模型:
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import java.util.*;
public interface TetsModelDAO extends JpaRepository<Samples, Long>
{
@Query("SELECT s FROM TestModel s WHERE LOWER(s.name) LIKE LOWER(:entry) ORDER BY s.name")
List<TestModel> fetchByNameEntry(@Param("entry") String entry);
}
控制器:
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;
@RestController
@RequestMapping("/")
public class TestController
{
@Autowired
private TetsModelDAO testmodel;
@RequestMapping("/name")
public List<TestModel> getDatasetsByNameEntry(@RequestParam("entry") String entry)
{
return testmodel.fetchByNameEntry("%"+entry+"%");
}
}
客戶端AJAX請求:
$.ajax(
{
url : "/name?entry=", //get all records
method: "GET"
})
這個例子完美的作品 - 字符串化的回覆看起來像非標準JSON結構:
{"id":"1", "name":"John", "content":"blablabla1"}
{"id":"2", "name":"Sam", "content":"blablabla2"}
{"id":"3", "name":"Ken", "content":"blablabla3"}
然而,當我試圖定義JPQL查詢的Fileds明確(讀取,也就是說,只有ID和名領域),我得到錯誤的答覆結果。
DAO與修改後的查詢(不改變其他代碼):
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import java.util.*;
public interface TetsModelDAO extends JpaRepository<Samples, Long>
{
@Query("SELECT s.id, s.name FROM TestModel s WHERE LOWER(s.name) LIKE LOWER(:entry) ORDER BY s.name")
List<TestModel> fetchByNameEntry(@Param("entry") String entry);
}
在這種情況下的答覆是這樣的:
1, John, 2, Sam, 3, Ken
如何優雅地解決這個問題(而無需創建「輔助類」 )?
org.hibernate.hql.internal.ast.QuerySyntaxException:無法找到類[TestDto] [SELECT new TestDto(s.id,s.name)FROM TestModel s WHERE LOWER(s.name)LIKE LOWER(:entry ) 這是什麼? Class TestDto與TestDAO相同包 – gorill
您必須在@Query中指定您的類的完整名稱(包括包) - 只需將其添加到我的答案 –
非常感謝您的幫助)))) – gorill