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包如下:

classes12.jar     
log4j-1.2.16.jar     
mybatis-3.0.6.jar     
mybatis-spring-1.0.2.jar     
org.springframework.aop-3.0.3.RELEASE.jar     
org.springframework.asm-3.0.3.RELEASE.jar     
org.springframework.aspects-3.0.3.RELEASE.jar     
org.springframework.beans-3.0.3.RELEASE.jar     
org.springframework.context-3.0.3.RELEASE.jar     
org.springframework.context.support-3.0.3.RELEASE.jar     
org.springframework.core-3.0.3.RELEASE.jar     
org.springframework.expression-3.0.3.RELEASE.jar     
org.springframework.jdbc-3.0.3.RELEASE.jar     
org.springframework.transaction-3.0.3.RELEASE.jar     
org.springframework.web-3.0.3.RELEASE.jar     
commons-logging-1.1.1.jar     
commons-dbcp-1.2.jar     
commons-pool-1.4.jar 

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

log4j.appender.stdout=org.apache.log4j.ConsoleAppender     
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout     
log4j.appender.stdout.layout.ConversionPattern=%d %p [%c] -%m%n     
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,stdout    

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

-- Create table     
create table USER_INFO     
(     
  ID          NUMBER(12) not null,     
  NAME        VARCHAR2(50)     
);     
     
--Insert data     
insert into USER_INFO(ID,NAME) values(1,'张三');   

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

package com.user;     
     
public class UserInfo {     
    private int id;     
    private String name;     
     
    public UserInfo() {     
    }     
     
    public UserInfo(String name) {     
        this(0, name);     
    }     
     
    public UserInfo(int id, String name) {     
        this.id = id;     
        this.name = name;     
    }     
     
    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;     
    }     
     
    @Override     
    public String toString() {     
        return "ID: " + id + ", Name: " + name;     
    }     
}   

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

<?xml version="1.0" encoding="UTF-8" ?>     
     
<!DOCTYPE mapper PUBLIC      
    "-//mybatis.org//DTD Mapper 3.0//EN"     
    "http://mybatis.org/dtd/mybatis-3-mapper.dtd">     
     
<mapper namespace="User">     
    <select id="selectUser" parameterType="int" resultType="UserInfo">     
    <![CDATA[     
        select * from user_info where id = #{id}     
    ]]>     
    </select>     
</mapper>  

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

<?xml version="1.0" encoding="UTF-8" ?>     
     
<!DOCTYPE configuration PUBLIC      
    "-//mybatis.org//DTD Config 3.0//EN"     
    "http://mybatis.org/dtd/mybatis-3-config.dtd">     
     
<configuration>     
    <typeAliases>     
        <typeAlias alias="UserInfo" type="com.user.UserInfo" />     
    </typeAliases>     
         
    <mappers>     
        <mapper resource="com/user/sqlmap/UserInfo.xml" />     
    </mappers>     
</configuration>    

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

package com.user;     
     
import org.mybatis.spring.SqlSessionTemplate;     
     
public class UserService {     
    private SqlSessionTemplate  sqlSession;     
         
    public SqlSessionTemplate getSqlSession() {     
        return sqlSession;     
    }     
     
    public void setSqlSession(SqlSessionTemplate sqlSession) {     
        this.sqlSession = sqlSession;     
    }     
         
    public UserInfo selectUser(){     
          UserInfo user = null;     
          try {     
                          user = (UserInfo) sqlSession.selectOne("User.selectUser", "1");     
                    } catch (Exception e) {     
                          e.printStackTrace();     
                    }     
             
                   return user;     
             }     
}    

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

<?xml version="1.0" encoding="UTF-8"?>     
<beans xmlns="http://www.springframework.org/schema/beans"     
    default-autowire="byName"     
    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-3.0.xsd">     
     
    <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource">     
        <property name="driverClassName" value="oracle.jdbc.OracleDriver" />     
        <property name="url" value="jdbc:oracle:thin:@localhost:1521:SID" />     
        <property name="username" value="xxxx" />     
        <property name="password" value="xxxx" />     
        <property name="maxActive" value="100"></property>     
        <property name="maxIdle" value="30"></property>     
        <property name="maxWait" value="500"></property>     
        <property name="defaultAutoCommit" value="true"></property>     
    </bean>     
         
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">     
        <property name="configLocation" value="classpath:mybatis.cfg.xml"></property>     
        <property name="dataSource" ref="dataSource" />     
    </bean>     
         
    <bean id="sqlSessionTemplate" class="org.mybatis.spring.SqlSessionTemplate">     
        <constructor-arg index="0" ref="sqlSessionFactory" />     
    </bean>     
         
    <bean id="userService" class="com.user.UserService">     
       <property name="sqlSession" ref="sqlSessionTemplate" />     
    </bean>     
     
</beans> 

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

package com.user;     
     
import java.io.IOException;     
     
import org.springframework.context.ApplicationContext;     
import org.springframework.context.support.ClassPathXmlApplicationContext;     
     
     
     
public class UserInfoTest {     
     
    /**   
     * @param args   
     * @throws IOException    
     */     
    public static void main(String[] args) throws IOException {     
        ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");     
        UserService userService = (UserService)context.getBean("userService");     
        UserInfo userInfo = userService.selectUser();     
        System.out.println(userInfo);     
     
    }     
     
}     
(11)右键UserInfoTest 类,选择Run As Application,运行MyBaits操作数据库。

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


你可能感兴趣的:(mybatis)