zoukankan      html  css  js  c++  java
  • Spring和MyBatis的整合

    1. Spring和各个框架的整合

    Spring目前是JavaWeb开发中最终的框架,提供一站式服务,可以其他各个框架整合集成

    Spring整合方案

    1.1. SSH

    ssh是早期的一种整合方案

    Struts2 Web层框架

    Spring : 容器框架

    Hibernate : 持久层框架

    1.2. SSM

    主流的项目架构的三大框架(相对其他框架而言,最优秀)

     SpringMVC spring自己家的 Web层框架,spring的一个模块

     Spring :容器框架

     MyBatis :持久层框架

    2. SpringMyBatis整合

    2.1. 集成思路

    实际开发,使用Maven项目,直接引入项项目在Maven仓库中的坐标即可

    学习阶段: 手动导入jar包,从零开始集成(巩固基础知识)

    2.2. 创建java项目

    准备集成相关jar

     

    完成项目层与层之间spring对象的创建和依赖关系的维护

    package cn.sxt.pojo;
    
    public class User {
        private Integer id;
        private String name;
        private String password;
        private Integer age;
        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 String getPassword() {
            return password;
        }
        public void setPassword(String password) {
            this.password = password;
        }
        public Integer getAge() {
            return age;
        }
        public void setAge(Integer age) {
            this.age = age;
        }
        @Override
        public String toString() {
            return "User [id=" + id + ", name=" + name + ", password=" + password + ", age=" + age + "]";
        }
        public User(Integer id, String name, String password, Integer age) {
            super();
            this.id = id;
            this.name = name;
            this.password = password;
            this.age = age;
        }
        public User() {
            super();
            // TODO Auto-generated constructor stub
        }
        
    }
    package cn.sxt.mapper;
    
    import java.util.List;
    
    import cn.sxt.pojo.User;
    
    public interface UserMapper {
    
        int insert(User user);
    
        int deleteByPrimaryKey(Integer id);
    
        int updateByPrimaryKey(User user);
    
        User selectByPrimaryKey(Integer id);
    
        List<User> selectList();
    }
    <?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.sxt.mapper.UserMapper">
          
          <insert id="insert" parameterType="User"
              keyColumn="id"
              keyProperty="id"
              useGeneratedKeys="true"
          >
              insert into user (name,password,age)values(#{name},#{password},#{age})
              
          </insert>
          <!-- 单行查询
              <select resultType ="">
              查询功能的标签
              resultType : 返回结果的数据类型,和接口对应方法的返回类型必须一致
           -->
          <select id="selectByPrimaryKey" parameterType="Integer" resultType="User">
              <!--  #{对象属性} ,主键理论上任何值都可以 #{abc},#{xxx},可以不用对象属性-->
              select * from user where id = #{id}
          </select>
          
          <!-- 多行查询
              无论单行或者多行查询,返回的数据类型都是 对应 pojo 对应的对象类型
           -->
          <select id="selectList" resultType="User">
              select * from user
          </select>
          
          <!-- 删除操作 -->
          <delete id="deleteByPrimaryKey" parameterType="Integer">
              delete from user where id = #{id}
          </delete>
          
          
          <!-- 修改操作 -->
          <update id="updateByPrimaryKey" parameterType="User">
              <!-- 固定语义的sql语句 -->
              update user set name = #{name},password = #{password},age = #{age} where id = #{id}
          </update>
          
    </mapper>
    package cn.sxt.service;
    
    import java.util.List;
    
    import cn.sxt.pojo.User;
    
    public interface UserService {
        int insert(User user);
    
        int deleteByPrimaryKey(Integer id);
    
        int updateByPrimaryKey(User user);
    
        User selectByPrimaryKey(Integer id);
    
        List<User> selectList();
    }
    package cn.sxt.service.impl;
    
    import java.util.List;
    
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.stereotype.Service;
    
    import cn.sxt.mapper.UserMapper;
    import cn.sxt.pojo.User;
    import cn.sxt.service.UserService;
    
    
    @Service
    public class UserServiceImpl implements UserService {
        /*
         *     问题1 : UserMapper是接口,如何创建对象?
         *     答: 使用MyBatis的SqlSession 会话对象。
         * 
         *    问题2:SqlSession如何创建?
         *    答: 使用MyBatis的SqlSessionFactory 工厂对象创建
         *
         *    问题3:SqlSessionFactory工厂对象如何创建?
         *
         *    答:在使用Spring之前
         *    开发者自己写代码读取MyBatis配置文件,创建SqlSessionFactory
         *    使用Spring之后,让Spring框架帮我们创建
         *
         *    问题4:SqlSessionFactory 工厂对象Spring框架如何创建出来?
         *
         *    答:MyBatis工厂对象创建的类在 MyBatis框架和Spring集成的桥梁包mybatis-spring-1.3.1.jar
         *      的org.mybatis.spring.SqlSessionFactoryBean 负责创建工厂对象
         *        开发者只需要在Spring配置配置此类就可以创建出来SqlSessionFactory对象 
         * 
         */
        @Autowired
        private UserMapper mapper;
    
        @Override
        public int insert(User user) {
            return mapper.insert(user);
        }
    
        @Override
        public int deleteByPrimaryKey(Integer id) {
            return mapper.deleteByPrimaryKey(id);
        }
    
        @Override
        public int updateByPrimaryKey(User user) {
            return mapper.updateByPrimaryKey(user);
        }
    
        @Override
        public User selectByPrimaryKey(Integer id) {
            return mapper.selectByPrimaryKey(id);
        }
    
        @Override
        public List<User> selectList() {
            return mapper.selectList();
        }
    
        
    }
    package cn.sxt.test;
    import java.util.List;
    
    import org.junit.Test;
    import org.junit.runner.RunWith;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.test.context.ContextConfiguration;
    import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
    
    import cn.sxt.pojo.User;
    import cn.sxt.service.UserService;
    @RunWith(SpringJUnit4ClassRunner.class)
    @ContextConfiguration("classpath:applicationContext.xml")
    public class test01 {
        @Autowired
        private UserService service;
        @Test
        public void testInsert() {
            User user = new User(null, "虚竹", "xuzhu", 30);
            service.insert(user);
        }
    
        @Test
        public void testDeleteByPrimaryKey() {
            service.deleteByPrimaryKey(10);
        }
    
        @Test
        public void testUpdateByPrimaryKey() {
            User user = new User(9, "孙悟空", "wukong", 600);
            service.updateByPrimaryKey(user );
        }
    
        @Test
        public void testSelectByPrimaryKey() {
            User user = service.selectByPrimaryKey(11);
        }
    
        @Test
        public void testSelectList() {
            List<User> users = service.selectList();
        }
    
    }
    <?xml version="1.0" encoding="UTF-8"?>
    <beans xmlns="http://www.springframework.org/schema/beans"
        xmlns:p="http://www.springframework.org/schema/p"
        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: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/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
            ">
    
    
        <!-- 配置组件包扫描的位置 -->
        <context:component-scan base-package="cn.sxt" />
        <!-- 读取db.properties配置文件到Spring容器中 -->
        <context:property-placeholder
            location="classpath:db.properties" />
        <!-- 配置 阿里巴巴的 druid 数据源(连接池) -->
        <bean id="dataSource"
            class="com.alibaba.druid.pool.DruidDataSource" init-method="init"
            destroy-method="close">
            <!-- SpringEL 语法 ${key} -->
            <property name="driverClassName"
                value="${jdbc.driverClassName}" />
            <property name="url" value="${jdbc.url}" />
    
            <!-- ${username}如果key是username,name 默认spring框架调用的当前操作系统的账号 解决方案:可以统一给key加一个前缀 -->
    
            <property name="username" value="${jdbc.username}" />
            <property name="password" value="${jdbc.password}" />
            <property name="maxActive" value="${jdbc.maxActive}" />
    
        </bean>
        <!-- 创建SqlSessionFactory MyBatis会话工厂对象 -->
        <bean id="sqlSessionFactory"
            class="org.mybatis.spring.SqlSessionFactoryBean">
            <!-- 注入数据源 -->
            <property name="dataSource" ref="dataSource" />
            <!-- 读取映射文件 ,MyBatis的纯注解不用配置 -->
            <property name="mapperLocations">
                <array>
                    <!-- 配置单个映射文件 -->
                    <!-- <value>classpath:cn/zj/ssm/mapper/UserMapper.xml</value> -->
                    <!-- 配置多个映射文件使用 * 通配符 -->
                    <value>classpath:cn/sxt/mapper/*Mapper.xml</value>
                </array>
    
            </property>
            <!-- 配置mybatis-confg.xml主配置文件(注配置文件可以保留一些个性化配置,缓存,日志,插件) -->
            <property name="configLocation"
                value="classpath:mybatis-config.xml" />
            <!-- 配置别名,使用包扫描 -->
            <property name="typeAliasesPackage" value="cn.sxt.pojo"></property>
        </bean>
        <!-- SqlSession 不用单独创建,每次做crud操作都需要Mapper接口的代理对象 而代理对象的创建又必须有 SqlSession对象创建 
            Spring在通过MyBatis创建 Mapper接口代理对象的时候,底层自动把SqlSession会话对象创建出来 -->
    
        <!-- 创建UserMapper接口的代理对象,创建单个代理对象 参考桥梁包:org.mybatis.spring.mapper.MapperFactoryBean<T> 
            此类就是创建 Mapper 代理对象的类 -->
        <!--<bean id="userMapper" class="org.mybatis.spring.mapper.MapperFactoryBean"> 
            注入UserMapper接口 <property name="mapperInterface" value="cn.sxt.mapper.UserMapper"/> 
            注入sqlSessionFactory工厂对象 <property name="sqlSessionFactory" ref="sqlSessionFactory"/> 
            </bean> -->
        <!-- 使用包扫描创建代理对象,包下面所有Mapper接口统一创建代理对象 使用桥梁包下面 : org.mybatis.spring.mapper.MapperScannerConfigurer 
            可以包扫描创建所有映射接口的代理对象 -->
        <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
            <!-- 配置SqlSessionFactoryBean的名称 -->
            <property name="basePackage" value="cn.sxt.mapper"/>
            <!-- 可选,如果不写,Spring启动时候。容器中。自动会按照类型去把SqlSessionFactory对象注入进来 -->
            <!-- <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/> -->
    
            <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/>
    
        </bean>
        <!--  1.配置事务管理器 -->
        <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <!-- 注入数据源 -->
        
        <property name="dataSource" ref="dataSource"></property>
        
        </bean>
        <!-- 
            2.配置事务的细节
            配置事务通知/增强
         -->
         <tx:advice id="tx" transaction-manager="transactionManager" >
         
         <!-- 配置属性 -->
             <tx:attributes>
                 <!-- DQL  -->
                 <tx:method name="select*" read-only="true" isolation="REPEATABLE_READ" propagation="REQUIRED" timeout="5"/>
                 <tx:method name="query*" read-only="true" isolation="REPEATABLE_READ" propagation="REQUIRED" timeout="5"/>
                 <tx:method name="get*" read-only="true" isolation="REPEATABLE_READ" propagation="REQUIRED" timeout="5"/>
                 <tx:method name="find*" read-only="true" isolation="REPEATABLE_READ" propagation="REQUIRED" timeout="5"/>
                 <!-- 其他 -->
                 <tx:method name="*" read-only="false" isolation="REPEATABLE_READ" propagation="REQUIRED" timeout="5"/>
         </tx:attributes>
         </tx:advice>
        
        <!-- 
                3.使用AOP将事务切到Service层
            -->
            <aop:config>
                <!-- 配置切入点 -->
                <aop:pointcut expression="execution(* cn.zj.ssm.service..*.*(..))" id="pt"/>
            <!-- 配置切面= 切入点+通知 -->
            <aop:advisor advice-ref="tx" pointcut-ref="pt"/>
            </aop:config>
    
    </beans>
    jdbc.driverClassName=com.mysql.cj.jdbc.Driver
    jdbc.url=jdbc:mysql://localhost:3306/mybatis?useUnicode=true&characterEncoding=utf-8&serverTimezone=GMT
    jdbc.username=root
    jdbc.password=gzsxt
    jdbc.maxActive=10
    # Global logging configuration
    log4j.rootLogger=ERROR, stdout
    # MyBatis logging configuration...
    log4j.logger.cn.sxt.mapper=TRACE
    # Console output...
    log4j.appender.stdout=org.apache.log4j.ConsoleAppender
    log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
    log4j.appender.stdout.layout.ConversionPattern=%5p [%t] - %m%n
    <?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>
         <!-- mybatis框架的个性化配置可在此配置 -->
         
    </configuration>
  • 相关阅读:
    用elasticsearch分析中国大学省份分布
    【翻译】Kinect v1和Kinect v2的彻底比较
    翻译 Tri-Ace:在Shader里近似渲染公式
    翻译 基于物理渲染的美术资源设计流程
    翻译 次世代基于物理渲染的反射模型
    关于Depth Bounds Test (DBT)和在CE3的运用
    使用Xcode GPU Frame Caputre教程
    如何使用Xcode分析调试在真机运行的UE4 IOS版游戏
    个人翻译的cedec2010基于物理的光照
    使用Nsight查找CE3的渲染bug
  • 原文地址:https://www.cnblogs.com/406070989senlin/p/11154791.html
Copyright © 2011-2022 走看看