Spring JdbcTemplate (1)

前言

spring 的 JdbcTemplate 提供了很多操作JDBC的模板方法(需要注入数据源),操作简单同时也有局限性

JdbcDaoSupport  聚合了JdbcTemplate 。通过继承JdbcDaoSupport并实现MultTableTemplate(自定义)接口,来实现对JdbcTemplate进一步包装。一种模板设计模式的思想。


继承JdbcSupport

package com.learn.frame.spring.jdbc;

import javax.sql.DataSource;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.jdbc.core.support.JdbcDaoSupport;
import org.springframework.stereotype.Repository;

/**
 * spring jdbc使用
 * @author Administrator
 *
 */
@Repository("jdbcCustomerDao")
public class JdbcCustomerDao extends JdbcDaoSupport implements MultTableTemplate{
	
	
	@Autowired
	@Qualifier("dataSource")
	//Autowired按类型匹配  @Qualifier 明确确实注入哪个实现类
	public void setInject(DataSource dataSource){
		super.setDataSource(dataSource);
	}
	//MultTableTemplate接口扩展CRUD .....
}


dataSource为application.xml中配置的数据源bean对象


注入JdbcCustomerDao

package com.learn.frame.spring.service.impl;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.jdbc.core.support.JdbcDaoSupport;
import org.springframework.stereotype.Service;


import com.learn.frame.spring.po.User;
import com.learn.frame.spring.service.UserService;

@Service("userService2")
public class UserServiceImpl2 implements UserService{
	
	@Autowired //按类型自动匹配
	private JdbcDaoSupport template;
	
	
	@Override
	public User searchUserById(int id) throws Exception {
		String sql = "select * from user where id = ?";
		return template.getJdbcTemplate().queryForObject(sql, new Object[]{id}, new RowMapper<User>(){
			@Override
			public User mapRow(ResultSet rs, int rowNum) throws SQLException {
				User user = new User();
				user.setCd(rs.getInt("id"));
				user.setUsername(rs.getString("username"));
				user.setPassword(rs.getString("password"));
				user.setBirthday(rs.getDate("birthday"));
				user.setAddress(rs.getString("address"));
				return user;
			}
		});
	}

	.....
	
	
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值