简体   繁体   中英

How to stop repeating sql query code?

I'm making a backend in java/tomcat and after repeating the code for a db insert again I was wondering if there was a way of reusing code.

The basic of an insert is the following.

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
    }
}

The only part I manage to reuse was the getConnection(); which is in the parent class.

But I would like to reuse more to prevent human error, maybe a way of mapping the models to the query or something.

Edit:

Great! thanks to all of you, I didn't knew of all of this frameworks but that's exactly what I needed. I still haven't figure out what I'm going to use because the project is already a bit long and I have to choose the best integration with the current code base.

If you don't want to use third-party frameworks like Spring and Hibernate then my suggestion is to use apache-commons DbUtils class, which provides JDBC common utility methods out of the box. https://commons.apache.org/proper/commons-dbutils/examples.html

Hibernate is also a good choice for object-relational mapping and reduce the amount of boiler code. http://docs.jboss.org/hibernate/orm/5.2/quickstart/html_single/

Spring jdbc is also a good choice, please refer this links for more details - https://docs.spring.io/spring/docs/4.0.x/spring-framework-reference/html/jdbc.html

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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