• 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

  • 相关阅读:
    前端试题本(Javascript篇)
    前端知识杂烩(Javascript篇)
    前端知识杂烩(HTML[5]?+CSS篇)
    Javascript实现的数组降维——维度不同,怎么谈恋爱
    你不知道的CSS背景—css背景属性全解
    基于Codeigniter框架实现的APNS批量推送—叮咚,查水表
    CSS布局经典—圣杯布局与双飞翼布局
    JavaScript异步编程的主要解决方案—对不起,我和你不在同一个频率上
    CSS实现元素水平垂直居中—喜欢对称美,这病没得治
    JS实现常用排序算法—经典的轮子值得再造
  • 原文地址:https://www.cnblogs.com/Vincent-yuan/p/11298922.html
Copyright © 2020-2023  润新知