无法知道如何在两个表之间链接数据

时间:2016-06-30 09:33:38

标签: rest jdbc

我从javabrains网站学习RESTful网络服务。这里有一个名为Comments的部分,这与消息有关,但我无法知道如何将这两者联系起来。

下面是我的消息和评论的SQL表。

讯息

enter image description here

评论

enter image description here

这里基本上看起来都很相似(表设计),但值不同。我使用以下方法发送数据。

public Comment addComment(long messageId, Comment comment) throws Exception {
    Properties properties = new Properties();
    properties.load(getClass().getClassLoader().getResourceAsStream("/config.properties"));
    String userName = properties.getProperty("user");
    String password = properties.getProperty("pass");
    String url = properties.getProperty("Sqldburl");
    int key = 0;
    try {
        Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver").newInstance();
        Connection conn = DriverManager.getConnection(url, userName, password);
        String query = "select count(*) from Comments";
        PreparedStatement ps = conn.prepareStatement(query);
        ResultSet rs = ps.executeQuery();
        rs.next();
        key = rs.getInt(1);
    } catch (Exception e) {
        System.out.println(e);
    }

    try {
        Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver").newInstance();
        Connection conn = DriverManager.getConnection(url, userName, password);
        String query = "insert into Comments(id, message, author) values(?,?,?)";
        PreparedStatement ps = conn.prepareStatement(query);
        ps.setInt(1, key);
        ps.setString(2, comment.getMessage());
        ps.setString(3, comment.getAuthor());
        ps.executeQuery();
    } catch (Exception e) {
        System.out.println(e);
    }

    try {
        Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver").newInstance();
        Connection conn = DriverManager.getConnection(url, userName, password);
        String query = "select * from Comments where messageId=?";
        PreparedStatement ps = conn.prepareStatement(query);
        ps.setLong(1, messageId);
        ResultSet rs = ps.executeQuery();
        while (rs.next()) {
            comment.setAuthor(rs.getString("Author"));
            comment.setId(rs.getInt("Id"));
            comment.setMessage(rs.getString("message"));
        }
    } catch (Exception e) {
        System.out.println(e + "b3");
    }
    return comment;
}

编写完此代码后,我意识到我在Comments表格中确实添加了评论,但它与Messages无关联。

我知道一种方法,就是我在评论表中创建了一个新列并使用join操作,我需要在评论表中更新相同的messageId。但我想知道是否有更好的方法来完成这项工作,而不使用连接的概念。

MessageBean中,有一个声明如下的地图。

private Map<Long, Comment> comments = new HashMap<>();
@XmlTransient
public Map<Long, Comment> getComments() {
    return comments;
}

public void setComments(Map<Long, Comment> comments) {
    this.comments = comments;
}

我可以利用这一点来避免join吗?

0 个答案:

没有答案