Mybatis技术(二) MyBatis-Spring Mybatis技术(二) MyBatis-Spring

Mybaits为什么要整合Spring?

说白了其实就想使用Spring提供的服务,比如Spring的事务管理、Spring的IOC对Bean进行管理等。 

 

Mybatis怎么整合Spring?

 由于目前Spring官方还没有出整合Mybatis的特性,所以这里在Spring框架和MyBatis框架上再添加用于整合的框架“mybatis-spring-1.0.2.jar” (该框架时MyBatis官方自己出的)。

 

(1)新建一个Web工程,名称为MybatisSpring。

 

(2)将Spring3.0.3、Mybatis3.0.6、Mybatis-Spring1.0.2、log4j、Oracle驱动和DBCP连接池的JAR包放到Web工程的lib下面,具体的JAR包如下:

Java代码    收藏代码
  1. classes12.jar  
  2. log4j-1.2.16.jar  
  3. mybatis-3.0.6.jar  
  4. mybatis-spring-1.0.2.jar  
  5. org.springframework.aop-3.0.3.RELEASE.jar  
  6. org.springframework.asm-3.0.3.RELEASE.jar  
  7. org.springframework.aspects-3.0.3.RELEASE.jar  
  8. org.springframework.beans-3.0.3.RELEASE.jar  
  9. org.springframework.context-3.0.3.RELEASE.jar  
  10. org.springframework.context.support-3.0.3.RELEASE.jar  
  11. org.springframework.core-3.0.3.RELEASE.jar  
  12. org.springframework.expression-3.0.3.RELEASE.jar  
  13. org.springframework.jdbc-3.0.3.RELEASE.jar  
  14. org.springframework.transaction-3.0.3.RELEASE.jar  
  15. org.springframework.web-3.0.3.RELEASE.jar  
  16. commons-logging-1.1.1.jar  
  17. commons-dbcp-1.2.jar  
  18. commons-pool-1.4.jar  

 

(3)在src下面新建log4j.properties文件,该文件的内容如下:

Java代码    收藏代码
  1. log4j.appender.stdout=org.apache.log4j.ConsoleAppender  
  2. log4j.appender.stdout.layout=org.apache.log4j.PatternLayout  
  3. log4j.appender.stdout.layout.ConversionPattern=%d %p [%c] -%m%n  
  4. log4j.logger.com.ibatis=debug  
  5. log4j.logger.com.ibatis.common.jdbc.SimpleDataSource=debug  
  6. log4j.logger.com.ibatis.common.jdbc.ScriptRunner=debug  
  7. log4j.logger.com.ibatis.sqlmap.engine.impl.SqlMapClientDelegate=debug  
  8. log4j.logger.java.sql.Connection=debug  
  9. log4j.logger.java.sql.Statement=debug  
  10. log4j.logger.java.sql.PreparedStatement=debug,stdout  

 

 

(4)在Oracle数据库执行以下SQL,创建一个USER_INFO的表:

 

Java代码    收藏代码
  1. -- Create table  
  2. create table USER_INFO  
  3. (  
  4.   ID          NUMBER(12) not null,  
  5.   NAME        VARCHAR2(50)  
  6. );  
  7.   
  8. --Insert data  
  9. insert into USER_INFO(ID,NAME) values(1,'张三');  

 

(5)新建一个Java类UserInfo.java,该类的内容如下:

 

Java代码    收藏代码
  1. package com.user;  
  2.   
  3. public class UserInfo {  
  4.     private int id;  
  5.     private String name;  
  6.   
  7.     public UserInfo() {  
  8.     }  
  9.   
  10.     public UserInfo(String name) {  
  11.         this(0, name);  
  12.     }  
  13.   
  14.     public UserInfo(int id, String name) {  
  15.         this.id = id;  
  16.         this.name = name;  
  17.     }  
  18.   
  19.     public int getId() {  
  20.         return id;  
  21.     }  
  22.   
  23.     public void setId(int id) {  
  24.         this.id = id;  
  25.     }  
  26.   
  27.     public String getName() {  
  28.         return name;  
  29.     }  
  30.   
  31.     public void setName(String name) {  
  32.         this.name = name;  
  33.     }  
  34.   
  35.     @Override  
  36.     public String toString() {  
  37.         return "ID: " + id + ", Name: " + name;  
  38.     }  
  39. }  

 

(6)在com.user.sqlmap下面新建UserInfo.xml文件,该文件的内容如下:

 

Java代码    收藏代码
  1. <?xml version="1.0" encoding="UTF-8" ?>  
  2.   
  3. <!DOCTYPE mapper PUBLIC   
  4.     "-//mybatis.org//DTD Mapper 3.0//EN"  
  5.     "http://mybatis.org/dtd/mybatis-3-mapper.dtd">  
  6.   
  7. <mapper namespace="User">  
  8.     <select id="selectUser" parameterType="int" resultType="UserInfo">  
  9.     <![CDATA[  
  10.         select * from user_info where id = #{id}  
  11.     ]]>  
  12.     </select>  
  13. </mapper>  

 

(7)在src下面新建mybatis.cfg.xml文件,该文件的内容如下:

Java代码    收藏代码
  1. <?xml version="1.0" encoding="UTF-8" ?>  
  2.   
  3. <!DOCTYPE configuration PUBLIC   
  4.     "-//mybatis.org//DTD Config 3.0//EN"  
  5.     "http://mybatis.org/dtd/mybatis-3-config.dtd">  
  6.   
  7. <configuration>  
  8.     <typeAliases>  
  9.         <typeAlias alias="UserInfo" type="com.user.UserInfo" />  
  10.     </typeAliases>  
  11.       
  12.     <mappers>  
  13.         <mapper resource="com/user/sqlmap/UserInfo.xml" />  
  14.     </mappers>  
  15. </configuration>  

 

 

(8)新建一个Java类UserService.java,该类的内容如下:

 

Java代码    收藏代码
  1. package com.user;  
  2.   
  3. import org.mybatis.spring.SqlSessionTemplate;  
  4.   
  5. public class UserService {  
  6.     private SqlSessionTemplate  sqlSession;  
  7.       
  8.     public SqlSessionTemplate getSqlSession() {  
  9.         return sqlSession;  
  10.     }  
  11.   
  12.     public void setSqlSession(SqlSessionTemplate sqlSession) {  
  13.         this.sqlSession = sqlSession;  
  14.     }  
  15.       
  16.     public UserInfo selectUser(){  
  17.           UserInfo user = null;  
  18.           try {  
  19.                           user = (UserInfo) sqlSession.selectOne("User.selectUser""1");  
  20.                     } catch (Exception e) {  
  21.                           e.printStackTrace();  
  22.                     }  
  23.           
  24.                    return user;  
  25.              }  
  26. }  

 

(9)在src下面新建applicationContext.xml文件,该文件的内容如下:

Java代码    收藏代码
  1. <?xml version="1.0" encoding="UTF-8"?>  
  2. <beans xmlns="http://www.springframework.org/schema/beans"  
  3.     default-autowire="byName"  
  4.     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  
  5.     xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">  
  6.   
  7.     <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource">  
  8.         <property name="driverClassName" value="oracle.jdbc.OracleDriver" />  
  9.         <property name="url" value="jdbc:oracle:thin:@localhost:1521:SID" />  
  10.         <property name="username" value="xxxx" />  
  11.         <property name="password" value="xxxx" />  
  12.         <property name="maxActive" value="100"></property>  
  13.         <property name="maxIdle" value="30"></property>  
  14.         <property name="maxWait" value="500"></property>  
  15.         <property name="defaultAutoCommit" value="true"></property>  
  16.     </bean>  
  17.       
  18.     <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">  
  19.         <property name="configLocation" value="classpath:mybatis.cfg.xml"></property>  
  20.         <property name="dataSource" ref="dataSource" />  
  21.     </bean>  
  22.       
  23.     <bean id="sqlSessionTemplate" class="org.mybatis.spring.SqlSessionTemplate">  
  24.         <constructor-arg index="0" ref="sqlSessionFactory" />  
  25.     </bean>  
  26.       
  27.     <bean id="userService" class="com.user.UserService">  
  28.        <property name="sqlSession" ref="sqlSessionTemplate" />  
  29.     </bean>  
  30.   
  31. </beans>  

 

 

(10)新建一个测试Java类UserInfoTest.java,该类的具体内容如下:

Java代码    收藏代码
  1. package com.user;  
  2.   
  3. import java.io.IOException;  
  4.   
  5. import org.springframework.context.ApplicationContext;  
  6. import org.springframework.context.support.ClassPathXmlApplicationContext;  
  7.   
  8.   
  9.   
  10. public class UserInfoTest {  
  11.   
  12.     /** 
  13.      * @param args 
  14.      * @throws IOException  
  15.      */  
  16.     public static void main(String[] args) throws IOException {  
  17.         ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");  
  18.                             UserService userService = (UserService)context.getBean("userService");  
  19.                             UserInfo userInfo = userService.selectUser();  
  20.                             System.out.println(userInfo);  
  21.   
  22.     }  
  23.   
  24. }  

 

 

(11)右键UserInfoTest 类,选择Run As Application,运行MyBaits操作数据库。

 

Java代码    收藏代码
  1. log4j:WARN No appenders could be found for logger (org.springframework.context.support.ClassPathXmlApplicationContext).  
  2. log4j:WARN Please initialize the log4j system properly.  
  3. log4j:WARN See http://logging.apache.org/log4j/1.2/faq.html#noconfig for more info.  
  4. 2012-02-11 21:13:42,156 DEBUG [java.sql.PreparedStatement] -==>  Executing: select * from user_info where id = ?   
  5. 2012-02-11 21:13:42,156 DEBUG [java.sql.PreparedStatement] -==> Parameters: 1(String)  
  6. ID: 1, Name: 张三  

 

Mybaits为什么要整合Spring?

说白了其实就想使用Spring提供的服务,比如Spring的事务管理、Spring的IOC对Bean进行管理等。 

 

Mybatis怎么整合Spring?

 由于目前Spring官方还没有出整合Mybatis的特性,所以这里在Spring框架和MyBatis框架上再添加用于整合的框架“mybatis-spring-1.0.2.jar” (该框架时MyBatis官方自己出的)。

 

(1)新建一个Web工程,名称为MybatisSpring。

 

(2)将Spring3.0.3、Mybatis3.0.6、Mybatis-Spring1.0.2、log4j、Oracle驱动和DBCP连接池的JAR包放到Web工程的lib下面,具体的JAR包如下:

Java代码    收藏代码
  1. classes12.jar  
  2. log4j-1.2.16.jar  
  3. mybatis-3.0.6.jar  
  4. mybatis-spring-1.0.2.jar  
  5. org.springframework.aop-3.0.3.RELEASE.jar  
  6. org.springframework.asm-3.0.3.RELEASE.jar  
  7. org.springframework.aspects-3.0.3.RELEASE.jar  
  8. org.springframework.beans-3.0.3.RELEASE.jar  
  9. org.springframework.context-3.0.3.RELEASE.jar  
  10. org.springframework.context.support-3.0.3.RELEASE.jar  
  11. org.springframework.core-3.0.3.RELEASE.jar  
  12. org.springframework.expression-3.0.3.RELEASE.jar  
  13. org.springframework.jdbc-3.0.3.RELEASE.jar  
  14. org.springframework.transaction-3.0.3.RELEASE.jar  
  15. org.springframework.web-3.0.3.RELEASE.jar  
  16. commons-logging-1.1.1.jar  
  17. commons-dbcp-1.2.jar  
  18. commons-pool-1.4.jar  

 

(3)在src下面新建log4j.properties文件,该文件的内容如下:

Java代码    收藏代码
  1. log4j.appender.stdout=org.apache.log4j.ConsoleAppender  
  2. log4j.appender.stdout.layout=org.apache.log4j.PatternLayout  
  3. log4j.appender.stdout.layout.ConversionPattern=%d %p [%c] -%m%n  
  4. log4j.logger.com.ibatis=debug  
  5. log4j.logger.com.ibatis.common.jdbc.SimpleDataSource=debug  
  6. log4j.logger.com.ibatis.common.jdbc.ScriptRunner=debug  
  7. log4j.logger.com.ibatis.sqlmap.engine.impl.SqlMapClientDelegate=debug  
  8. log4j.logger.java.sql.Connection=debug  
  9. log4j.logger.java.sql.Statement=debug  
  10. log4j.logger.java.sql.PreparedStatement=debug,stdout  

 

 

(4)在Oracle数据库执行以下SQL,创建一个USER_INFO的表:

 

Java代码    收藏代码
  1. -- Create table  
  2. create table USER_INFO  
  3. (  
  4.   ID          NUMBER(12) not null,  
  5.   NAME        VARCHAR2(50)  
  6. );  
  7.   
  8. --Insert data  
  9. insert into USER_INFO(ID,NAME) values(1,'张三');  

 

(5)新建一个Java类UserInfo.java,该类的内容如下:

 

Java代码    收藏代码
  1. package com.user;  
  2.   
  3. public class UserInfo {  
  4.     private int id;  
  5.     private String name;  
  6.   
  7.     public UserInfo() {  
  8.     }  
  9.   
  10.     public UserInfo(String name) {  
  11.         this(0, name);  
  12.     }  
  13.   
  14.     public UserInfo(int id, String name) {  
  15.         this.id = id;  
  16.         this.name = name;  
  17.     }  
  18.   
  19.     public int getId() {  
  20.         return id;  
  21.     }  
  22.   
  23.     public void setId(int id) {  
  24.         this.id = id;  
  25.     }  
  26.   
  27.     public String getName() {  
  28.         return name;  
  29.     }  
  30.   
  31.     public void setName(String name) {  
  32.         this.name = name;  
  33.     }  
  34.   
  35.     @Override  
  36.     public String toString() {  
  37.         return "ID: " + id + ", Name: " + name;  
  38.     }  
  39. }  

 

(6)在com.user.sqlmap下面新建UserInfo.xml文件,该文件的内容如下:

 

Java代码    收藏代码
  1. <?xml version="1.0" encoding="UTF-8" ?>  
  2.   
  3. <!DOCTYPE mapper PUBLIC   
  4.     "-//mybatis.org//DTD Mapper 3.0//EN"  
  5.     "http://mybatis.org/dtd/mybatis-3-mapper.dtd">  
  6.   
  7. <mapper namespace="User">  
  8.     <select id="selectUser" parameterType="int" resultType="UserInfo">  
  9.     <![CDATA[  
  10.         select * from user_info where id = #{id}  
  11.     ]]>  
  12.     </select>  
  13. </mapper>  

 

(7)在src下面新建mybatis.cfg.xml文件,该文件的内容如下:

Java代码    收藏代码
  1. <?xml version="1.0" encoding="UTF-8" ?>  
  2.   
  3. <!DOCTYPE configuration PUBLIC   
  4.     "-//mybatis.org//DTD Config 3.0//EN"  
  5.     "http://mybatis.org/dtd/mybatis-3-config.dtd">  
  6.   
  7. <configuration>  
  8.     <typeAliases>  
  9.         <typeAlias alias="UserInfo" type="com.user.UserInfo" />  
  10.     </typeAliases>  
  11.       
  12.     <mappers>  
  13.         <mapper resource="com/user/sqlmap/UserInfo.xml" />  
  14.     </mappers>  
  15. </configuration>  

 

 

(8)新建一个Java类UserService.java,该类的内容如下:

 

Java代码    收藏代码
  1. package com.user;  
  2.   
  3. import org.mybatis.spring.SqlSessionTemplate;  
  4.   
  5. public class UserService {  
  6.     private SqlSessionTemplate  sqlSession;  
  7.       
  8.     public SqlSessionTemplate getSqlSession() {  
  9.         return sqlSession;  
  10.     }  
  11.   
  12.     public void setSqlSession(SqlSessionTemplate sqlSession) {  
  13.         this.sqlSession = sqlSession;  
  14.     }  
  15.       
  16.     public UserInfo selectUser(){  
  17.           UserInfo user = null;  
  18.           try {  
  19.                           user = (UserInfo) sqlSession.selectOne("User.selectUser""1");  
  20.                     } catch (Exception e) {  
  21.                           e.printStackTrace();  
  22.                     }  
  23.           
  24.                    return user;  
  25.              }  
  26. }  

 

(9)在src下面新建applicationContext.xml文件,该文件的内容如下:

Java代码    收藏代码
  1. <?xml version="1.0" encoding="UTF-8"?>  
  2. <beans xmlns="http://www.springframework.org/schema/beans"  
  3.     default-autowire="byName"  
  4.     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  
  5.     xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">  
  6.   
  7.     <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource">  
  8.         <property name="driverClassName" value="oracle.jdbc.OracleDriver" />  
  9.         <property name="url" value="jdbc:oracle:thin:@localhost:1521:SID" />  
  10.         <property name="username" value="xxxx" />  
  11.         <property name="password" value="xxxx" />  
  12.         <property name="maxActive" value="100"></property>  
  13.         <property name="maxIdle" value="30"></property>  
  14.         <property name="maxWait" value="500"></property>  
  15.         <property name="defaultAutoCommit" value="true"></property>  
  16.     </bean>  
  17.       
  18.     <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">  
  19.         <property name="configLocation" value="classpath:mybatis.cfg.xml"></property>  
  20.         <property name="dataSource" ref="dataSource" />  
  21.     </bean>  
  22.       
  23.     <bean id="sqlSessionTemplate" class="org.mybatis.spring.SqlSessionTemplate">  
  24.         <constructor-arg index="0" ref="sqlSessionFactory" />  
  25.     </bean>  
  26.       
  27.     <bean id="userService" class="com.user.UserService">  
  28.        <property name="sqlSession" ref="sqlSessionTemplate" />  
  29.     </bean>  
  30.   
  31. </beans>  

 

 

(10)新建一个测试Java类UserInfoTest.java,该类的具体内容如下:

Java代码    收藏代码
  1. package com.user;  
  2.   
  3. import java.io.IOException;  
  4.   
  5. import org.springframework.context.ApplicationContext;  
  6. import org.springframework.context.support.ClassPathXmlApplicationContext;  
  7.   
  8.   
  9.   
  10. public class UserInfoTest {  
  11.   
  12.     /** 
  13.      * @param args 
  14.      * @throws IOException  
  15.      */  
  16.     public static void main(String[] args) throws IOException {  
  17.         ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");  
  18.                             UserService userService = (UserService)context.getBean("userService");  
  19.                             UserInfo userInfo = userService.selectUser();  
  20.                             System.out.println(userInfo);  
  21.   
  22.     }  
  23.   
  24. }  

 

 

(11)右键UserInfoTest 类,选择Run As Application,运行MyBaits操作数据库。

 

Java代码    收藏代码
  1. log4j:WARN No appenders could be found for logger (org.springframework.context.support.ClassPathXmlApplicationContext).  
  2. log4j:WARN Please initialize the log4j system properly.  
  3. log4j:WARN See http://logging.apache.org/log4j/1.2/faq.html#noconfig for more info.  
  4. 2012-02-11 21:13:42,156 DEBUG [java.sql.PreparedStatement] -==>  Executing: select * from user_info where id = ?   
  5. 2012-02-11 21:13:42,156 DEBUG [java.sql.PreparedStatement] -==> Parameters: 1(String)  
  6. ID: 1, Name: 张三  

 

猜你喜欢

转载自rongdmmap-126-com.iteye.com/blog/1410099