1.添加开发环境
---ioc、aop、dao、jdbc、dbcp开发包
---添加applicationContext.xml配置文件
2.编写实体类Emp和操作数据库的EmpDao
package entity;
import java.io.Serializable;
public class Emp implements Serializable{
private Integer id;
private String name;
private Double salary;
private Integer age;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Double getSalary() {
return salary;
}
public void setSalary(Double salary) {
this.salary = salary;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
}
import entity.Emp;
@Repository
public class EmpDao {
@Resource
private JdbcTemplate template;
//增加
public void save(Emp emp){
String sql = "insert into emp(name,salary,age) values(?,?,?)";
Object[] params = {emp.getName(),emp.getSalary(),emp.getAge()};
template.update(sql, params);
}
//删除
public void delete(int id){
String sql = "delete from emp where id=?";
Object[] params={id};
template.update(sql, params);
}
//查询多行
public List<Emp> findAll(){
String sql = "select * from emp";
EmpRowMapper rowMapper = new EmpRowMapper();
List<Emp> list = template.query(sql, rowMapper);
return list;
}
//查询单行
public Emp findEmpById(int id){
String sql = "select * from emp where id=?";
Object[] params = {id};
EmpRowMapper rowMapper = new EmpRowMapper();
Emp emp = template.queryForObject(sql, params, rowMapper);
return emp;
}
}
当需要查询操作时,需要再写一个类用于将查询到的结果进行封装
public class EmpRowMapper implements RowMapper{
@Override
public Object mapRow(ResultSet rs, int index) throws SQLException {
Emp emp = new Emp();
emp.setId(rs.getInt("id"));
emp.setName(rs.getString("name"));
emp.setSalary(rs.getDouble("salary"));
emp.setAge(rs.getInt("age"));
return emp;
}
}
3.配置applicationContext.xml
<context:component-scan base-package="dao"></context:component-scan>
<bean id="template" class="org.springframework.jdbc.core.JdbcTemplate">
<property name="dataSource" ref="dbcp"></property>
</bean>
<bean id="dbcp" class="org.apache.commons.dbcp.BasicDataSource">
<property name="username" value="root"></property>
<property name="password" value="123456"></property>
<property name="driverClassName" value="com.mysql.jdbc.Driver"></property>
<property name="url" value="jdbc:mysql:///mybatis"></property>
</bean>
4.进行测试操作
public class TestEmp {
public static void main(String[] args) {
String conf = "applicationContext.xml";
ApplicationContext ac = new ClassPathXmlApplicationContext(conf);
EmpDao empDao = ac.getBean("empDao",EmpDao.class);
//测试增加
Emp emp = new Emp();
emp.setName("xiaolv");
emp.setSalary(200.0);
emp.setAge(20);
empDao.save(emp);
//测试删除
empDao.delete(1);
//测试多行查询
List<Emp> list = empDao.findAll();
for(Emp e : list){
System.out.println(e.getId()+":"+e.getName()+":"+e.getSalary()+":"+e.getAge());
}
//测试单行查询
Emp emp1 = empDao.findEmpById(2);
System.out.println(emp1.getId()+":"+emp1.getName());
}
}