如何停止重复sql查询代码?

时间:2018-04-10 04:44:33

标签: java design-patterns

我在java / tomcat中创建了一个后端,在重复db插入的代码后,我想知道是否有一种重用代码的方法。

插入的基本内容如下。

public class DBUser extends DB {

  public void insertUser(User user, Login login, XmppUser xmppUser) throws Exception
  {     
    Connection connection = this.getConnection(); // repeats

    try {
        PreparedStatement pstmt = connection.prepareStatement(DBvariables.UserContract.insert); // change query
        Password password = EncryptionService.createPassword(login);
        pstmt.setString(1, user.getMail().toString()); // slightly changes
        pstmt.setString(2, user.getUsername()); // slightly changes
        pstmt.setString(3, password.passwordHash); // slightly changes
        pstmt.setString(4, password.salt); // slightly changes
        pstmt.setString(5, xmppUser.getJID()); // slightly changes
        pstmt.setString(6, xmppUser.getPassword()); // slightly changes

        pstmt.execute(); // repeats
        connection.close(); // repeats

    } catch(SQLException e)
    {
        ServerException se = new ServerException(ExceptionsVariables.SQL_EXCEPTION,"SQL exception"); // repeats
        se.setParentException(e); // repeats
        throw  se; // repeats
    } finally {
        connection.close(); // repeats
    }
}

我设法重用的唯一部分是父类中的getConnection();

但是我想重复使用更多来防止人为错误,也许是将模型映射到查询或其他东西的方法。

修改

大!感谢大家,我不知道所有这些框架,但这正是我所需要的。我还没弄清楚我将要使用什么,因为该项目已经有点长了,我必须选择与当前代码库的最佳集成。

1 个答案:

答案 0 :(得分:0)

如果您不想使用Spring和Hibernate等第三方框架,那么我的建议是使用apache-commons DbUtils 类,它提供了开箱即用的JDBC常用实用程序方法。 https://commons.apache.org/proper/commons-dbutils/examples.html

Hibernate也是对象关系映射的一个很好的选择,并减少了锅炉代码的数量。 http://docs.jboss.org/hibernate/orm/5.2/quickstart/html_single/

Spring jdbc也是不错的选择,请参考此链接了解更多详情 - https://docs.spring.io/spring/docs/4.0.x/spring-framework-reference/html/jdbc.html