1

我正在使用 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 模型类:

public class Blog
extends Model {

}

现在,问题来了:当我导航到控制器处理的路径时,我得到了这个输出流:

{"frozen":false,"id":1,"valid":true,"new":false,"compositeKeys":null,"modified":false,"idName":"id","longId":1}

我可以说这是关于返回对象的元数据,因为这些集群的数量会根据我的参数而变化 - 即,当我全选时,有四个,当我使用参数时,我得到的数字与符合条件的相同,当我拉第一个时只有一个。我究竟做错了什么?有趣的是,当我恢复到旧的数据源并使用旧的 Connection/PreparedStatement/ResultSet 时,我能够很好地提取数据,所以问题不会出现在我的 Tomcat 的 context.xml 或路径中基地开放。

4

2 回答 2

0

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" ) ;
于 2015-10-29T21:43:26.583 回答
0

正如您已经说过的,模型不是字符串,因此将其转储到流中并不是最好的主意。由于您正在编写服务,因此您可能需要 JSON、XML 或其他形式的字符串。您的替代方案是:

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 之前/之后打开和关闭连接。

于 2015-10-30T15:06:33.047 回答