[英]ActiveJDBC data model returning metadata instead of data
我正在使用JavaLite ActiveJDBC從本地MySQL服務器提取數據。 這是我簡單的RestController:
@RequestMapping(value = "/blogs")
@ResponseBody
public Blog getAllBlogs( )
throws SQLException {
Base.open( "com.mysql.jdbc.Driver", "jdbc:mysql://localhost:3306/rainydaymatt", "root", "" ) ;
List<Blog> blogs = Blog.where( "postType = 'General'" ) ;
return blogs.get( 0 ) ;
}
這是我的簡單模型,它擴展了ActiveJDBC Model類:
public class Blog
extends Model {
}
現在,這是問題所在:當我導航到控制器處理的路徑時,我得到以下輸出流:
{"frozen":false,"id":1,"valid":true,"new":false,"compositeKeys":null,"modified":false,"idName":"id","longId":1}
我可以說這是有關返回對象的元數據,因為這些簇的數量根據我的參數而變化-即,當我全選時,有四個,當我使用參數時,我得到的數字與滿足條件的數字相同,當我拉第一個時只有一個。 我究竟做錯了什么? 有趣的是,當我恢復到老式的DataSource並使用舊的Connection / PreparedStatement / ResultSet時,我能夠很好地提取數據,因此問題不會出在Tomcat的context.xml或路徑中。 Base.open。
ActiveJDBC模型不能作為原始輸出流轉出。 您需要執行類似的操作以將選擇范圍縮小到一個模型,然后參考其字段。
Base.open( "com.mysql.jdbc.Driver", "jdbc:mysql://localhost:3306/rainydaymatt", "root", "" ) ;
List<Blog> blogs = Blog.where( "postType = 'General'" ) ;
Blog tempBlog = blogs.get( 0 ) ;
return (String)tempBlog.get( "postBody" ) ;
正如您已經說過的,模型不是String,所以將其轉儲到流中並不是最好的主意。 由於您正在編寫服務,因此可能需要JSON,XML或某種其他形式的String。 您的替代方法是:
JSON:
public Blog getAllBlogs() throws SQLException {
Base.open( "com.mysql.jdbc.Driver", "jdbc:mysql://localhost:3306/rainydaymatt", "root", "" ) ;
String json = Blog.where( "postType = 'General'" ).toJson(false); ;
Base.close();
return json ;
}
XML:
public Blog getAllBlogs() throws SQLException {
Base.open( "com.mysql.jdbc.Driver", "jdbc:mysql://localhost:3306/rainydaymatt", "root", "" ) ;
String xml = toXml(true, false);
Base.close();
return xml;
}
地圖:
public Blog getAllBlogs() throws SQLException {
Base.open( "com.mysql.jdbc.Driver", "jdbc:mysql://localhost:3306/rainydaymatt", "root", "" ) ;
List<Map> maps = Blog.where( "postType = 'General'" ).toMaps() ;
String output = doWhatYouNeedToGenerateOutput(maps);
Base.close();
return output;
}
另外,我必須說您沒有關閉代碼中的連接,並且通常不建議在這種方法內部打開連接。 每個方法中的連接打開和關閉語句都會使您的代碼雜亂無章。 最好使用Servlet過濾器在特定URI之前/之后打開和關閉連接。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.