说起这三个的整合,其实还是ibatis+spring的整合,好了,开始了!
Spring iBATIS整合实例这里介绍两种Spring iBATIS整合的方式,这两种整合方式也是spring官方文档中提到的这两种整合方案。
Spring iBATIS整合模式一
可以基于原生的iBATIS API来编程,而无需对Spring产生任何依赖。直接使用注入的 SqlMapClient
。
实例:
- package net.chinaideal.samples.ibatis.dao;
- import java.sql.SQLException;
- import net.chinaideal.samples.ibatis.model.User;
- import com.ibatis.sqlmap.client.SqlMapClient;
- /**
- * SpringiBatis - UserDAO.java
- * 说明:
- * UserDAO 实现
- * 这个实现通过Spring维护iBatis的SqlMapClient,具体调用还是通过iBatis的API完成。
- * 这样实现的有点是在不使用Spring的时,由于使用的都是iBatis的API,所以可移植性较好。
- **/
- public class UserDAOImpl implements UserDAO {
- protected SqlMapClient sqlMapClient;
- public User getUserByUsername(String username) {
- try {
- return (User) this.sqlMapClient.queryForObject("getUserbyUsername", username);
- } catch (SQLException ex) {
- ex.printStackTrace();
- }
- return null;
- }
- public SqlMapClient getSqlMapClient() {
- return sqlMapClient;
- }
- public void setSqlMapClient(SqlMapClient sqlMapClient){
- this.sqlMapClient = sqlMapClient;
- }
- }
package net.chinaideal.samples.ibatis.dao;
import java.sql.SQLException;
import net.chinaideal.samples.ibatis.model.User;
import com.ibatis.sqlmap.client.SqlMapClient;
/**
* SpringiBatis - UserDAO.java
* 说明:
* UserDAO 实现
* 这个实现通过Spring维护iBatis的SqlMapClient,具体调用还是通过iBatis的API完成。
* 这样实现的有点是在不使用Spring的时,由于使用的都是iBatis的API,所以可移植性较好。
**/
public class UserDAOImpl implements UserDAO {
protected SqlMapClient sqlMapClient;
public User getUserByUsername(String username) {
try {
return (User) this.sqlMapClient.queryForObject("getUserbyUsername", username);
} catch (SQLException ex) {
ex.printStackTrace();
}
return null;
}
public SqlMapClient getSqlMapClient() {
return sqlMapClient;
}
public void setSqlMapClient(SqlMapClient sqlMapClient){
this.sqlMapClient = sqlMapClient;
}
}
Spring iBATIS整合模式二
- package net.chinaideal.samples.ibatis.dao;
- import net.chinaideal.samples.ibatis.model.User;
- import org.springframework.orm.ibatis.support.SqlMapClientDaoSupport;
- /**
- * SpringiBatis - UserDAOImpl2.java
- * 说明:
- * 模式2:UserDAOImpl2继承SqlMapClientDaoSupport类
- * SqlMapClientDaoSupport这个类为Spring的ibatis模版类
- * ibatis模版类提供很多模版方法,Spring提供了异常处理,使用比较方便。
- * 例如:
- * queryForObject(statename, args)等等。
- *
- * 但是这个方法用使用类Spring的SqlMapClientDaoSupport,所以需要Spring的支持简化了编码的过程,移植性不够。
- */
- public class UserDAOImpl2 extends SqlMapClientDaoSupport implements UserDAO {
- /*
- * 注意这里就不需要声明SqlMapClient 但在spring配置文件中写UserDAOImpl2这个bean时必须传入
- * sqlMapClient的bean依赖
- */
- public User getUserByUsername(String username) {
- return (User)getSqlMapClientTemplate().queryForObject("getUserbyUsername", username);
- }
- }
package net.chinaideal.samples.ibatis.dao;
import net.chinaideal.samples.ibatis.model.User;
import org.springframework.orm.ibatis.support.SqlMapClientDaoSupport;
/**
* SpringiBatis - UserDAOImpl2.java
* 说明:
* 模式2:UserDAOImpl2继承SqlMapClientDaoSupport类
* SqlMapClientDaoSupport这个类为Spring的ibatis模版类
* ibatis模版类提供很多模版方法,Spring提供了异常处理,使用比较方便。
* 例如:
* queryForObject(statename, args)等等。
*
* 但是这个方法用使用类Spring的SqlMapClientDaoSupport,所以需要Spring的支持简化了编码的过程,移植性不够。
*/
public class UserDAOImpl2 extends SqlMapClientDaoSupport implements UserDAO {
/*
* 注意这里就不需要声明SqlMapClient 但在spring配置文件中写UserDAOImpl2这个bean时必须传入
* sqlMapClient的bean依赖
*/
public User getUserByUsername(String username) {
return (User)getSqlMapClientTemplate().queryForObject("getUserbyUsername", username);
}
}
- Spring的配置文件中则需要如下配置:
- <bean id="sqlMapClient" class="org.springframework.orm.ibatis.SqlMapClientFactoryBean">
- <property name="configLocation" value="WEB-INF/sql-map-config.xml"/>
- <property name="dataSource" ref="dataSource"/>
- </bean>
- <bean id="userDao2" class="net.chinaideal.samples.ibatis.dao.UserDAOImpl2 ">
- <property name="sqlMapClient" ref="sqlMapClient"/>
- </bean>
Spring的配置文件中则需要如下配置:
<bean id="sqlMapClient" class="org.springframework.orm.ibatis.SqlMapClientFactoryBean">
<property name="configLocation" value="WEB-INF/sql-map-config.xml"/>
<property name="dataSource" ref="dataSource"/>
</bean>
<bean id="userDao2" class="net.chinaideal.samples.ibatis.dao.UserDAOImpl2 ">
<property name="sqlMapClient" ref="sqlMapClient"/>
</bean>
------------------------------------
作为开源的Orm对象映射框架,ibatis是一个线程安全,学习容易,但是开发相对于hibernate来说的话,就要繁锁些,没有很好的工具支持ibatis所有的配置几乎是通过手写,这样增加了开发者的难度、、好啦,言归正转。下面编写实现。
一、引入spring,ibatis jar包.
二、编写log4j.properties日志文件
log4j.rootLogger=DEBUG,stdout
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%c{1}% - %m%n
log4j.logger.java.sql.PreparedStatement=DEBUG
三、建立Student.java类映象属性
- package org.terry.ibatis.pojo;
- public class Student {
- private Long id;
- private String name;
- private String subject;
- private Long score;
- public Long getId() { return id; }
- public void setId(Long id) { this.id = id; }
- public String getName() { return name; }
- public void setName(String name) { this.name = name; }
- public Long getScore() { return score; }
- public void setScore(Long score) { this.score = score; }
- public String getSubject() { return subject; }
- public void setSubject(String subject) { this.subject = subject; }
- }
package org.terry.ibatis.pojo;
public class Student {
private Long id;
private String name;
private String subject;
private Long score;
public Long getId() { return id; }
public void setId(Long id) { this.id = id; }
public String getName() { return name; }
public void setName(String name) { this.name = name; }
public Long getScore() { return score; }
public void setScore(Long score) { this.score = score; }
public String getSubject() { return subject; }
public void setSubject(String subject) { this.subject = subject; }
}
四、编写 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 namespace="student">
- <typeAlias alias="student" type="org.terry.ibatis.pojo.Student"/>
- <resultMap class="student" id="studentResult">
- <result property="id" column="id" jdbcType="number" javaType="java.lang.Long"/>
- <result property="name" column="name"/>
- <result property="subject" column="subject"/>
- <result property="score" column="score"/>
- </resultMap>
- <select id="selectAll" resultMap="studentResult">
- select * from student
- </select>
- <select id="findbyId" parameterClass="java.lang.Long" resultClass="student">
- select * from student where id=#id#
- </select>
- <insert id="insert" parameterClass="student">
- insert into student(id,name,subject,score) values(#id#,#name#,#subject#,#score#)
- </insert>
- <update id="update" parameterClass="student">
- update student set name=#name#,subject=#subject#,score=#score# where id=#id#
- </update>
- <delete id="delete" parameterClass="java.lang.Long">
- delete from student where id=#id#
- </delete>
- </sqlMap>
<?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 namespace="student"> <typeAlias alias="student" type="org.terry.ibatis.pojo.Student"/> <resultMap class="student" id="studentResult"> <result property="id" column="id" jdbcType="number" javaType="java.lang.Long"/> <result property="name" column="name"/> <result property="subject" column="subject"/> <result property="score" column="score"/> </resultMap> <select id="selectAll" resultMap="studentResult"> select * from student </select> <select id="findbyId" parameterClass="java.lang.Long" resultClass="student"> select * from student where id=#id# </select> <insert id="insert" parameterClass="student"> insert into student(id,name,subject,score) values(#id#,#name#,#subject#,#score#) </insert> <update id="update" parameterClass="student"> update student set name=#name#,subject=#subject#,score=#score# where id=#id# </update> <delete id="delete" parameterClass="java.lang.Long"> delete from student where id=#id# </delete> </sqlMap>
五、编写 SqlMapConfig.xml文件【ibatis的配置文件中只剩下sqlMap了,其它都不要了】
- <?xml version="1.0" encoding="utf-8" ?>
- <!DOCTYPE sqlMapConfig
- PUBLIC "-//ibatis.apache.org//DTD SQL Map Config 2.0//EN" "http://ibatis.apache.org/dtd/sql-map-config-2.dtd">
- <sqlMapConfig>
- <sqlMap resource="org/terry/ibatis/pojo/student.xml"/>
- </sqlMapConfig>
<?xml version="1.0" encoding="utf-8" ?> <!DOCTYPE sqlMapConfig PUBLIC "-//ibatis.apache.org//DTD SQL Map Config 2.0//EN" "http://ibatis.apache.org/dtd/sql-map-config-2.dtd"> <sqlMapConfig> <sqlMap resource="org/terry/ibatis/pojo/student.xml"/> </sqlMapConfig>
六、编写 StudentDao.java(实现类)
- package org.terry.ibatis.dao;
- import java.io.IOException;
- import java.sql.SQLException;
- import java.util.List;
- import org.springframework.beans.factory.xml.XmlBeanFactory;
- import org.springframework.core.io.ClassPathResource;
- import org.springframework.core.io.Resource;
- import org.springframework.orm.ibatis.SqlMapClientCallback;
- import org.springframework.orm.ibatis.support.SqlMapClientDaoSupport;
- import org.terry.ibatis.pojo.Student;
- import com.ibatis.sqlmap.client.SqlMapExecutor;
- public class StudentDao extends SqlMapClientDaoSupport implements Idao{
- public void delete(Long id) {
- this.getSqlMapClientTemplate().delete("delete", id);
- }
- public Object findbyId(Long id) {
- return this.getSqlMapClientTemplate().queryForObject("findbyId", id);
- }
- public List getAll() {
- return (List)this.getSqlMapClientTemplate().execute(new SqlMapClientCallback(){
- public Object doInSqlMapClient(SqlMapExecutor sqlMapper) throws SQLException {
- return sqlMapper.queryForList("selectAll");
- }
- });
- }
- public void save(Object o) {
- this.getSqlMapClientTemplate().insert("insert", o);
- }
- public void update(Object o) {
- this.getSqlMapClientTemplate().update("update", o);
- }
- public static void main(String[] args) throws IOException {
- Resource re=new ClassPathResource("Ibatis-Context.xml");
- XmlBeanFactory xml=new XmlBeanFactory(re);
- StudentDao student=(StudentDao)xml.getBean("studentDao");
- Student stu=new Student();
- stu.setId(Long.valueOf(16));
- stu.setName("terry");
- stu.setScore(Long.valueOf(99));
- stu.setSubject("数学");
- student.delete(Long.valueOf(16));
- }
- }
package org.terry.ibatis.dao;
import java.io.IOException;
import java.sql.SQLException;
import java.util.List;
import org.springframework.beans.factory.xml.XmlBeanFactory;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.orm.ibatis.SqlMapClientCallback;
import org.springframework.orm.ibatis.support.SqlMapClientDaoSupport;
import org.terry.ibatis.pojo.Student;
import com.ibatis.sqlmap.client.SqlMapExecutor;
public class StudentDao extends SqlMapClientDaoSupport implements Idao{
public void delete(Long id) {
this.getSqlMapClientTemplate().delete("delete", id);
}
public Object findbyId(Long id) {
return this.getSqlMapClientTemplate().queryForObject("findbyId", id);
}
public List getAll() {
return (List)this.getSqlMapClientTemplate().execute(new SqlMapClientCallback(){
public Object doInSqlMapClient(SqlMapExecutor sqlMapper) throws SQLException {
return sqlMapper.queryForList("selectAll");
}
});
}
public void save(Object o) {
this.getSqlMapClientTemplate().insert("insert", o);
}
public void update(Object o) {
this.getSqlMapClientTemplate().update("update", o);
}
public static void main(String[] args) throws IOException {
Resource re=new ClassPathResource("Ibatis-Context.xml");
XmlBeanFactory xml=new XmlBeanFactory(re);
StudentDao student=(StudentDao)xml.getBean("studentDao");
Student stu=new Student();
stu.setId(Long.valueOf(16));
stu.setName("terry");
stu.setScore(Long.valueOf(99));
stu.setSubject("数学");
student.delete(Long.valueOf(16));
}
}
七、配置 ApplicationContext.xml文件
- <?xml version="1.0" encoding="UTF-8"?>
- <!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN" "http://www.springframework.org/dtd/spring-beans.dtd">
- <beans>
- <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource">
- <property name="driverClassName">
- <value>oracle.jdbc.driver.OracleDriver</value>
- </property>
- <property name="url">
- <value>jdbc:oracle:thin:@localhost:1521:orcl</value>
- </property>
- <property name="username">
- <value>terry</value>
- </property>
- <property name="password">
- <value>terry</value>
- </property>
- </bean>
- <bean id="sqlMapClient" class="org.springframework.orm.ibatis.SqlMapClientFactoryBean">
- <property name="configLocation" value="SqlMapConfig.xml"/>
- <property name="dataSource" ref="dataSource"></property>
- </bean>
- <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
- <property name="dataSource" ref="dataSource"></property>
- </bean>
- <!-- 配置事务拦截器 -->
- <bean id="transactionIterceptor" class="org.springframework.transaction.interceptor.TransactionInterceptor">
- <!-- 事务拦截器需要注入一个事务管理器 -->
- <property name="transactionManager" ref="transactionManager"></property>
- <property name="transactionAttributes">
- <props>
- <prop key="insert*">PROPAGATION_REQUIRED</prop>
- <prop key="find*,get*">PROPAGATION_REQUIRED,readOnly</prop>
- <prop key="*">PROPAGATION_REQUIRED</prop>
- </props>
- </property>
- </bean>
- <bean class="org.springframework.aop.framework.autoproxy.BeanNameAutoProxyCreator">
- <property name="beanNames">
- <list>
- <value>*Dao</value>
- </list>
- </property>
- <property name="interceptorNames">
- <list>
- <value>transactionIterceptor</value>
- </list>
- </property>