在Spring中提供了对jdbc的封装类叫JdbcTemplate。它可以很方便的帮我们执行sql语句,操作数据库。
drop database if exists jdbctemplate;
create database jdbctemplate;
use jdbctemplate;
create table `employee` (
`id` int(11) primary key auto_increment,
`name` varchar(100) default null,
`salary` decimal(11,2) default null
);
insert into `employee`(`id`,`name`,`salary`)
values (1,'李三',5000.23),(2,'李四',4234.77),(3,'王五',9034.51),
(4,'赵六',8054.33),(5,'孔七',6039.11),(6,'曹八',7714.11);
select * from employee;
JdbcTemplate的使用需要在applicationContext.xml中进行配置
<!-- jdbcTemplate -->
<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
<property name="dataSource" ref="c3p0DataSource"/>
</bean>
@Test
public void test2() throws Exception {
// 实验2:将emp_id=5的记录的salary字段更新为1300.00
String sql = “update employee set salary = ? where id = ?”;
jdbcTemplate.update(sql, 1300, 5);
}
、
@Test
public void test3() throws Exception {
String sql = "insert into employee(`name`,`salary`) values(?,?)";
ArrayList<Object[]> params = new ArrayList<>();
params.add(new Object[] {"aaa",100});
params.add(new Object[] {"bbb",100});
params.add(new Object[] {"ccc",100});
jdbcTemplate.batchUpdate(sql, params);
}
创建一个Employee对象
public class Employee {
private Integer id;
private String name;
private BigDecimal salary;
@Test
public void test4() throws Exception {
// 实验4:查询id=5的数据库记录,封装为一个Java对象返回
String sql = "select id ,name ,salary from employee where id = ?";
/**
* 在queryRunner中使用的是ResultSetHandler
* 在Spring的jdbcTemplate中,使用RowMapper。
* BeanPropertyRowMapper 可以把一个结果集转成一个bean对象
*/
Employee employee = jdbcTemplate.queryForObject(sql, new BeanPropertyRowMapper(Employee.class), 5);
System.out.println(employee);
}
@Test
public void test5() throws Exception {
// 实验5:查询salary>4000的数据库记录,封装为List集合返回
String sql = "select id,name,salary from employee where salary > ?";
List<Employee> list = jdbcTemplate.query(sql, new BeanPropertyRowMapper(Employee.class), 4000);
System.out.println(list);
}
@Test
public void test6() throws Exception {
// 实验6:查询最大salary
String sql = "select max(salary) from employee";
BigDecimal salary = jdbcTemplate.queryForObject(sql, BigDecimal.class);
System.out.println(salary);
}
<!-- namedParameterJdbcTemplate -->
<bean id="namedParameterJdbcTemplate" class="org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate" >
<constructor-arg name="dataSource" ref="c3p0DataSource" />
</bean>
@ContextConfiguration(locations = "classpath:applicationContext.xml")
@RunWith(SpringJUnit4ClassRunner.class)
public class JdbcTest {
@Autowired
DataSource dataSource;
@Autowired
JdbcTemplate jdbcTemplate;
@Autowired
NamedParameterJdbcTemplate namedParameterJdbcTemplate;
@Test
public void test7() throws Exception {
// 实验7:使用带有具名参数的SQL语句插入一条员工记录,并以Map形式传入参数值
String sql = "insert into employee(`name`,`salary`) values(:name,:salary)";
Map<String, Object> param = new HashMap<String,Object>();
param.put("name", "小明");
param.put("salary", new BigDecimal(55));
namedParameterJdbcTemplate.update(sql, param);
}
@Test
public void test8() throws Exception {
// 实验8:重复实验7,以SqlParameterSource形式传入参数值
String sql = “insert into employee(name
,salary
) values(:name,:salary)”;
//通过一个bean对象的属性会自动赋值
SqlParameterSource sqlParameterSource = new BeanPropertySqlParameterSource(new Employee(0,
“小新”, new BigDecimal(11111)));
namedParameterJdbcTemplate.update(sql, sqlParameterSource);
}
创建Dao,自动装配JdbcTemplate对象
添加类
@Repository
public class EmployeeDao {
@Autowired
JdbcTemplate jdbcTemplate;
public int saveEmployee(Employee employee) {
String sql = "insert into employee(`name`,`salary`) values(?,?)";
return jdbcTemplate.update(sql, employee.getName(), employee.getSalary());
}
}
在applicationContext.xml中配置
<!-- 添加包扫描 -->
<context:component-scan base-package="com.atguigu" />
测试代码
@ContextConfiguration(locations = "classpath:applicationContext.xml")
@RunWith(SpringJUnit4ClassRunner.class)
public class JdbcTest {
@Autowired
DataSource dataSource;
@Autowired
JdbcTemplate jdbcTemplate;
@Autowired
NamedParameterJdbcTemplate namedParameterJdbcTemplate;
@Autowired
EmployeeDao employeeDao;
@Test
public void test9() throws Exception {
// 实验9:创建Dao,自动装配JdbcTemplate对象
employeeDao.saveEmployee(new Employee(null, "ssssss", new BigDecimal(999)));
}
@Repository
public class EmployeeDao extends JdbcDaoSupport {
@Autowired
protected void setDataSource2(DataSource dataSource) {
System.out.println("自动注入 + " + dataSource);
super.setDataSource(dataSource);
}
public int saveEmployee(Employee employee) {
String sql = "insert into employee(`name`,`salary`) values(?,?)";
return getJdbcTemplate().update(sql, employee.getName(), employee.getSalary());
}
}