ActiveJDBC数据模型返回元数据而不是数据

时间:2015-10-29 21:06:04

标签: java mysql activejdbc

我正在使用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。

2 个答案:

答案 0 :(得分: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" ) ;

答案 1 :(得分:0)

正如您所说,模型不是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之前/之后打开和关闭连接。