最近一直在看spring和ibatis的东西,由于目前SSH的流行,大多讲Spring和Hibernate的整合开发,作者一直对Hibernate不是很感冒,也许是因为日常开发程序对性能要求比较高,和Hibernate比较起来Ibatis更合适。虽然网络上有很多讲Spring和Ibatis整合的文章,但查看了许多,发现能顺利开发下去的文章太少,于是我就为大家准备了这篇Spring+Ibatis的入门级整合文章。
环境介绍
先来介绍一下本入门级整合文章所用到的环境:Spring2.5.5、Ibatis2.3.0、JDK1.6、Oracle数据库,如果没有用过Oracle的读者读到这里请不要慌张,因为本实例还会讲解Mysql和SqlServer的。
程序介绍
实例中要求完成Spring与Ibatis的整合,并往数据库的UserInfo表中插入用户信息。
开发部分
好了,下面我们开始边开发边讲解吧,Let‘s go!
1、首先我们一起先来看看本实例的整个目录结构
从图中,我们可以看出,这个spring_ibatis工程下有2个代码包:study.spring.dao、study.spring.manager
2个文件夹:properties、sqlmap
除jdk外的jar包:ibatis下的jar包:ibatis-2.3.0.677.jar
oracle下的jar包:classes12.jar
spring下的jar包:spring.jar、commons-logging.jar、log4j.jar
其中:properties文件夹下放置这spring的配置文件applicationContext.xml和Ibatis的配置文件SqlMapConfig.xml
sqlmap文件夹下放置的是Ibatis的SqlMap配置文件(最终转化成可执行的SQL语句)
包study.spring.dao下有3个java文件:
1)UserInfo:用户类
2)UserDao:数据库操作接口
3)User4OracleImpl:数据库操作实现类,继承与UserDao接口
包study.spring.manager下有2个java文件:
1)UserManager:数据库操作管理类
2)Client:测试主类
2、在数据库中新建一张UserInfo表
- CREATE TABLE userinfo
- (
- userid varchar2 (10), --用户ID
- username varchar2 (20), --用户名
- password varchar2 (16), --密码
- age int --年龄
- );
3、在study.spring.dao下建立一个与数据库Userinfo表对应的Java类
- package study.spring.dao;
- public class UserInfo {
-
- private String userid;
-
- private String username;
-
- private String password;
-
- private int age;
- public int getAge() {
- return age;
- }
- public void setAge(int age) {
- this.age = age;
- }
- public String getPassword() {
- return password;
- }
- public void setPassword(String password) {
- this.password = password;
- }
- public String getUserid() {
- return userid;
- }
- public void setUserid(String userid) {
- this.userid = userid;
- }
- public String getUsername() {
- return username;
- }
- public void setUsername(String username) {
- this.username = username;
- }
- }
4、配置Ibatis的数据库连接信息
在properties下的SqlMapClient.xml中添加如下语句
- <?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>
- <!-- MySQL 连接的配置信息-->
- <!--
- <transactionManager type="JDBC" commitRequired="false">
- <dataSource type="SIMPLE">
- <property name="JDBC.Driver" value="com.mysql.jdbc.Driver"/>
- <property name="JDBC.ConnectionURL" value="jdbc:mysql://localhost:3306/test"/>
- <property name="JDBC.Username" value="root"/>
- <property name="JDBC.Password" value="root"/>
- </dataSource>
- </transactionManager>
- -->
- <!-- Oracle 连接的配置信息 -->
- <transactionManager type="JDBC">
- <dataSource type="SIMPLE">
- <property name="JDBC.Driver" value="oracle.jdbc.driver.OracleDriver"/>
- <property name="JDBC.ConnectionURL" value="jdbc:oracle:thin:@10.60.108.11:1550:cdbeff"/>
- <property name="JDBC.Username" value="cdbeff"/>
- <property name="JDBC.Password" value="password"/>
- <property name="Pool.MaximumActiveConnections" value="10"/>
- <property name="Pool.MaximumIdleConnections" value="5"/>
- <property name="Pool.MaximumCheckoutTime" value="120000"/>
- <property name="Pool.TimeToWait" value="500"/>
- <property name="Pool.PingQuery" value="select 1 from dual"/>
- <property name="Pool.PingEnabled" value="false"/>
- <property name="Pool.PingConnectionsOlderThan" value="1"/>
- <property name="Pool.PingConnectionsNotUsedFor" value="1"/>
- </dataSource>
- </transactionManager>
- <!-- SQL Server 连接的配置信息
- <transactionManager type="JDBC" commitRequired="false">
- <dataSource type="SIMPLE">
- <property name="JDBC.Driver"
- value="com.microsoft.jdbc.sqlserver.SQLServerDriver" />
- <property name="JDBC.ConnectionURL"
- value="jdbc:microsoft:sqlserver://localhost:1433;databaseName=pubs;SelectMethod=Cursor" />
- <property name="JDBC.Username" value="sa" />
- <property name="JDBC.Password" value="" />
- </dataSource>
- </transactionManager>
- -->
- <!-- SqlMap的配置文件 -->
- <sqlMap resource="sqlmap/SqlMap_UserInfo.xml" />
- </sqlMapConfig>
5、整合spring和ibatis
在properties的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"
- xmlns:aop="http://www.springframework.org/schema/aop"
- xmlns:tx="http://www.springframework.org/schema/tx"
- xsi:schemaLocation="
- http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
- http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.5.xsd
- http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd">
-
-
- <bean id="SqlMapClientFactoryBean" class="org.springframework.orm.ibatis.SqlMapClientFactoryBean">
- <property name="configLocations">
- <value>properties/SqlMapConfig.xml</value>
- </property>
- </bean>
- <bean id="userInfo" class="study.spring.dao.UserInfo">
- <property name="userid" value="51048"></property>
- <property name="username" value="zhanhj"></property>
- <property name="password" value="dcfszhj09"></property>
- <property name="age" value="24"></property>
- </bean>
- <bean id="userDao4OracleImpl" class="study.spring.dao.User4OracleImpl">
-
- <property name="sqlMapClient" ref="SqlMapClientFactoryBean"></property>
- </bean>
- <bean id="userManager" class="study.spring.manager.UserManager">
- <property name="userDao" ref="userDao4OracleImpl"></property>
- </bean>
- </beans>
在此文件中,其中整合ibatis的为如下语句,其余的配置信息为本程序的其他实现类的bean
-
- <bean id="SqlMapClientFactoryBean" class="org.springframework.orm.ibatis.SqlMapClientFactoryBean">
- <property name="configLocations">
- <value>properties/SqlMapConfig.xml</value>
- </property>
- </bean>
6、UserDao的实现
- package study.spring.dao;
- import com.ibatis.sqlmap.client.SqlMapClient;
- public interface UserDao {
-
- public void save(SqlMapClient client, UserInfo user);
- public void delete(SqlMapClient client, UserInfo user);
- }
7、User4OracleImpl的实现
- package study.spring.dao;
- import java.sql.SQLException;
- import org.springframework.orm.ibatis.support.SqlMapClientDaoSupport;
- import org.apache.commons.logging.Log;
- import org.apache.commons.logging.LogFactory;
- import com.ibatis.sqlmap.client.SqlMapClient;
- public class User4OracleImpl extends SqlMapClientDaoSupport implements UserDao {
- private Log log = LogFactory.getLog(User4OracleImpl.class);
-
- public void delete(SqlMapClient client, UserInfo user) {
- try {
- client.delete(user.getUserid());
- } catch (SQLException e) {
- e.printStackTrace();
- }
- }
-
- public void save(SqlMapClient client, UserInfo user) {
- try {
- client.startTransaction();
- client.insert("insertUserInfo", user);
- log.info(user.getUserid() + "的信息插入成功!");
- client.commitTransaction();
- } catch (SQLException e) {
- e.printStackTrace();
- }
- }
- }
8、UserManager的实现
- package study.spring.manager;
- import com.ibatis.sqlmap.client.SqlMapClient;
- import study.spring.dao.UserDao;
- import study.spring.dao.UserInfo;
- public class UserManager {
- public UserDao userDao;
- public void setUserDao(UserDao userDao) {
- this.userDao = userDao;
- }
- public void save(SqlMapClient client, UserInfo user) {
- userDao.save(client, user);
- }
- public void delete(SqlMapClient client, UserInfo user) {
- userDao.delete(client, user);
- }
- }
9、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>
- <typeAlias alias="Userinfo" type="study.spring.dao.UserInfo"/>
- <resultMap id="queryResult" class="Userinfo">
- <result property="userid" column="userid"/>
- <result property="username" column="username"/>
- <result property="password" column="password"/>
- <result property="age" column="age"/>
- </resultMap>
- <select id="selectAllusers" resultMap="queryResult">
- select * from userinfo
- </select>
-
-
- <insert id="insertUserInfo" parameterClass="Userinfo">
- insert into userinfo (
- userid,
- username,
- password,
- age)
- values (
- #userid#, #username#, #password#, #age#
- )
- </insert>
-
- <delete id="deleteUserById" parameterClass="java.lang.String">
- delete from userinfo where userid = #userid#
- </delete>
-
- </sqlMap>
10、Client测试主类的实现
- package study.spring.manager;
- import org.springframework.beans.factory.BeanFactory;
- import org.springframework.context.support.ClassPathXmlApplicationContext;
- import com.ibatis.sqlmap.client.SqlMapClient;
- import study.spring.dao.UserInfo;
- import junit.framework.TestCase;
- public class Client extends TestCase{
-
- public static void main(String[] args) {
- BeanFactory factory = new ClassPathXmlApplicationContext("properties/applicationContext.xml");
- UserManager userManager = (UserManager) factory.getBean("userManager");
- UserInfo user = (UserInfo)factory.getBean("userInfo");
- SqlMapClient client = (SqlMapClient)factory.getBean("SqlMapClientFactoryBean");
- userManager.save(client,user);
-
- }
- }
11、测试结果
- 2010-11-22 20:05:47,187 INFO [org.springframework.context.support.ClassPathXmlApplicationContext] - Refreshing org.springframework.context.support.ClassPathXmlApplicationContext@197d257: display name [org.springframework.context.support.ClassPathXmlApplicationContext@197d257]; startup date [Mon Nov 22 20:05:47 CST 2010]; root of context hierarchy
- 2010-11-22 20:05:47,492 INFO [org.springframework.beans.factory.xml.XmlBeanDefinitionReader] - Loading XML bean definitions from class path resource [properties/applicationContext.xml]
- 2010-11-22 20:05:48,188 INFO [org.springframework.context.support.ClassPathXmlApplicationContext] - Bean factory for application context [org.springframework.context.support.ClassPathXmlApplicationContext@197d257]: org.springframework.beans.factory.support.DefaultListableBeanFactory@1319c
- 2010-11-22 20:05:48,255 INFO [org.springframework.beans.factory.support.DefaultListableBeanFactory] - Pre-instantiating singletons in org.springframework.beans.factory.support.DefaultListableBeanFactory@1319c: defining beans [SqlMapClientFactoryBean,userInfo,userDao4OracleImpl,userManager]; root of factory hierarchy
- 2010-11-22 20:05:51,194 INFO [study.spring.dao.User4OracleImpl] - 51048的信息插入成功!
到这里,需要讲解的内容就结束了,下面我们一起来总结一下:
1、spring整合ibatis:在applicationContext.xml中将ibatis的sqlMapClient注入(参考第5点)
2、ibatis配置数据库连接信息(包括Oracle、MySql、Sql
Server,参考第4点)
其他的各位一一理解吧,今天先到这里,再见!