To add a Find method to the parent class:
1 PackageCom.xxyh.jdbc.dao.refactor;2 Importjava.sql.Connection;3 Importjava.sql.PreparedStatement;4 ImportJava.sql.ResultSet;5 Importjava.sql.SQLException;6 Importcom.xxyh.jdbc.JdbcUtils;7 Importcom.xxyh.jdbc.dao.DaoException;8 Public Abstract classAbstractdao {9 Ten PublicObject Find (String sql, object[] args) { OneConnection conn =NULL; APreparedStatement PS =NULL; -ResultSet rs =NULL; - Try { theconn =jdbcutils.getconnection (); -PS =conn.preparestatement (SQL); - for(inti = 0;i < args.length; i++) -Ps.setobject (i+1, Args[i]); +rs =ps.executequery (); -Object obj =NULL; + while(Rs.next ()) { Aobj =RowMapper (RS); at } - returnobj; -}Catch(SQLException e) { - Throw Newdaoexception (E.getmessage (), e); -}finally { - Jdbcutils.close (RS, PS, conn); in } - } to + Abstract protectedObject RowMapper (ResultSet rs)throwsSQLException; - the /** * * Dynamic Update $ * @paramSQL UPDATE statementPanax Notoginseng * @paramargs need to pass in Parameters - * @returnreturns the number of result bars the */ + Public intUpdate (String sql, object[] args) { AConnection conn =NULL; thePreparedStatement PS =NULL; +ResultSet rs =NULL; - Try { $conn =jdbcutils.getconnection (); $PS =conn.preparestatement (SQL); - - for(inti = 0; i < args.length; i++) thePs.setobject (i+1, Args[i]); - Wuyi returnps.executeupdate (); the}Catch(SQLException e) { - Throw Newdaoexception (E.getmessage (), e); Wu}finally { - Jdbcutils.close (RS, PS, conn); About } $ } -}
Refine the implementation class:
1 PackageCom.xxyh.jdbc.dao.refactor;2 ImportJava.sql.ResultSet;3 Importjava.sql.SQLException;4 ImportCom.xxyh.jdbc.domain.User;5 Public classUserdaoimplextendsabstractdao{6 7 PublicUser Finduser (String name) {8String sql = "SELECT ID, Name, money, birthday from user where name=?";9object[] args =Newobject[] {name};TenObject user =Super. Find (sql, args); One return(user) user; A } - - Public voidDelete (user user) { theString sql = "Delete from user where id=?"; -object[] args =Newobject[] {user.getid ()}; - Super. Update (sql, args); - } + - Public voidUpdate (user user) { +String sql = "Udpate user set name=?,birthday=?,money=?" where id=? "; Aobject[] args =Newobject[] {user.getname (), User.getbirthday (), at User.getmoney (), User.getid ()}; - Super. Update (sql, args); - } - @Override - protectedUser RowMapper (ResultSet rs)throwsSQLException { -User User =NewUser (); inUser.setid (Rs.getint ("id")); -User.setname (rs.getstring ("name")); toUser.setmoney (Rs.getfloat ("Money")); +User.setbirthday (rs.getdate ("Birthday")); - returnuser; the } *}
JDBC Learning Note (21): Designing patterns using template methods