spring3 jdbctemplate 注解实例
程序员文章站
2022-06-16 10:26:43
...
第二步,配置注解扫描,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" />
第三步,配置jdbctemplate的实例,同样提供一个datasource就可以了
- <!-- JDBC模板 -->
- <bean id="jdbcTemplate"
- class="org.springframework.jdbc.core.JdbcTemplate">
- <property name="dataSource" ref="dynamicDataSource" />
- </bean>
第四步,写个BaseDao方便下面的dao层调用,由于时间转换经常用到,这里只写了个通用的时间转换
- /**
- *
- * @author shadow
- * @email 124010356@qq.com
- * @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;
- }
- }
第五步,写个UserDao接口跟实现类
- 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;
- }
- }
- }
第六步,写service层调用dao的方法
- 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;
- }
- }
第七步,写junit测试
- @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());
- }
- }
- }
最后右键run as junit就ok了
附言,其实spring jdbctemplate是很灵活的,性能也很不错,你能使用queryForXX一类的方法返回map,也能返回原始ResultSet,当然也能使用回调接口映射成对象,我的例子里就是演示了如何把结果集映射成实体对象