• Spring整合Mybatis--xml配置文件方式


    1.环境搭建

    1.1.导入依赖

         <dependency>
                <groupId>junit</groupId>
                <artifactId>junit</artifactId>
                <version>4.11</version>
            </dependency>
    <!--        Spring需要的依赖-->
           <!-- https://mvnrepository.com/artifact/org.springframework/spring-webmvc -->
           <dependency>
               <groupId>org.springframework</groupId>
               <artifactId>spring-webmvc</artifactId>
               <version>5.2.5.RELEASE</version>
           </dependency>
    <!--        Spring整合需要的依赖-->
           <!-- https://mvnrepository.com/artifact/org.springframework/spring-jdbc -->
           <dependency>
               <groupId>org.springframework</groupId>
               <artifactId>spring-jdbc</artifactId>
               <version>5.2.5.RELEASE</version>
           </dependency>
    <!--        事物需要的依赖-->
            <!-- https://mvnrepository.com/artifact/org.aspectj/aspectjweaver -->
            <dependency>
                <groupId>org.aspectj</groupId>
                <artifactId>aspectjweaver</artifactId>
                <version>1.9.5</version>
            </dependency>
           <!--Mybatis需要的依赖-->
           <!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java -->
            <dependency>
                <groupId>mysql</groupId>
                <artifactId>mysql-connector-java</artifactId>
                <version>5.1.49</version>
            </dependency>
            <!-- https://mvnrepository.com/artifact/org.mybatis/mybatis -->
            <dependency>
                <groupId>org.mybatis</groupId>
                <artifactId>mybatis</artifactId>
                <version>3.5.2</version>
            </dependency>
            <!-- https://mvnrepository.com/artifact/log4j/log4j -->
            <dependency>
                <groupId>log4j</groupId>
                <artifactId>log4j</artifactId>
                <version>1.2.17</version>
            </dependency>
            <!-- https://mvnrepository.com/artifact/org.mybatis/mybatis-spring -->
            <dependency>
                <groupId>org.mybatis</groupId>
                <artifactId>mybatis-spring</artifactId>
                <version>2.0.2</version>
            </dependency>
         <!--END-->
    

    1.2 创建实体类

    public class User {
        private int id;
        private String username;
        private String password;
    }
    

    1.3 配置文件

    1.3.1 Spring-dao.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-4.1.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">
    
    </beans>
    

    配置数据源

    <!--   配置数据源   我这是使用Spring的数据源-->
        <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
            <property name="driverClassName" value="com.mysql.jdbc.Driver"/>
            <property name="url" value="jdbc:mysql://127.0.0.1:3306/sqltest?useUnicode=true&amp;characterEncoding=utf-8"/>
            <property name="username" value="root"/>
            <property name="password" value="root"/>
        </bean>
    

    获取SqlSessionFactory

    <!--    获取sqlSessionFactory-->
      <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
          <!-- 映射数据源 -->
          <property name="dataSource" ref="dataSource"/>
             <!-- 映射mybatis核心配置文件 -->
          <property name="configLocation" value="classpath:mybatis/mybatis-config.xml"/>
          <!-- 映射mapper文件 -->
          <property name="mapperLocations" value="classpath:mapper/*.xml"/>
      </bean>
    

    获得SqlSession

     <!-- 获得sqlSession -->
        <bean id="sqlSession" class="org.mybatis.spring.SqlSessionTemplate">
                <!--只能用构造方法设置-->
            <constructor-arg name="sqlSessionFactory" ref="sqlSessionFactory"/>
        </bean>
    

    配置声明式事物

       <!--   配送声明式事物-->
    <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
             <!--        映射数据源-->
            <property name="dataSource" ref="dataSource"/>
    </bean>
    

    配置事物通知

        <!--    结合aop实现是事物植入-->
        <!--    配置事物通知-->
        <tx:advice id="transaction" transaction-manager="transactionManager">
    <!-- 给哪些方法配置事物-->
            <tx:attributes>
                <tx:method name="add*" propagation="REQUIRED"/>
                <tx:method name="query*" propagation="SUPPORTS"/>
                <tx:method name="update*" propagation="REQUIRED"/>
                <tx:method name="delete*" propagation="REQUIRED"/>
            </tx:attributes>
        </tx:advice>
    

    Spring中七种Propagation类的事务属性详解:

    REQUIRED:支持当前事务,如果当前没有事务,就新建一个事务。这是最常见的选择。

    SUPPORTS:支持当前事务,如果当前没有事务,就以非事务方式执行。

    MANDATORY:支持当前事务,如果当前没有事务,就抛出异常。

    REQUIRES_NEW:新建事务,如果当前存在事务,把当前事务挂起。

    NOT_SUPPORTED:以非事务方式执行操作,如果当前存在事务,就把当前事务挂起。

    NEVER:以非事务方式执行,如果当前存在事务,则抛出异常。

    NESTED:支持当前事务,如果当前事务存在,则执行一个嵌套事务,如果当前没有事务,就新建一个事务。

    配置SpringAOP切面植入事物

    <!--配置切面-->
        <aop:config>
            <aop:pointcut id="point" expression="execution(* com.lgw.dao.*.*(..))"/>
            <aop:advisor advice-ref="transaction" pointcut-ref="point"></aop:advisor>
        </aop:config>
    

    1.3.2 mybatis-config.xml

    建议把 settingstypeAliases 存放在 mybatis-config.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>
        <settings>
            <!--标准日志输出-->
            <!--<setting name="logImpl" value="STDOUT_LOGGING"/>-->
            <setting name="logImpl" value="LOG4J"/>
            <!--驼峰解决字段对应-->
            <setting name="mapUnderscoreToCamelCase" value="true"/>
            <!--懒加载-->
            <setting name="lazyLoadingEnabled" value="true"/>
        </settings>
        <!--别名-->
        <typeAliases>
            <package name="com.lgw.pojo"/>
        </typeAliases>
    </configuration>
    

    2.编写代码

    创建*Mapper接口

    public interface UserMapper {
    //    查询全部
        List<User>  queryUsers();
    }
    

    创建*Mapper.xml

    <?xml version="1.0" encoding="UTF-8" ?>
    <!DOCTYPE mapper
            PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
            "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
    <mapper namespace="com.lgw.dao.UserMapper">
    <select id="queryUsers"  resultType="User">
        select id,username,password from user;
    </select>
    </mapper>
    

    创建*MapperImpl类

    方式一

    public class UserMapperImpl implements UserMapper {
        private SqlSessionTemplate sqlsession;
    
        public void setSqlsession(SqlSessionTemplate sqlsession) {
            this.sqlsession = sqlsession;   
        }
        
            public List<User> queryUsers() {
            return sqlsession.getMapper(UserMapper.class).queryUsers();
        }
    

    方式二 继承SqlSessionDaoSupport

    public class UserMapperImpl2 extends SqlSessionDaoSupport implements UserMapper {
          public List<User> queryUsers() {
            return sqlsession.getMapper(UserMapper.class).queryUsers();
        }
    }
    

    把*MapperImpl纳入Spring管理

    把刚刚的Spring-dap.xml用Import导入过来

    <?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:aop="http://www.springframework.org/schema/aop"
           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/spring-aop.xsd">
    
        <import resource="spring-dao.xml"/>
    
        <bean id="UserMapperImpl" class="com.lgw.dao.UserMapperImpl">
            <property name="sqlsession" ref="sqlSession"/>
        </bean>
        
        <bean id="UserMapperImpl2" class="com.lgw.dao.UserMapperImpl2">
            <property name="sqlSessionFactory" ref="sqlSessionFactory"/>
        </bean>
    

    3.junit测试

        @Test
        public void SpringMybatisTest(){
            ApplicationContext context=new ClassPathXmlApplicationContext("applicationContext.xml");
            UserMapper bean = (UserMapper) context.getBean("UserMapperImpl");
            List<User> userList = bean.queryUsers();
            for (User user : userList) {
                System.out.println(user);
            }
        }
    
  • 相关阅读:
    牛客网 二叉树的镜像 JAVA
    牛客网 反转链表 JAVA
    牛客网 调整数组顺序使奇数位于偶数前面 JAVA
    Integer to Roman LeetCode Java
    Valid Number leetcode java
    Longest Common Prefix
    Wildcard Matching leetcode java
    Regular Expression Matching
    Longest Palindromic Substring
    Add Binary LeetCode Java
  • 原文地址:https://www.cnblogs.com/sky1023/p/13100754.html
Copyright © 2020-2023  润新知