java之mybatis整合spring


這篇講解spring+mybatis的整合。

目錄結構:

一. 整合spring的第一種方法

1. 新建 java 項目 : spring_mybatis

2.導入jar 包-----spring和mybatis的整合包,然后build

aopalliance.jar
aspectjweaver.jar
commons-logging.jar
mybatis-3.2.7.jar
mybatis-spring-1.2.3.jar
mysql-connector-java-5.1.20-bin.jar
spring-aop-4.1.6.RELEASE.jar
spring-aspects-4.1.6.RELEASE.jar
spring-beans-4.1.6.RELEASE.jar
spring-context-4.1.6.RELEASE.jar
spring-core-4.1.6.RELEASE.jar
spring-expression-4.1.6.RELEASE.jar
spring-jdbc-4.1.6.RELEASE.jar
spring-orm-4.1.6.RELEASE.jar
spring-tx-4.1.6.RELEASE.jar
spring-web-4.1.6.RELEASE.jar
spring-webmvc-4.1.6.RELEASE.jar

3.編寫 vo 類

在cn.vincent.vo下 User.java

 1 package cn.vincent.vo;
 2 
 3 import java.io.Serializable;
 4 
 5 public class User implements Serializable {
 6 
 7     private int id;
 8     private String name;
 9     private int age;
10     private int rileId;
11     public int getId() {
12         return id;
13     }
14     public void setId(int id) {
15         this.id = id;
16     }
17     public String getName() {
18         return name;
19     }
20     public void setName(String name) {
21         this.name = name;
22     }
23     public int getAge() {
24         return age;
25     }
26     public void setAge(int age) {
27         this.age = age;
28     }
29     public int getRileId() {
30         return rileId;
31     }
32     public void setRileId(int rileId) {
33         this.rileId = rileId;
34     }
35     @Override
36     public String toString() {
37         return "User [id=" + id + ", name=" + name + ", age=" + age
38                 + ", rileId=" + rileId + "]";
39     }
40     
41     
42 }
View Code

4.編寫 映射文件

在cn.vincent.mapper下 UserMapper.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="cn.vincent.mapper.UserMapper">
    <select id="findAll" resultType="User">
        select * from t_user
    </select>
</mapper>

5.編寫 dao

在cn.vincent.mapper下 UserMapper.java

package cn.vincent.mapper;

import java.util.List;

import cn.vincent.vo.User;

public interface UserMapper {

    public List<User> findAll();
}

在cn.vincent.mapper.impl下 UserMapperImpl.java

package cn.vincent.mapper.impl;

import java.util.List;

import org.apache.ibatis.session.SqlSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import cn.vincent.mapper.UserMapper;
import cn.vincent.vo.User;

@Repository("userMapper") public class UserMapperImpl implements UserMapper {

    @Autowired private SqlSession sqlSession;
    public void setSqlSession(SqlSession sqlSession){
        this.sqlSession=sqlSession;
    }
    
    @Override
    public List<User> findAll() {
        return sqlSession.selectList("cn.vincent.mapper.UserMapper.findAll");
    }

    
}

6.編寫 service

在 cn.vincent.service下 UserService.java

package cn.vincent.service;

import java.util.List;

import cn.vincent.vo.User;

public interface UserService {

    public List<User> findAll();
}

在 cn.vincent.service下 UserServiceImpl.java

package cn.vincent.service.impl;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import cn.vincent.mapper.UserMapper;
import cn.vincent.service.UserService;
import cn.vincent.vo.User;

@Service("userService") public class UserServiceImpl implements UserService {

    @Autowired private UserMapper userMapper;
    
    
    public void setUserMapper(UserMapper userMapper) {
        this.userMapper = userMapper;
    }


    @Override
    public List<User> findAll() {
        return userMapper.findAll();
    }

    
}

7. 編寫mybatis的配置文件

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>
        <package name="cn.vincent.vo"/>
    </typeAliases>
    <mappers>
        <mapper resource="cn/vincent/mapper/UserMapper.xml"/>
    </mappers>
</configuration>

8. 編寫spring的配置文件

beans.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:aop="http://www.springframework.org/schema/aop"
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:tx="http://www.springframework.org/schema/tx"
    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.xsd 
        http://www.springframework.org/schema/aop
        http://www.springframework.org/schema/aop/spring-aop.xsd 
        http://www.springframework.org/schema/tx
        http://www.springframework.org/schema/tx/spring-tx.xsd 
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context.xsd">
    <!--讀取外部配置-->
    <bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
        <property name="location" value="classpath:jdbc.properties"></property>
    </bean>
    <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
          <property name="driverClassName" value="${driver}"/>
          <property name="url" value="${url}"/>
          <property name="username" value="${username}"/>
          <property name="password" value="${password}"/>
      </bean>
    <!-- 根據mybatis的配置文件 來創建sqlSessionFactory -->
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="dataSource" ref="dataSource"></property>
        <property name="configLocation" value="classpath:mybatis.cfg.xml"/>
    </bean>
    <bean id="sqlSession" class="org.mybatis.spring.SqlSessionTemplate">
        <constructor-arg index="0" ref="sqlSessionFactory"></constructor-arg>
    </bean>
    <!-- 事務管理器 -->
    <bean id="txManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="dataSource"></property>
    </bean>
    <!-- 事務通知 -->
    <tx:advice id="txAdvice" transaction-manager="txManager">
        <tx:attributes>
          <!-- 表示以save開頭的方法都需要事務      
          propagation  表示事務的傳播特性 
          REQUIRED  查看當前是否有事務,如果有,使用當前事務,如果沒有開啟新事務
          -->
          <tx:method name="save*" propagation="REQUIRED"/>
          <tx:method name="update*" propagation="REQUIRED"/>
          <tx:method name="find*" read-only="true"/>
          <tx:method name="*" propagation="REQUIRED"/>
      </tx:attributes>
    </tx:advice>
    <aop:config>
        <!--expression  指明事務在哪里起作用
        第一個* 表示所有返回值 
        第二個* 表示所有類
        第三個* 表示類中的所有方法
        .. 表示所有參數
          -->
        <aop:pointcut expression="execution(* cn.vincent.service.impl.*.*(..))" id="pointcut"/>
        <aop:advisor advice-ref="txAdvice" pointcut-ref="pointcut"/>
    </aop:config> 
    <context:component-scan base-package="cn.vincent"></context:component-scan>
 </beans>

jdbc.properties

driver=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/test
username=root
password=root

9.添加測試

在 test下的 cn.vincent.service下的 UserServiceTest.java

package cn.vincent.service;

import java.util.List;

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

import cn.vincent.vo.User;

public class UserServiceTest {

    @Test public void testFindAll(){
        ApplicationContext ac=new ClassPathXmlApplicationContext("beans.xml");
        UserService userService=ac.getBean(UserService.class);
        List<User> list=userService.findAll();
        for(User u:list){
            System.out.println(u);
        }
    }
}

10. 運行測試

效果如下:

二. 第二種是去掉mybatis配置文件的配置方法

在beans.xml中修改 SqlSessionFactory的配置

    <!-- 根據mybatis的配置文件 來創建sqlSessionFactory -->
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="dataSource" ref="dataSource"></property>
        <property name="typeAliasesPackage" value="cn.vincent.vo"></property>
        <property name="mapperLocations">
            <list>
                <value>classpath:cn/vincent/mapper/UserMapper.xml</value>
            </list>
        </property>
    </bean>

三. 可以通過代理的方式來生成實現類的配置

beans.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:aop="http://www.springframework.org/schema/aop"
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:tx="http://www.springframework.org/schema/tx"
    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.xsd 
        http://www.springframework.org/schema/aop
        http://www.springframework.org/schema/aop/spring-aop.xsd 
        http://www.springframework.org/schema/tx
        http://www.springframework.org/schema/tx/spring-tx.xsd 
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context.xsd">
      <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
          <property name="driverClassName" value="com.mysql.jdbc.Driver"/>
          <property name="url" value="jdbc:mysql://localhost:3306/test"/>
          <property name="username" value="root"/>
          <property name="password" value="1111"/>
      </bean>
    <!-- 根據mybatis的配置文件 來創建sqlSessionFactory -->
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="dataSource" ref="dataSource"></property>
        <property name="typeAliasesPackage" value="cn.sxt.vo"></property>
        <property name="mapperLocations">
            <list>
                <value>classpath:cn/sxt/mapper/UserMapper.xml</value>
            </list>
        </property>
    </bean>
    <!-- mapper的接口和mapper的映射文件在同一個包下,並且 mapper的接口名稱和mapper的映射文件名相同 mapper接口中的方法名稱和mapper映射文件中的id的名稱一致 mapper映射文件中的namespace和mapper文件所在的包名+mapper文件名 該類將掃描指定的包 並且通過代理生成mapper接口的實現類 生成的類的id名稱為 mapper接口首字母小寫 -->
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <property name="sqlSessionFactory" ref="sqlSessionFactory"></property>
        <property name="basePackage" value="cn.vincent.mapper"></property>
    </bean>
    <!-- 事務管理器 -->
    <bean id="txManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="dataSource"></property>
    </bean>
    <!-- 事務通知 -->
    <tx:advice id="txAdvice" transaction-manager="txManager">
        <tx:attributes>
          <!-- 表示以save開頭的方法都需要事務      
          propagation  表示事務的傳播特性 
          REQUIRED  查看當前是否有事務,如果有,使用當前事務,如果沒有開啟新事務
          -->
          <tx:method name="save*" propagation="REQUIRED"/>
          <tx:method name="update*" propagation="REQUIRED"/>
          <tx:method name="find*" read-only="true"/>
          <tx:method name="*" propagation="REQUIRED"/>
      </tx:attributes>
    </tx:advice>
    <aop:config>
        <!--expression  指明事務在哪里起作用
        第一個* 表示所有返回值 
        第二個* 表示所有類
        第三個* 表示類中的所有方法
        .. 表示所有參數
          -->
        <aop:pointcut expression="execution(* cn.vincent.service.impl.*.*(..))" id="pointcut"/>
        <aop:advisor advice-ref="txAdvice" pointcut-ref="pointcut"/>
    </aop:config> 
       <context:component-scan base-package="cn.vincent"></context:component-scan>
</beans>

github地址:https://github.com/Vincent-yuan/spring_mybatis


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM