本文章摘编、转载需要注明来源 http://blog.csdn.net/shadowsick/article/details/8888187
网上这spring jdbctemplate的例子多如牛毛,我下面也继续再造一次轮子
第一步,先引入需要的包,这里不作详细说明
第二步,配置注解扫描,txManager是事务管理提供datasource就可以了
<aop:aspectj-autoproxy /> <!-- transaction manager, use JtaTransactionManager for global tx --> <bean id="txManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> <property name="dataSource" ref="dynamicDataSource" /> </bean> <!-- enable component scanning (beware that this does not enable mapper scanning!) --> <context:component-scan base-package="com.shadow" /> <!-- enable autowire --> <context:annotation-config /> <!-- enable transaction demarcation with annotations --> <tx:annotation-driven transaction-manager="txManager" />
<!-- JDBC模板 --> <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate"> <property name="dataSource" ref="dynamicDataSource" /> </bean>
/** * * @author shadow * @email [email protected] * @create 2012.04.28 * * @param <T> */ public abstract class AbstractBaseDao<T> implements DateFormatEntry { // SPRING JDBC模板接口 private JdbcTemplate jdbcTemplate; public JdbcTemplate getJdbcTemplate() { return jdbcTemplate; } @Resource public void setJdbcTemplate(JdbcTemplate jdbcTemplate) { this.jdbcTemplate = jdbcTemplate; } /** * 获取日期 * * @param timestamp * @return Date */ public Date getDate(Timestamp timestamp) { return toDate(timestamp, null); } /** * 获取日期 * * @param timestamp * @param format * @return Date */ public Date getDate(Timestamp timestamp, String format) { return toDate(timestamp, format); } /** * Timestamp按格式转换成Date * * @param timestamp * @param format * @return Date */ public Date toDate(Timestamp timestamp, String format) { Date date = null; if (null == format || "".equals(format)) format = DEFAULT_FORMAT; SimpleDateFormat sdf = new SimpleDateFormat(format); try { date = sdf.parse(sdf.format(timestamp)); } catch (ParseException e) { e.printStackTrace(); } return date; } }
public interface UserDao { public List<User> queryByUserName(String username); public int checkUser(String username); public List<User> queryForAll(); }
这里使用@Component("userDao"),相当于在xml配置里做一个<bean id="userDao" class="xxxxxx.UserDaoImpl"/>,然后我们在service调用就直接Resource("userDao")就能自动匹配这个实现类了
@Component("userDao") public class UserDaoImpl extends AbstractBaseDao<User> implements UserDao { public int checkUser(String username) { // TODO Auto-generated method stub return 0; } @SuppressWarnings("unchecked") public List<User> queryByUserName(String username) { String sql = "select t1.* from t_user t1 where t1.username = ?"; List<User> list = this.getJdbcTemplate().query(sql, new Object[] { username }, new UserMapper()); return list; } public List<User> queryForAll() { SqlRowSet rowSet = getJdbcTemplate().queryForRowSet(null); while (rowSet.next()) { } return null; } @SuppressWarnings("unchecked") private class UserMapper implements RowMapper { public Object mapRow(ResultSet rs, int i) throws SQLException { User vo = new User(); vo.setId(rs.getInt("id")); vo.setUsername(rs.getString("username")); vo.setPassword(rs.getString("password")); vo.setName(rs.getString("name")); return vo; } } }
public interface UserService { /** * 更新登录信息 * * @param user */ public void LoginForUpdate(User user); /** * 安全退出功能 * * @return String */ public String logout(); /** * 检测用户是否存在 * * @param username * @return Boolean */ public boolean checkUser(String username); /** * 通过用户名获取账号 * * @param username * @return List<User> */ public List<User> findByUserName(String username);
这里使用了的@Resource没有带参数就是默认使用接口类名首字母小写(例如接口是UserDao,默认匹配是userDao),@Transactional是事务的注解,可加各种参数设置,
具体请看帮助文档
@Transactional @Component("userService") public class UserServiceImpl implements UserService { @Resource private UserDao userDao; public void LoginForUpdate(User user) { // TODO Auto-generated method stub } public boolean checkUser(String username) { // TODO Auto-generated method stub return false; } public List<User> findByUserName(String username) { return this.userDao.queryByUserName(username); } public String logout() { // TODO Auto-generated method stub return null; } }
@RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration("classpath:application.xml") public class Junit { @Resource private UserService userService; @Test public void test() { for (int i = 0; i < 10; i++) { List<User> users = userService.findByUserName("3213231"); System.out.println("当前用户数:" + users.size()); } } }
附言,其实spring jdbctemplate是很灵活的,性能也很不错,你能使用queryForXX一类的方法返回map,也能返回原始ResultSet,当然也能使用回调接口映射成对象,我的例子里就是演示了如何把结果集映射成实体对象