利用模板模式重构JDBC操作业务场景
Posted 前进道路上的程序猿
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了利用模板模式重构JDBC操作业务场景相关的知识,希望对你有一定的参考价值。
前言
模板模式是指定义一个算法的骨架,并允许子类为一个或者多个步骤提供实现。JDBC操作业务是运用模板模式一个很典型的场景,下面我们就利用模板模式重构JDBC操作业务场景
案例
我们以查询为例,首先我们定义一个RowMapper接口,这个接口定义了mapRow方法,用于实现实体关系映射
RowMapper:
public interface RowMapper<T>
T mapRow(ResultSet rs,int rowNum) throws Exception;
接下来,我们定义JdbcTemplate这个模板类,在模板类的查询方法中,我们定义实现查询的骨架,实现共同的部分,并且根据传递的参数实现差异化的实现
JdbcTemplate :
public class JdbcTemplate
private DataSource dataSource;
public JdbcTemplate(DataSource dataSource)
this.dataSource = dataSource;
public List<?> executeQuery(String sql, RowMapper<?> rowMapper, Object[] values)
try
Connection conn = this.getConnection();
PreparedStatement pstm = this.createPrepareStatement(conn,sql);
ResultSet rs = this.executeQuery(pstm,values);
List<?> result = this.paresResultSet(rs,rowMapper);
this.closeResultSet(rs);
this.closeStatement(pstm);
this.closeConnection(conn);
return result;
catch (Exception e)
e.printStackTrace();
return null;
protected void closeConnection(Connection conn) throws Exception
conn.close();
protected void closeStatement(PreparedStatement pstm) throws Exception
pstm.close();
protected void closeResultSet(ResultSet rs) throws Exception
rs.close();
protected List<?> paresResultSet(ResultSet rs,RowMapper<?> rowMapper) throws Exception
List<Object> result = new ArrayList<Object>();
int rowNum = 1;
while(rs.next())
result.add(rowMapper.mapRow(rs,rowNum++));
return result;
protected ResultSet executeQuery(PreparedStatement pstm,Object[] values) throws Exception
for(int i=0;i<values.length;i++)
pstm.setObject(i,values[i]);
return pstm.executeQuery();
protected PreparedStatement createPrepareStatement(Connection conn,String sql) throws Exception
return conn.prepareStatement(sql);
public Connection getConnection() throws Exception
return this.dataSource.getConnection();
定义model
Member :
public class Member
private String username;
private String password;
private String nickName;
private int age;
private String addr;
//get set方法
然后我们定义DAO继承这个模板类
MemberDao:
public class MemberDao extends JdbcTemplate
public MemberDao(DataSource dataSource)
super(dataSource);
public List<?> selectAll()
String sql = "select * from t_member";
return super.executeQuery(sql, new RowMapper<Member>()
@Override
public Member mapRow(ResultSet rs, int rowNum) throws Exception
Member member = new Member();
member.setUsername(rs.getString("username"));
member.setPassword(rs.getString("password"));
member.setAge(rs.getInt("age"));
member.setAddr(rs.getString("addr"));
return member;
,null);
我们可以看到MemberDao继承JdbcTemplate,然后在查询方法中调用JdbcTemplate的executeQuery方法,根据传进去的参数来生成相应的查询返回实体对象。
以上是关于利用模板模式重构JDBC操作业务场景的主要内容,如果未能解决你的问题,请参考以下文章