【问题标题】:ActiveJDBC data model returning metadata instead of dataActiveJDBC 数据模型返回元数据而不是数据
【发布时间】:2015-10-29 21:06:03
【问题描述】:

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

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

【问题讨论】:

    标签: java mysql activejdbc


    【解决方案1】:

    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" ) ;
    

    【讨论】:

    • 实际上你可以在这里遇到问题,因为:return (String)tempBlog.get( "postBody" ) ; 可以抛出 ClassCastException。你需要:return tempBlog.getString( "postBody" ) ;
    【解决方案2】:

    正如您已经说过的,模型不是字符串,因此将其转储到流中并不是最好的主意。由于您正在编写服务,因此您可能需要 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 之前/之后打开和关闭连接。

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-01-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-01-13
    • 1970-01-01
    • 2015-08-15
    相关资源
    最近更新 更多