JdbcTemplate需要是一个DataSource实例去实现数据库链接,如下面代码:
private BasicDataSource dataSource; private JdbcTemplate template; public TestServiceImpl() { dataSource = new BasicDataSource(); dataSource.setDriverClassName(driver); dataSource.setUrl(url); dataSource.setUsername(username); dataSource.setPassword(password); template = new JdbcTemplate(dataSource); }
Spring提供了很多数据访问模板,这里使用的是JDBC,当然你也可以使用,比如orm.jpa.jpaTemplate、orm.jdo.JdoTemplate等。
访问模板实例化好了,接下来就是代码的实现,这里会给出3个例子,getAll、getRow、add。取全部,取一行,插入一行数据,直接看代码:
public List<LxUserModel> getAll() { RowMapper<List<LxUserModel>> rowMapper = new RowMapper<List<LxUserModel>>() { @Nullable @Override public List<LxUserModel> mapRow(ResultSet rs, int i) throws SQLException { List<LxUserModel> list = new ArrayList<>(); ResultSetMetaData metaData = rs.getMetaData(); int closNum = metaData.getColumnCount(); do { LxUserModel m = new LxUserModel(); m.setId(rs.getInt(1)); m.setUsername(rs.getString(2)); m.setLoginPassword(rs.getString(3)); m.setNickname(rs.getString(4)); m.setRealName(rs.getString(5)); m.setEmail(rs.getString(6)); m.setMobile(rs.getString(7)); m.setSex(rs.getString(8)); m.setAge(rs.getInt(9)); m.setCreateTime(rs.getInt(10)); list.add(m); } while (rs.next()); return list; } }; List<LxUserModel> list = template.queryForObject("SELECT * FROM `lx_user` WHERE 1 ORDER BY id DESC", rowMapper, (Object[]) null); return list; }
调用模板方法queryForObject,返回的数据是一个List对象,这里需要我们实现RowMapper接口,并在mapRow方法中实现数据的组装。看完这里,如果你可以举一反三,那么不管是getRow还是getOne,我觉得对你而言都是很简单。下面来看看取一行的代码:
public LxUserModel getRow() { RowMapper<LxUserModel> rowMapper = new RowMapper<LxUserModel>() { @Nullable @Override public LxUserModel mapRow(ResultSet rs, int i) throws SQLException { LxUserModel m = new LxUserModel(); m.setId(rs.getInt(1)); m.setUsername(rs.getString(2)); m.setLoginPassword(rs.getString(3)); m.setNickname(rs.getString(4)); m.setRealName(rs.getString(5)); m.setEmail(rs.getString(6)); m.setMobile(rs.getString(7)); m.setSex(rs.getString(8)); m.setAge(rs.getInt(9)); m.setCreateTime(rs.getInt(10)); return m; } }; LxUserModel object = template.queryForObject("SELECT * FROM `lx_user` WHERE 1 ORDER BY id DESC limit 1", rowMapper, (Object[]) null); return object; }
同样实现了RowMapper接口,只是返回的方法不一样,简单吧?
现在来看看add的方法,插入一行数据,意味着需要执行一条SQL语句。
public int add(LxUserModel userModel) { String sql = "INSERT INTO `lx_user`(`username`, `loginPassword`, `nickname`, `createTime`) VALUES ('%s','%s','%s','%s')"; String finalSql = String.format(sql, userModel.getUsername(), userModel.getLoginPassword(), userModel.getNickname(), (System.currentTimeMillis() / 1000)); logger.info("sql {}", finalSql); class StatementCallback2 implements StatementCallback<Integer> { @Nullable @Override public Integer doInStatement(Statement statement) throws SQLException, DataAccessException { return statement.execute(finalSql) ? 1 : 0; } } template.execute(finalSql); class ResRowMapper implements RowMapper<Integer> { @Nullable @Override public Integer mapRow(ResultSet resultSet, int i) throws SQLException { return resultSet.getInt("id"); } } return template.queryForObject("select id from `lx_user` where 1 order by id desc limit 1", Integer.class); }
代码很直接粗暴,直接执行execute方法,这个方法是不会返回数据的,但是如果我们需要读取到刚刚插入数据的Id怎么办?这里返回使用
queryForObject方法只读取最后一行数据的id,并返回出去。