MyBatis系列:(9)mybatis-spring-springmvc-oracle/mysql整合


大體思路:首先是配置好mybatis的環境,其次就是mybatis與spring的整合,其整合的目標是①mybatis的SqlSessionFactory交由Spring來創建②mybatis的事務交由Spring來處理;最後就是springmvc的融入,使得mybatis(dao層)、spring(中間層)、springmvc(web層)融爲一體。


1、MyBatis環境配置

步驟:jar包->SQL語句->entity->dao

1.1、引入jar包

mybatismybatis-3.2.7.jar
mybatis的支持包

asm-3.3.1.jar

commons-logging-1.1.1.jar

log4j-1.2.17.jar

oracleojdbc5.jar


1.2、SQL語句

OracleSQL

create table emps(
	eid number(1) primary key,
	ename varchar2(20),
	esal number(6,2),
	egender varchar2(3)
);


1.3、entity

Emp.java

package com.rk.entity;

public class Emp {
    private Integer id;
    private String name;
    private Double sal;
    private String gender;
    public Emp(){}
    
    public Emp(Integer id, String name, Double sal, String gender) {
        this.id = id;
        this.name = name;
        this.sal = sal;
        this.gender = gender;
    }

    public Integer getId() {
        return id;
    }
    public void setId(Integer id) {
        this.id = id;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public Double getSal() {
        return sal;
    }
    public void setSal(Double sal) {
        this.sal = sal;
    }
    public String getGender() {
        return gender;
    }
    public void setGender(String gender) {
        this.gender = gender;
    }
    
}


1.4、dao

EmpDao.java

package com.rk.dao;

import java.io.IOException;
import java.io.Reader;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import com.rk.entity.Emp;

public class EmpDao {
    private static SqlSessionFactory sqlSessionFactory;
    static {
        try {
            Reader reader = Resources.getResourceAsReader("mybatis.xml");
            sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader);
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        }
    }
    public void add(Emp emp)throws Exception{
        SqlSession sqlSession = sqlSessionFactory.openSession();
        sqlSession.insert("empNamespace.add", emp);
        sqlSession.commit();
        sqlSession.close();
    }
}


1.5、mybatis的映射文件(EmpMapper.xml)和主配置文件(mybatis.xml)

EmpMapper.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="empNamespace">
    <resultMap type="com.rk.entity.Emp" id="empResultMap">
        <id property="id" column="eid"/>
        <result property="name" column="ename"/>
        <result property="sal" column="esal"/>
        <result property="gender" column="egender"/>
    </resultMap>
    <insert id="add" parameterType="com.rk.entity.Emp">
        insert into emps(eid,ename,esal,egender) values(#{id},#{name},#{sal},#{gender})
    </insert>
</mapper>

mybatis.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>
    <properties resource="db.properties"/>
    <environments default="oracle_development">
        <environment id="oracle_development">
            <transactionManager type="JDBC"></transactionManager>
            <dataSource type="POOLED">
                <property name="driver" value="${oracle.driver}"/>
                <property name="url" value="${oracle.url}"/>
                <property name="username" value="${oracle.username}"/>
                <property name="password" value="${oracle.password}"/>
            </dataSource>
        </environment>
        <environment id="mysql_developer">
            <transactionManager type="jdbc"/>   
            <dataSource type="pooled">
                <property name="driver" value="${mysql.driver}"/>
                <property name="url" value="${mysql.url}"/>
                <property name="username" value="${mysql.username}"/>
                <property name="password" value="${mysql.password}"/>
            </dataSource>
        </environment>
    </environments>
    <mappers>
        <mapper resource="com/rk/entity/EmpMapper.xml"/>
    </mappers>
</configuration>

db.properties

#key=value
oracle.driver=oracle.jdbc.driver.OracleDriver
oracle.url=jdbc:oracle:thin:@127.0.0.1:1521:orcl
oracle.username=scott
oracle.password=tiger

mysql.driver=com.mysql.jdbc.Driver
mysql.url=jdbc:mysql://127.0.0.1:3306/testdb
mysql.username=root
mysql.password=root


1.6、測試

package com.rk.test;

import org.junit.Test;

import com.rk.dao.EmpDao;
import com.rk.entity.Emp;

public class MybatisTest {

    @Test
    public void testAdd() throws Exception {
        EmpDao dao = new EmpDao();
        Emp emp = new Emp(1, "小明", 800D, "男");
        dao.add(emp);
    }

}


2、Mybatis與Spring整合

(1)MyBatis的SqlSessionFactory交由Spring來創建

(2)Mybatis的事務交由Spring來管理

(3)DAO、Service對象的生成和依賴注入由Spring來完成


2.1、引入需要的jar包

c3p0c3p0-0.9.1.2.jar
spring-core

commons-logging-1.2.jar (mybaits中引入了1.1.1版本,可以刪除1.1.1版本)

spring-beans-3.2.5.RELEASE.jar

spring-context-3.2.5.RELEASE.jar

spring-core-3.2.5.RELEASE.jar

spring-expression-3.2.5.RELEASE.jar

spring-aop

aopalliance-.jar

aspectjrt.jar

aspectjweaver.jar

spring-aop-3.2.5.RELEASE.jar

spring-jdbc

spring-jdbc-3.2.5.RELEASE.jar

spring-tx-3.2.5.RELEASE.jar

spring-ormspring-orm-3.2.5.RELEASE.jar
mybatis與spring整合的jar

mybatis-spring-1.2.4.jar

下載地址:https://github.com/mybatis/spring/releases 

版本不同帶來的問題:之前引入的是mybatis-spring-1.0.0.jar,後來測試的時候發現錯誤,錯誤信息:java.lang.AbstractMethodError: org.mybatis.spring.transaction.SpringManagedTransactionFactory.newTransaction(Ljavax/sql/DataSource;Lorg/apache/ibatis/session/TransactionIsolationLevel;Z)Lorg/apache/ibatis/transaction/Transaction。換成1.2.4版本後,錯誤消失。


2.2、修改mybatis.xml

註釋或者刪除mybatis.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>
    <!--
    <properties resource="db.properties"/>
    <environments default="oracle_development">
        <environment id="oracle_development">
            <transactionManager type="JDBC"></transactionManager>
            <dataSource type="POOLED">
                <property name="driver" value="${oracle.driver}"/>
                <property name="url" value="${oracle.url}"/>
                <property name="username" value="${oracle.username}"/>
                <property name="password" value="${oracle.password}"/>
            </dataSource>
        </environment>
        <environment id="mysql_developer">
            <transactionManager type="jdbc"/>   
            <dataSource type="pooled">
                <property name="driver" value="${mysql.driver}"/>
                <property name="url" value="${mysql.url}"/>
                <property name="username" value="${mysql.username}"/>
                <property name="password" value="${mysql.password}"/>
            </dataSource>
        </environment>
    </environments> 
    -->
    <mappers>
        <mapper resource="com/rk/entity/EmpMapper.xml"/>
    </mappers>
</configuration>


2.3、添加Spring的主配置文件spring.xml


(1)MyBatis的SqlSessionFactory交由Spring來創建

(2)Mybatis的事務交由Spring來管理

(3)DAO、Service對象的生成和依賴注入由Spring來完成



<?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:context="http://www.springframework.org/schema/context"
    xmlns:tx="http://www.springframework.org/schema/tx"
    xmlns:aop="http://www.springframework.org/schema/aop"
    xmlns:mvc="http://www.springframework.org/schema/mvc"
    xsi:schemaLocation="
        http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context.xsd
        http://www.springframework.org/schema/tx
        http://www.springframework.org/schema/tx/spring-tx.xsd
        http://www.springframework.org/schema/aop
        http://www.springframework.org/schema/aop/spring-aop.xsd
        http://www.springframework.org/schema/mvc
        http://www.springframework.org/schema/mvc/spring-mvc.xsd">
    <!-- 配置C3P0連接池,目的:管理數據庫連接 -->
<!-- 
    <bean id="comboPooledDataSourceID" class="com.mchange.v2.c3p0.ComboPooledDataSource">
        <property name="driverClass" value="oracle.jdbc.driver.OracleDriver"></property>
        <property name="jdbcUrl" value="jdbc:oracle:thin:@127.0.0.1:1521:orcl"></property>
        <property name="user" value="scott"></property>
        <property name="password" value="tiger"></property>
    </bean> 
 -->    
    <context:property-placeholder location="classpath:db.properties"/>
    <bean id="comboPooledDataSourceID" class="com.mchange.v2.c3p0.ComboPooledDataSource">
        <property name="driverClass" value="${oracle.driver}"></property>
        <property name="jdbcUrl" value="${oracle.url}"></property>
        <property name="user" value="${oracle.username}"></property>
        <property name="password" value="${oracle.password}"></property>
    </bean> 
    
    <!-- 配置SqlSessionFactoryBean,目的:加載mybaits配置文件和映射文件,即替代原Mybatis工具類的作用 -->
    <bean id="sqlSessionFactoryBeanID" class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="dataSource" ref="comboPooledDataSourceID"></property>
        <property name="configLocation" value="classpath:mybatis.xml"></property>
    </bean>
    
    <!-- 配置Mybatis的事務管理器,即DataSourceTransactionManager。
            因爲Mybatis底層用的是JDBC事務管事器,所以在這裏依然配置JDBC事務管理器 
    -->
    <bean id="dataSourceTransactionManagerID" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="comboPooledDataSourceID"></property>
    </bean>
    
    <!-- 配置事務通知,即讓哪些方法需要事務支持 -->
    <tx:advice id="tx" transaction-manager="dataSourceTransactionManagerID">
        <tx:attributes>
            <tx:method name="*" propagation="REQUIRED"/>
        </tx:attributes>
    </tx:advice>
    
    <!-- 配置事務切面,即讓哪些包下的類需要事務 -->
    <aop:config>
        <aop:pointcut  id="pointcut" expression="execution(* com.rk.service.*.*(..))"/>
        <aop:advisor advice-ref="tx" pointcut-ref="pointcut"/>
    </aop:config>
    
    <!-- 註冊EmpDao -->
    <bean id="empDaoID" class="com.rk.dao.EmpDao">
        <property name="sqlSessionFactory" ref="sqlSessionFactoryBeanID"></property>
    </bean>
    
    <!-- 註冊EmpService -->
    <bean id="empService" class="com.rk.service.EmpService">
        <property name="empDao" ref="empDaoID"></property>
    </bean>
</beans>


2.4、Dao

EmpDao.java

package com.rk.dao;

import java.io.IOException;
import java.io.Reader;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import com.rk.entity.Emp;

public class EmpDao {
    private SqlSessionFactory sqlSessionFactory;
    public void setSqlSessionFactory(SqlSessionFactory sqlSessionFactory) {
        this.sqlSessionFactory = sqlSessionFactory;
    }
    
    public void add(Emp emp) throws Exception{
        SqlSession sqlSession = sqlSessionFactory.openSession();
        sqlSession.insert("empNamespace.add", emp);
        sqlSession.close();
    }
}


2.5、Serivce

EmpService.java

package com.rk.service;

import com.rk.dao.EmpDao;
import com.rk.entity.Emp;

public class EmpService {
    private EmpDao empDao;
    public void setEmpDao(EmpDao empDao) {
        this.empDao = empDao;
    }
    
    public void register(Emp emp) throws Exception{
//        int i = 1/0;
//        System.out.println(i);
        empDao.add(emp);
    }
}


2.6、測試

package com.rk.test;

import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import com.rk.entity.Emp;
import com.rk.service.EmpService;

public class TestMybatis_Spring {

    @Test
    public void testRegister() throws Exception {
        ApplicationContext ac = new ClassPathXmlApplicationContext("spring.xml");
        EmpService empService = (EmpService) ac.getBean("empService");
        
        Emp emp = new Emp(3, "小剛", 400D, "男");
        empService.register(emp);
        
    }

}




3、SpringMVC的融入


3.1、引入JAR包

spring-webspring-web-3.2.5.RELEASE.jar
spring-webmvcspring-webmvc-3.2.5.RELEASE.jar


3.2、配置web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">
    <display-name>springmvc-mybatis-oracle</display-name>
    <welcome-file-list>
        <welcome-file>index.jsp</welcome-file>
    </welcome-file-list>
    <!-- 核心springmvc核心控制器 -->
    <servlet>
        <servlet-name>DispatcherServlet</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>classpath:spring.xml</param-value>
        </init-param>
    </servlet> 
    <servlet-mapping>
        <servlet-name>DispatcherServlet</servlet-name>
        <url-pattern>*.action</url-pattern>
    </servlet-mapping>
    
    <!-- POST編碼過濾器 -->
    <filter>
        <filter-name>CharacterEncodingFilter</filter-name>
        <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
        <init-param>
            <param-name>encoding</param-name>
            <param-value>UTF-8</param-value>
        </init-param>
    </filter>
    <filter-mapping>
        <filter-name>CharacterEncodingFilter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>
     
</web-app>



3.3、修改spring.xml

添加以下內容

    <!-- 註冊EmpAction -->
    <context:component-scan base-package="com.rk.action"/>  
     
    <!-- 通知springioc容器這些註解的作用 -->     
    <context:annotation-config/>
    
    <!-- 視圖解析器 -->
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/jsp/"/>
        <property name="suffix" value=".jsp"/>
    </bean>

完整的spring.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:context="http://www.springframework.org/schema/context"
    xmlns:tx="http://www.springframework.org/schema/tx"
    xmlns:aop="http://www.springframework.org/schema/aop"
    xmlns:mvc="http://www.springframework.org/schema/mvc"
    xsi:schemaLocation="
        http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context.xsd
        http://www.springframework.org/schema/tx
        http://www.springframework.org/schema/tx/spring-tx.xsd
        http://www.springframework.org/schema/aop
        http://www.springframework.org/schema/aop/spring-aop.xsd
        http://www.springframework.org/schema/mvc
        http://www.springframework.org/schema/mvc/spring-mvc.xsd">
    <!-- 配置C3P0連接池,目的:管理數據庫連接 -->
<!-- 
    <bean id="comboPooledDataSourceID" class="com.mchange.v2.c3p0.ComboPooledDataSource">
        <property name="driverClass" value="oracle.jdbc.driver.OracleDriver"></property>
        <property name="jdbcUrl" value="jdbc:oracle:thin:@127.0.0.1:1521:orcl"></property>
        <property name="user" value="scott"></property>
        <property name="password" value="tiger"></property>
    </bean> 
 -->    
    <context:property-placeholder location="classpath:db.properties"/>
    <bean id="comboPooledDataSourceID" class="com.mchange.v2.c3p0.ComboPooledDataSource">
        <property name="driverClass" value="${oracle.driver}"></property>
        <property name="jdbcUrl" value="${oracle.url}"></property>
        <property name="user" value="${oracle.username}"></property>
        <property name="password" value="${oracle.password}"></property>
    </bean> 
    
    <!-- 配置SqlSessionFactoryBean,目的:加載mybaits配置文件和映射文件,即替代原Mybatis工具類的作用 -->
    <bean id="sqlSessionFactoryBeanID" class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="dataSource" ref="comboPooledDataSourceID"></property>
        <property name="configLocation" value="classpath:mybatis.xml"></property>
    </bean>
    
    <!-- 配置Mybatis的事務管理器,即DataSourceTransactionManager。
            因爲Mybatis底層用的是JDBC事務管事器,所以在這裏依然配置JDBC事務管理器 
    -->
    <bean id="dataSourceTransactionManagerID" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="comboPooledDataSourceID"></property>
    </bean>
    
    <!-- 配置事務通知,即讓哪些方法需要事務支持 -->
    <tx:advice id="tx" transaction-manager="dataSourceTransactionManagerID">
        <tx:attributes>
            <tx:method name="*" propagation="REQUIRED"/>
        </tx:attributes>
    </tx:advice>
    
    <!-- 配置事務切面,即讓哪些包下的類需要事務 -->
    <aop:config>
        <aop:pointcut  id="pointcut" expression="execution(* com.rk.service.*.*(..))"/>
        <aop:advisor advice-ref="tx" pointcut-ref="pointcut"/>
    </aop:config>
    
    <!-- 註冊EmpDao -->
    <bean id="empDaoID" class="com.rk.dao.EmpDao">
        <property name="sqlSessionFactory" ref="sqlSessionFactoryBeanID"></property>
    </bean>
    
    <!-- 註冊EmpService -->
    <bean id="empServiceID" class="com.rk.service.EmpService">
        <property name="empDao" ref="empDaoID"></property>
    </bean>
    
    <!-- 註冊EmpAction -->
    <context:component-scan base-package="com.rk.action"/>  
     
    <!-- 通知springioc容器這些註解的作用 -->     
    <context:annotation-config/>
    
    <!-- 視圖解析器 -->
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/jsp/"/>
        <property name="suffix" value=".jsp"/>
    </bean>
</beans>


3.4、添加action

package com.rk.action;

import javax.annotation.Resource;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import com.rk.entity.Emp;
import com.rk.service.EmpService;

@Controller
@RequestMapping(value="/emp")
public class EmpAction {
    private EmpService empService;
    @Resource(name="empServiceID")
    public void setEmpService(EmpService empService) {
        this.empService = empService;
    }
    @RequestMapping(value="/registerEmp")
    public String registerEmp(Emp emp) throws Exception{
        empService.register(emp);
        return "success";
    }
}


3.5、添加index.jsp和success.jsp

index.jsp

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <meta name="content-type" content="text/html; charset=UTF-8"/>
    <title>My JSP 'index.jsp' starting page</title>
  </head>
  <body>
    <form action="${pageContext.request.contextPath}/emp/registerEmp.action" method="POST">
        <table>
            <tr>
                <td>編號:</td>
                <td>
                    <input type="text" name="id"/>
                </td>
            </tr>
            <tr>
                <td>姓名:</td>
                <td>
                    <input type="text" name="name"/>
                </td>
            </tr>
            <tr>
                <td>薪水:</td>
                <td>
                    <input type="text" name="sal"/>
                </td>
            </tr>
            <tr>
                <td>性別:</td>
                <td>
                    <input type="radio" name="gender" value="男"/>男
                    <input type="radio" name="gender" value="女" checked="checked"/>女
                </td>
            </tr>
            <tr>
                <td colspan="2">
                    <input type="submit" value="註冊"/>
                </td>
            </tr>
        </table>
    </form>
  </body>
</html>

/jsp/success.jsp

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <meta name="content-type" content="text/html; charset=UTF-8"/>
    <title>success page</title>
  </head>
  
  <body>
    success <br>
  </body>
</html>








發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章