繁体   English   中英

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

[英]How to stop repeating sql query code?

我正在用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(); 在父类中。

但是我想重用更多以防止人为错误,也许是将模型映射到查询之类的方法。

编辑:

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

如果您不想使用像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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM