</beans>
@Repository
@Transactional(readOnly = true)
public class UserDao {
@Resource
private JdbcTemplate jdbcTemplate;
/**
* 保存
*
* @param user
*/
@Transactional(readOnly = false)
public void save(final User user) {
// jdbcTemplate.execute(new ConnectionCallback() {
// public Object doInConnection(Connection conn) throws SQLException, DataAccessException {
// String sql = "insert into t_user(name, age) values (?, ?)";
// PreparedStatement ps = conn.prepareStatement(sql);
// ps.setString(1, user.getName()); // 第1个参数的索引是1
// ps.setInt(2, user.getAge());
// ps.execute();
// ps.close();
// return null;
// }
// });
String sql = "insert into t_user(name, age) values (?, ?)";
jdbcTemplate.update(sql, new Object[] { user.getName(), user.getAge() });
delete(1);
}
/**
* 删除
*
* @param id
*/
public void delete(Integer id) {
String sql = "delete from t_user where id=?";
jdbcTemplate.update(sql, new Object[] { id });
}
/**
* 更新
*
* @param user
*/
public void update(User user) {
String sql = "update t_user set name=?, age=? where id=?";
jdbcTemplate.update(sql, new Object[] { user.getName(), user.getAge(), user.getId() });
}
/**
* 根据id查询一个数据
*
* @param id
* @return
*/
public User getById(final Integer id) {
String sql = "select name,age from t_user where id=?";
return (User) jdbcTemplate.queryForObject(sql, new Object[] { id }, new RowMapper() {
public Object mapRow(ResultSet rs, int rowNum) throws SQLException {
String name = rs.getString(1);
int age = rs.getInt(2);
return new User(id, name, age);
}
});
}
@Transactional(isolation = Isolation.READ_COMMITTED)
public void testGet(int id) {
User user = getById(id);
System.out.println(user);
user = getById(id);
System.out.println(user);
}
/**
* 查询总数量
*
* @return
*/
public int getCount() {
String sql = "select count(*) from t_user";
return jdbcTemplate.queryForInt(sql);
}
/**
* 查询所有
*
* @return
*/
@SuppressWarnings("unchecked")
public List<User> findAll() {
String sql = "select id,name,age from t_user";
return jdbcTemplate.query(sql, new RowMapper() {
public Object mapRow(ResultSet rs, int rowNum) throws SQLException {
int id = rs.getInt(1);
String name = rs.getString(2);
int age = rs.getInt(3);
return new User(id, name, age);
}
});
}
/**
* 查询所有(分页)
*
* @param firstResult
* @param maxResult
* @return
*/
public QueryResult findAll(int firstResult, int maxResult) {
int count = jdbcTemplate.queryForInt("select count(*) from t_user");
List list = jdbcTemplate.query(//
"select id,name,age from t_user limit ?,?", //
new Object[] { firstResult, maxResult }, //
new RowMapper() {
public Object mapRow(ResultSet rs, int rowNum) throws SQLException {
int id = rs.getInt(1);
String name = rs.getString(2);
int age = rs.getInt(3);
return new User(id, name, age);
}
});
return new QueryResult(count, list);
}
}
public class QueryResult {
private int count;
private List list;
public QueryResult(int count, List list) {
this.count = count;
this.list = list;
}
。。。
}