mybatis學習筆記(八):mybatis 與 spring 的整合


項目結構:

1、導入相關 jar 包:

*  mysql的jar:
*      mysql-connector-java-5.1.25-bin.jar
*  oracle的jar:
*      jdbc5.jar
*  c3p0的jar:
*      c3p0-0.9.1.2.jar
*  mybatis的jar:
*      asm-3.3.1.jar
*      cglib-2.2.2.jar
*      commons-logging.jar
*      mybatis-3.1.1.jar
*  mybatis與spring整合的jar
*      【mybatis-spring-1.1.1.jar】
*  spring的ioc模塊的jar:
*      org.springframework.asm-3.0.5.RELEASE.jar
*      org.springframework.beans-3.0.5.RELEASE.jar
*      org.springframework.context-3.0.5.RELEASE.jar
*      org.springframework.core-3.0.5.RELEASE.jar
*      org.springframework.expression-3.0.5.RELEASE.jar
*      commons-logging.jar【mybatis也依賴此包】
*  spring的aop模塊的jar:
*      aopalliance.jar
*      aspectjweaver.jar
*      cglib-2.2.2.jar【mybatis也依賴此包】
*      org.springframework.aop-3.0.5.RELEASE.jar
*  spring的transaction模塊的jar:
*      org.springframework.jdbc-3.0.5.RELEASE.jar
*      org.springframework.orm-3.0.5.RELEASE.jar
*      org.springframework.transaction-3.0.5.RELEASE.jar

2、創建 emps 表:

create table emps(
    eid number(5) primary key,
    ename varchar2(20),
    esal number(8,2),
    esex varchar2(5)
);

3、創建 Emp.java 類:

package com.mybatis.entity;

/**
 * 實體類
 */
public class Emp {
    private Integer id;
    private String name;
    private Double sal;
    private String sex;

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

    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 getSex() {
        return sex;
    }

    public void setSex(String sex) {
        this.sex = sex;
    }

}

4、創建 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 標籤:映射實體與表的關係 -->
    <resultMap id="empMap" type="com.mybatis.entity.Emp">
        <id property="id" column="eid"/>
        <result property="name" column="ename"/>
        <result property="sal" column="esal"/>
        <result property="sex" column="esex"/>
    </resultMap>

    <!-- 增加員工 -->
    <insert id="add" parameterType="com.mybatis.entity.Emp">
        insert into emps(eid, ename, esal, esex) values(#{id}, #{name}, #{sal}, #{sex})
    </insert>
</mapper>

5、創建 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>
    <!-- 加載映射文件 -->
    <mappers>
        <mapper resource="com/mybatis/entity/EmpMapper.xml"/>
    </mappers>
</configuration>

6、創建 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: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-3.0.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context-3.0.xsd
        http://www.springframework.org/schema/aop
        http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
        http://www.springframework.org/schema/tx
        http://www.springframework.org/schema/tx/spring-tx-3.0.xsd">

    <!-- 配置 C3P0 連接池:目的是管理數據庫連接 -->
    <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
        <!-- mysql -->
        <!--<property name="driverClass" value="com.mysql.jdbc.Driver"/>-->
        <!--<property name="jdbcUrl" value="jdbc:mysql://localhost:3306/mybatis"/>-->
        <!--<property name="user" value="root"/>-->
        <!--<property name="password" value="root"/>-->

        <!-- oracle -->
        <property name="driverClass" value="oracle.jdbc.driver.OracleDriver"/>
        <property name="jdbcUrl" value="jdbc:oracle:thin:@localhost:1521:orcl"/>
        <property name="user" value="scott"/>
        <property name="password" value="tiger"/>
    </bean>

    <!-- 配置 SqlSessionFactoryBean,目的是加載 mybatis 配置文件和映射文件,相當於原 MybatisUtils 工具類的作用 -->
    <bean id="sqlSessionFactoryBean" class="org.mybatis.spring.SqlSessionFactoryBean">
        <!-- 加載 mybatis 主配置文件 -->
        <property name="configLocation" value="classpath:mybatis.xml"/>
        <!-- 引用上面配置的連接池 -->
        <property name="dataSource" ref="dataSource"/>
    </bean>

    <!-- 配置 mybatis 的事務管理器,因爲 mybatis 底層使用的是 JDBC 事務管理器,所以在這裏配置的是 JDBC 事務管理器 -->
    <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <!-- 引用上面配置的連接池 -->
        <property name="dataSource" ref="dataSource"/>
    </bean>

    <!-- 配置事務通知:即設置哪些方法需要事務支持 -->
    <tx:advice id="transaction" transaction-manager="transactionManager">
        <tx:attributes>
            <!-- *:表示所有的方法都使用事務;REQUIRED:表示必須要有事務; -->
            <tx:method name="*" propagation="REQUIRED"/>
            <!--<tx:method name="add*" propagation="REQUIRED"/>-->
            <!--<tx:method name="delete*" propagation="REQUIRED"/>-->
            <!--<tx:method name="update*" propagation="REQUIRED"/>-->
        </tx:attributes>
    </tx:advice>

    <!-- 配置事務切面:即設置哪些包下的類或者方法需要事務 -->
    <aop:config>
        <!-- 表示 com.mybatis.dao 包下的所有類中的所有方法都需要事務
            第一個 * 表示返回值不限;(..)表示參數不限; -->
        <aop:pointcut id="pointCut" expression="execution(* com.mybatis.dao.*.*(..))"/>
        <!-- 表示將上面配置的 事務通知 切入到需要 切面中 -->
        <aop:advisor advice-ref="transaction" pointcut-ref="pointCut"/>
    </aop:config>

    <!-- 註冊 EmpDao,表示將 EmpDao 對象的創建交給 IOC 容器去完成 -->
    <bean id="empDao" class="com.mybatis.dao.EmpDao">
        <!-- 注入上面配置的 sqlSessionFactory 對象 -->
        <property name="sqlSessionFactory" ref="sqlSessionFactoryBean"/>
    </bean>
</beans>

7、創建 EmpDao.java 類:

package com.mybatis.dao;

import com.mybatis.entity.Emp;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;

/**
 * 持久層
 */
public class EmpDao {

    // IOC 容器自動注入 sqlSessionFactory 對象
    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();
    }
}

8、創建 EmpDaoTest.java 類:

package com.mybatis.dao;

import com.mybatis.dao.EmpDao;
import com.mybatis.entity.Emp;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class EmpDaoTest {
    public static void main(String[] args) throws Exception{
        // 加載 spring.xml 配置文件
        ApplicationContext applicationContext = new ClassPathXmlApplicationContext("spring.xml");
        // 從 IOC 容器中獲取 empDao 對象
        EmpDao empDao = (EmpDao) applicationContext.getBean("empDao");
        empDao.add(new Emp(2, "嘻嘻", 8000D, "女"));
    }
}

 

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