一.Spring整合iBatis原理
Apache iBatis是当前IT项目中使用很广泛的一个半自动ORM框架,区别于Hibernate之类的全自动框架,iBatis对数据库的操作拥有更加灵活的控制,对于那些经常需要调用本地数据库函数自定义SQL语句,或是喜欢自己优化SQL执行效率的开发者来说,iBatis是一个非常不错的选择。而得到广泛应用的开源企业架构SpringFramework,也很好的将其进行了集成,使得iBatis在 SpringFramework中的使用更加便利、快捷。
开发者所要做的就是继承SpringFramework中提供的 SqlMapClientDaoSupport类即可。
1、SqlMapClientFactoryBean 的装配
SqlMapClientFactoryBean是SqlMapClientTemplate使用的基础,如果在SpringFramework应用中没有装配SqlMapClientFactoryBean,那么SqlMapClientTemplate将不可用,报空指针错误。
<bean id="sqlMapClient" class="org.springframework.orm.ibatis.SqlMapClientFactoryBean"> <property name="configLocation" value="/WEB-INF/sqlmap-config.xml"/> <!-- iBatis sqlmap config 文件位置 --> <property name="dataSource" ref="dataSource"/> <!-- 在SpringFramework配置文件中使用的数据源 --> <property name="lobHandler" ref="oracleLobHandler"/> <!-- 如果需要读写Lob字段,需要注入在SpringFramework配置文件中配置好的Handler,--> <!-- 这里是Oracle的数据库 --> </bean>
2、继承使用SqlMapClientDaoSupport类
声明Java类:
......
import org.springframework.orm.ibatis.support.SqlMapClientDaoSupport;
......
public class ReportDAOImpl extends SqlMapClientDaoSupport {
......
}
SpringFramework配置文件中装配Java类:
<bean id="reportDao" class="com.test.dao.ReportDAOImpl"> <property name="sqlMapClient" ref="sqlMapClient"/> <!-- 装配SqlMapClientFactoryBean --> </bean>
3、使用SqlMapClientTemplate查询
当执行没有参数的查询时:
List result = getSqlMapClientTemplate().queryForList("TestSpace.qryTest");
//"TestSpace"为iBatis SqlMap文件的命名空间;"qryTest"为iBatis SqlMap的查询方法id
当按照主键获取某条记录信息时:
Long id = new Long("2");
Object resultObj = getSqlMapClientTemplate().queryForObject("TestSpace.getTest", id);
当按照某些条件查询时:
ObjectA objA = new ObjectA();
objA.setParam1("test1");
objA.setParam2("test2");
......
List result = getSqlMapClientTemplate().queryForList("TestSpace.qryTestByParam", objA);
如果需要取4~40条数据:
List result = getSqlMapClientTemplate().queryForList("TestSpace.qryTestByParam", objA, 4, 40);
也可以返回Map
Map result = getSqlMapClientTemplate().queryForMap("TestSpace.qryTestByParam", objA, "MapKey");
4、使用SqlMapClientTemplate添加数据
ObjectA objA = new ObjectA();
objA.setParam1("test1");
objA.setParam2("test2");
......
getSqlMapClientTemplate().insert("TestSpace.insertTest", objA);
5、使用SqlMapClientTemplate更新数据
ObjectA objA = new ObjectA();
objA.setParam1("test1");
objA.setParam2("test2");
......
getSqlMapClientTemplate().update("TestSpace.updateTest", objA);
更新前20条记录:
getSqlMapClientTemplate().update("TestSpace.updateTest", objA, 20);
6、使用SqlMapClientTemplate删除数据
Long id = new Long("2");
getSqlMapClientTemplate().delete("TestSpace.deleteTest", id);
1.Pom文件
<?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>Ibatis</groupId> <artifactId>Ibatis</artifactId> <version>1.0-SNAPSHOT</version> <properties> <spring-version>3.0.6.RELEASE</spring-version> </properties> <dependencies> <!--Junti--> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.11</version> <scope>test</scope> </dependency> <!--Spring--> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context</artifactId> <version>${spring-version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-tx</artifactId> <version>${spring-version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-orm</artifactId> <version>${spring-version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-aop</artifactId> <version>${spring-version}</version> </dependency> <!--Ibatis--> <dependency> <groupId>org.apache.ibatis</groupId> <artifactId>ibatis-sqlmap</artifactId> <version>2.3.4.726</version> </dependency> <!--dbcp--> <dependency> <groupId>c3p0</groupId> <artifactId>c3p0</artifactId> <version>0.9.1.2</version> </dependency> <dependency> <groupId>commons-dbcp</groupId> <artifactId>commons-dbcp</artifactId> <version>1.4</version> </dependency> <!--mysql--> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>5.1.27</version> </dependency> <!--log4j--> <dependency> <groupId>log4j</groupId> <artifactId>log4j</artifactId> <version>1.2.17</version> </dependency> <dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-api</artifactId> <version>1.7.5</version> </dependency> <dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-log4j12</artifactId> <version>1.7.5</version> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-compiler-plugin</artifactId> <version>2.5.1</version> <configuration> <source>1.6</source> <target>1.6</target> <encoding>UTF-8</encoding> </configuration> </plugin> </plugins> </build> </project>
2.applicationContext.xml
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.0.xsd"> <import resource="spring-ibatis.xml"/> </beans>
3.spring-ibatis.xml
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd"> <!-- spring 读取配置文件 --> <bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"> <property name="locations" value="jdbc.properties" /> </bean> <!--设置BasicDataSource连接池,须导入commons-dbcp包--> <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"> <property name="driverClassName" value="${db.driver}" /> <property name="url" value="${db.url}" /> <property name="username" value="${db.username}" /> <property name="password" value="${db.password}" /> <property name="initialSize" value="${db.initialPoolSize}" /> <property name="maxActive" value="${db.maxPoolSize}" /> <property name="maxWait" value="${db.maxIdleTime}" /> </bean> <!--配置c3p0连接池,须导入c3p0包--> <bean id="dataSource_c3p0" class="com.mchange.v2.c3p0.ComboPooledDataSource" destroy-method="close"> <property name="driverClass" value="${db.driver}"/> <property name="jdbcUrl" value="${db.url}"/> <property name="user" value="${db.username}"/> <property name="password" value="${db.password}"/> <property name="initialPoolSize" value="${db.initialPoolSize}"/> <property name="minPoolSize" value="${db.minPoolSize}"/> <property name="maxPoolSize" value="${db.maxPoolSize}"/> <property name="maxIdleTime" value="${db.maxIdleTime}"/> </bean> <!-- 此处应注入ibatis配置文件,而非sqlMap文件,否则会出现“there is no statement.....异常” --> <!-- 在此处引入数据库连接池的关联 --> <bean id="sqlMapClient" class="org.springframework.orm.ibatis.SqlMapClientFactoryBean"> <property name="configLocation" value="sqlMapConfig.xml" /> <property name="dataSource" ref="dataSource" /> </bean> <bean id="studentDao" class="com.suishou.ibatis1.dao.StudentDaoImpl"> <property name="sqlMapClient" ref="sqlMapClient" /> </bean> </beans>
4.jdbc.properties
db.driver=com.mysql.jdbc.Driver
db.url=jdbc:mysql://localhost:3306/ibatis?useUnicode=true&characterEncoding=UTF-8
db.username=root
db.password=111111
db.initialPoolSize=10
db.minPoolSize=10
db.maxPoolSize=20
db.maxIdleTime=60
5.Student.xml
<?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE sqlMap PUBLIC "-//ibatis.apache.org//DTD SQL Map 2.0//EN" "http://ibatis.apache.org/dtd/sql-map-2.dtd" > <sqlMap > <typeAlias type="com.suishou.ibatis1.entity.Student" alias="student"/> <!--<resultMap id="ibatisTest" class="student" > <result column="id" property="id" jdbcType="VARCHAR" /> <result column="name" property="name" jdbcType="VARCHAR" /> </resultMap>--> <!-- 获得全查询列表 --> <select id="getAllStudents" resultClass="student"> select * from student </select> <!-- 根据用户名获得用户对象 --> <select id="getStudentByName" resultClass="student"> select * from student where name=#value# </select> <!-- 根据id获得用户对象 --> <select id="getStudentById" resultClass="student"> select * from student where id=#value# </select> <!-- 新增用户对象 --> <insert id="insertStudent" parameterClass="student"> insert into student (id,name) values (#id#,#name#) </insert> <!-- 删除用户对象 --> <delete id="deleteStudent"> delete from student where id=#value# </delete> <!-- 更新用户对象 --> <delete id="updateStudent" parameterClass="student"> update student set name=#name# where id=#id# </delete> </sqlMap>
6.log4j.properties
#定义根目录的输出级别和目的地
log4j.rootLogger=INFO, stdout1,stdout2
#设置输出目的地和输出样式
log4j.appender.stdout1=org.apache.log4j.ConsoleAppender
log4j.appender.stdout1.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout1.layout.ConversionPattern=%d %-5p %C.%M(%L) - %m%n
log4j.appender.stdout2=org.apache.log4j.FileAppender
log4j.appender.stdout2.File=d:/log00.html
log4j.appender.stdout2.layout=org.apache.log4j.HTMLLayout
#设置每个包的输出级别
#log4j.logger.com.ibatis=debug
#log4j.logger.com.ibatis.common.jdbc.SimpleDataSource=debug
#log4j.logger.com.ibatis.common.jdbc.ScriptRunner=debug
#log4j.logger.com.ibatis.sqlmap.engine.impl.SqlMapClientDelegate=debug
#log4j.logger.java.sql.Connection=debug
##log4j.logger.java.sql.Statement=debug
#log4j.logger.java.sql.PreparedStatement=debug
7.Student实体类
public class Student {
private int id;
private String name;
private int age;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
@Override
public String toString() {
return "Student{" +
"id=" + id +
", name='" + name + '\'' +
", age=" + age +
'}';
}
}
8.IStudentDao
public interface IStudentDao {
void insert(Student student); //增
void delete(int id); //删
void update(Student student); //改
Student select(int id); //查
List<Student> selectAll(); //查询全部
}
9.StudentDaoImpl
public class StudentDaoImpl extends SqlMapClientDaoSupport implements IStudentDao {
@Override
public void insert(Student student) {
getSqlMapClientTemplate().insert("insertStudent",student);
}
@Override
public void delete(int id) {
getSqlMapClientTemplate().delete("deleteStudent",id);
}
@Override
public void update(Student student) {
getSqlMapClientTemplate().update("updateStudent",student);
}
@Override
public Student select(int id) {
return (Student) getSqlMapClientTemplate().queryForObject("getStudentById",id);
}
@Override
public List<Student> selectAll() {
return getSqlMapClientTemplate().queryForList("getAllStudents");
}
}
10.StudentService
public class StudentService {
private static Logger logger = LoggerFactory.getLogger(StudentService.class);
public static void main(String[] args) {
ApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext.xml");
IStudentDao studentDao = (IStudentDao) ctx.getBean("studentDao");
Student student = studentDao.select(6);
logger.info("The Student is {}", student);
}
}