Spring整合JDBC开发
Spring整合JDBC开发
背景
在JDBC开发中,充斥这大量重复的代码,可能只是换了个SQL语句,其他代码是完全不用变的。Spring的jar包里,提供了一个叫JDBCTemplate的模板,在保持操作灵活方便的情况下,将代码量降到最低。
配置文件
首先修改Spring的xml文件(src目录下),我这里采用的是c3p0数据源,如下图所示:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd">
<!-- 定义要扫描 controller的包 -->
<context:component-scan base-package="cn.com.restapi.controller" />
<context:component-scan base-package="cn.com.restapi.daoimpl"/>
<context:component-scan base-package="cn.com.restapi.serviceimpl"/>
<!-- 引用配置文件 -->
<context:property-placeholder location="classpath:jdbc.properties"/>
<mvc:default-servlet-handler />
<!-- 启动注解驱动 SpringMVC 功能 -->
<mvc:annotation-driven />
<!-- 配置视图解析器解析路径 -->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver" id="internalResourceViewResolver">
<!-- 定义视图存放路径 -->
<property name="prefix" value="/WEB-INF/jsp/" />
<!-- 定义视图后缀 -->
<property name="suffix" value=".jsp" />
</bean>
<!-- 1、声明数据源对象:C3P0连接池 -->
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
<!-- 加载jdbc驱动 -->
<property name="driverClass" value="${driverClass}"></property>
<!-- jdbc连接地址 -->
<property name="jdbcUrl" value="${jdbcUrl}"></property>
<!-- 连接数据库的用户名 -->
<property name="user" value="${user}"></property>
<!-- 连接数据库的密码 -->
<property name="password" value="${password}"></property>
<!-- 数据库的初始化连接数 -->
<property name="initialPoolSize" value="3"></property>
<!-- 数据库的最大连接数 -->
<property name="maxPoolSize" value="10"></property>
<!-- 数据库最多执行的事务 -->
<property name="maxStatements" value="100"></property>
<!-- 连接数量不够时每次的增量 -->
<property name="acquireIncrement" value="2"></property>
</bean>
<!-- 创建jdbcTemplate对象 -->
<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
<property name="dataSource" ref="dataSource">
</property>
</bean>
</beans>
properties文件(src目录下)如下图内容如下图所示:
然后写一个JDBCTemplate的类,里面的方法用于对数据进行增删改查操作。这里的JdbcTemplate属性,Spring容器会根据XML文件里的配置进行自动的注入。
package cn.com.restapi.daoimpl;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Repository;
import cn.com.restapi.dao.EmployeeDao;
import cn.com.restapi.model.Employee;
@Repository
public class EmployeeDaoImpl implements EmployeeDao{
@Autowired
private JdbcTemplate jdbcTemplate;
private Log log = LogFactory.getLog(EmployeeDaoImpl.class.getName());
@Override
public List<Employee> getEmployees() {
// TODO Auto-generated method stub
String sql = "SELECT EMPLOYEE_ID,EMPLOYEE_NAME,AGE,ADDRESS,SEX FROM EMPLOYEE";
log.info(sql);
return jdbcTemplate.query(sql, new EmployeeRowMapper());
}
@Override
public Employee getEmployeeByID(int id) {
// TODO Auto-generated method stub
String sql = "SELECT EMPLOYEE_ID,EMPLOYEE_NAME,AGE,ADDRESS,SEX FROM EMPLOYEE WHERE EMPLOYEE_ID = ?";
log.info(sql);
List<Employee> employees = this.jdbcTemplate.query(sql, new EmployeeRowMapper(),id);
if (employees.isEmpty()) {
return null;
}
return employees.get(0);
}
@Override
public int createEmployee(Employee employee) {
// TODO Auto-generated method stub
String sql = "INSERT INTO EMPLOYEE(EMPLOYEE_ID,EMPLOYEE_NAME,AGE,ADDRESS,SEX) VALUE(?,?,?,?,?)";
log.info(sql);
int rowNum = this.jdbcTemplate.update(sql,employee.getEmployeeID(),employee.getEmployeeName(),employee.getAge(),employee.getAddress(),employee.getSex());
return rowNum;
}
@Override
public int updateEmployee(Employee employee) {
// TODO Auto-generated method stub
String sql = "UPDATE EMPLOYEE SET EMPLOYEE_NAME = ?,AGE = ?,ADDRESS = ?,SEX = ? WHERE EMPLOYEE_ID = ?";
log.info(sql);
int rowNum = this.jdbcTemplate.update(sql,employee.getEmployeeName(),employee.getAge(),employee.getAddress(),employee.getSex(),employee.getEmployeeID());
return rowNum;
}
@Override
public int deleteEmployee(Employee employee) {
// TODO Auto-generated method stub
String sql = "DELETE EMPLOYEE WHERE EMPLOYEE_ID = ?";
log.info(sql);
int rowNum = this.jdbcTemplate.update(sql,employee.getEmployeeID());
return rowNum;
}
public class EmployeeRowMapper implements RowMapper<Employee>{
@Override
public Employee mapRow(ResultSet rSet, int rowNum) throws SQLException {
// TODO Auto-generated method stub
Employee employee = new Employee();
employee.setEmployeeID(rSet.getInt("EMPLOYEE_ID"));
employee.setEmployeeName(rSet.getString("EMPLOYEE_NAME"));
employee.setAddress(rSet.getString("ADDRESS"));
employee.setAge(rSet.getInt("AGE"));
employee.setSex(rSet.getString("SEX"));
return employee;
}
}
@Override
public boolean ifEmployeeExist(Employee employee) {
// TODO Auto-generated method stub
Employee employee2 = this.getEmployeeByID(employee.getEmployeeID());
if (employee2 == null) {
return true;
}
return false;
}
}
只要对JdbcCompany进行依赖注入,就可以调用使用了。以下是spring mvc rest服务中实现注入:
@RestController
public class CompanyController {
@Autowired
private JdbcCompany jdbcCompany;
@RequestMapping(value="/company",method = RequestMethod.GET)
public ResponseEntity<List<Company>> getAllCompany(){
List<Company> companies = new ArrayList<Company>();
companies = jdbcCompany.queryAllCompany();
if (companies.isEmpty()) {
return new ResponseEntity<List<Company>>(companies,HttpStatus.NO_CONTENT);
}
return new ResponseEntity<List<Company>>(companies,HttpStatus.OK);
}
@RequestMapping(value = "/company/{id}",method = RequestMethod.GET)
public ResponseEntity<List<Company>> getCompany(@PathVariable("id") String id){
List<Company> companies = null;
companies = jdbcCompany.queryCompany(id);
HttpStatus httpStatus = companies != null? HttpStatus.OK:HttpStatus.NOT_FOUND;
return new ResponseEntity<List<Company>>(companies,httpStatus);
}
}