[英]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.