• 2020-02-15


    庚子鼠年 戊寅月 戊子日

    描述

    spring-mybatis 文档阅读 http://mybatis.org/spring/zh/index.html

    spring-mybatis xml配置

    spring-mybatis java配置

    技术总结:spring-mybaits配置https://blog.csdn.net/qq_40674583/article/details/104332196

    随笔

    dataSource

    <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource"
          init-method="init" destroy-method="close">
        <property name="driverClassName" value="${driver}" />
        <property name="url" value="${url}" />
        <property name="username" value="${user}" />
        <property name="password" value="${password}" />
        <!-- 配置初始化大小、最小、最大 -->
        <property name="initialSize" value="1" />
        <property name="minIdle" value="1" />
        <property name="maxActive" value="10" />
    
        <!-- 配置获取连接等待超时的时间 -->
        <property name="maxWait" value="10000" />
    
        <!-- 配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒 -->
        <property name="timeBetweenEvictionRunsMillis" value="60000" />
    
        <!-- 配置一个连接在池中最小生存的时间,单位是毫秒 -->
        <property name="minEvictableIdleTimeMillis" value="300000" />
    
        <property name="testWhileIdle" value="true" />
    
        <!-- 这里建议配置为TRUE,防止取到的连接不可用 -->
        <property name="testOnBorrow" value="true" />
        <property name="testOnReturn" value="false" />
    
        <!-- 打开PSCache,并且指定每个连接上PSCache的大小 -->
        <property name="poolPreparedStatements" value="true" />
        <property name="maxPoolPreparedStatementPerConnectionSize"
                  value="20" />
    
        <!-- 这里配置提交方式,默认就是TRUE,可以不用配置 -->
        <property name="defaultAutoCommit" value="true" />
    
        <!-- 验证连接有效与否的SQL,不同的数据配置不同 -->
        <property name="validationQuery" value="select 1 " />
        <property name="filters" value="stat" />
    </bean>
    

    SqlSessionFactoryBean

    在基础的 MyBatis 用法中,是通过 SqlSessionFactoryBuilder 来创建 SqlSessionFactory 的。 而在 MyBatis-Spring 中,则使用 SqlSessionFactoryBean 来创建。

    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
      <property name="dataSource" ref="dataSource" />
        <!-- mybatis的配置文件设置(<settings>或<typeAliases>)-->
      <property name="configLocation" value="classpath:mybatis-config.xml"/>
    </bean>
    

    属性

    • SqlSessionFactory 有一个唯一的必要属性:用于 JDBC 的 DataSource。这可以是任意的 DataSource 对象,它的配置方法和其它 Spring 数据库连接是一样的。
    • 一个常用的属性是 configLocation,它用来指定 MyBatis 的 XML 配置文件路径。通常,基础配置指的是<settings> 或<typeAliases> 元素,需要注意的是,这个配置文件并不需要是一个完整的 MyBatis 配置。

    事务

    <!--配置Spring框架声明式事务管理-->
    <!--配置事务管理器-->
    <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="dataSource"/>
    </bean>
    
    <!--配置事务通知-->
    <tx:advice id="txAdvice" transaction-manager="transactionManager">
        <tx:attributes>
            <tx:method name="find*" read-only="true"/>
            <tx:method name="*" isolation="DEFAULT"/>
        </tx:attributes>
    </tx:advice>
    
    <!--配置AOP增强-->
    <aop:config>
        <aop:advisor advice-ref="txAdvice" pointcut="execution(* chang.service.impl.*ServiceImpl.*(..))"/>
    </aop:config>
    

    自动扫描Mapper

    <mybatis:scan base-package="chang.mapper" />
    

    如果需要使用mybatis的SqlSession

    <bean id="sqlSession" class="org.mybatis.spring.SqlSessionTemplate">
      <constructor-arg index="0" ref="sqlSessionFactory" />
    </bean>
    

    是自动扫描不香吗?要去用SqlSession获取mapper

    使用SqlSessionDaoSupport

    public class UserDaoImpl extends SqlSessionDaoSupport implements UserDao {
      public User getUser(String userId) {
        return getSqlSession().selectOne("org.mybatis.spring.sample.mapper.UserMapper.getUser", userId);
      }
    }
    
    <bean id="userDao" class="org.mybatis.spring.sample.dao.UserDaoImpl">
      <property name="sqlSessionFactory" ref="sqlSessionFactory" />
    </bean>
    

    使用注解配置

    test测试

    Maven 依赖

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-test</artifactId>
            <version>5.0.2.RELEASE</version>
        </dependency>
    
    @RunWith(SpringJUnit4ClassRunner.class)
    @ContextConfiguration(locations = "classpath:applicationContext.xml")
    @ContextConfiguration(classes = SimpleConfiguration.class)
    多个文件时,可用{}
    @ContextConfiguration(locations = { "classpath*:/spring1.xml", "classpath*:/spring2.xml" })
    

    引入配置参数

    @PropertySource({"classpath:teacher.properties"}) //指定某配置文件,无此参数则在默认全局配置文件中获取
    @ConfigurationProperties(prifix=“teacher”) //配置文件中前缀名为teacher的配置项的所有属性都映射到此JavaBean中
    

    Resource 子类

    ClassPathResource可用来获取类路径下的资源文件

    FileSystemResource可用来获取文件系统里面的资源。FileSystemResource还可以往对应的资源文件里面写内容,当然前提是当前资源文件是可写的,这可以通过其isWritable()方法来判断。FileSystemResource对外开放了对应资源文件的输出流,可以通过getOutputStream()方法获取到。

    UrlResource可用来代表URL对应的资源,它对URL做了一个简单的封装。

    ByteArrayResource是针对于字节数组封装的资源,它的构建需要一个字节数组。

    ServletContextResource是针对于ServletContext封装的资源,用于访问ServletContext环境下的资源。

    InputStreamResource是针对于输入流封装的资源,它的构建需要一个输入流。

    SpringConfig.java 配置类

    package chang.config;
    
    import com.alibaba.druid.pool.DruidDataSource;
    import org.apache.ibatis.session.SqlSessionFactory;
    import org.mybatis.spring.SqlSessionFactoryBean;
    import org.mybatis.spring.annotation.MapperScan;
    import org.springframework.beans.factory.annotation.Value;
    import org.springframework.context.annotation.Bean;
    import org.springframework.context.annotation.Configuration;
    import org.springframework.context.annotation.PropertySource;
    import org.springframework.core.io.ClassPathResource;
    
    import javax.sql.DataSource;
    
    @Configuration
    @MapperScan("chang.mapper")
    @PropertySource(value= {"classpath:db.properties"}, ignoreResourceNotFound = true) //读取外部文件获取jdbc参数值
    public class SpringConfig {
    
        @Value("${url}")
        private String url;
    
        @Value("${driver}")
        private String driver;
    
        @Value("${user}")
        private String user;
    
        @Value("${password}")
        private String password;
    
        @Bean(destroyMethod = "close",initMethod = "init")
        public DataSource dataSource() {
            DruidDataSource druidDataSource = new DruidDataSource();
            druidDataSource.setDriverClassName(driver);
            druidDataSource.setUrl(url);
            druidDataSource.setUsername(user);
            druidDataSource.setPassword(password);
            /*配置初始化大小、最小、最大*/
            druidDataSource.setInitialSize(1);
            druidDataSource.setMinIdle(1);
            druidDataSource.setMaxActive(10);
            /*配置获取连接等待超时的时间*/
            druidDataSource.setMaxWait(10000L);
            /*配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒*/
            druidDataSource.setTimeBetweenEvictionRunsMillis(60000L);
            /*配置一个连接在池中最小生存的时间,单位是毫秒*/
            druidDataSource.setMinEvictableIdleTimeMillis(300000L);
    
        /*
            <property name="testWhileIdle" value="true" />
    
            <!-- 这里建议配置为TRUE,防止取到的连接不可用 -->
            <property name="testOnBorrow" value="true" />
            <property name="testOnReturn" value="false" />
    
            <!-- 打开PSCache,并且指定每个连接上PSCache的大小 -->
            <property name="poolPreparedStatements" value="true" />
            <property name="maxPoolPreparedStatementPerConnectionSize"
            value="20" />
    
            <!-- 这里配置提交方式,默认就是TRUE,可以不用配置 -->
            <property name="defaultAutoCommit" value="true" />
    
            <!-- 验证连接有效与否的SQL,不同的数据配置不同 -->
            <property name="validationQuery" value="select 1 " />
            <property name="filters" value="stat" />
          */
            return druidDataSource;
        }
    
        @Bean
        public SqlSessionFactory sqlSessionFactory() throws Exception {
            SqlSessionFactoryBean factoryBean = new SqlSessionFactoryBean();
            factoryBean.setDataSource(dataSource());
            factoryBean.setConfigLocation(new ClassPathResource("mybatis-config.xml"));
            return factoryBean.getObject();
        }
    
    
    }
    

    测试类

    package chang.mapper;
    
    import chang.config.SpringConfig;
    import chang.pojo.User;
    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;
    
    
    @RunWith(SpringJUnit4ClassRunner.class)
    @ContextConfiguration(classes = SpringConfig.class)
    public class UserMapperTest {
    
        @Autowired
        private UserMapper userMapper;
    
        @Test
        public void javaConfig_findOneByXh(){
    
            User user = userMapper.findOneByXh("20177583");
            System.out.println(user);
    
        }
    
    }
    
  • 相关阅读:
    SpringMVC学习笔记----
    各种语言学习
    七步精通Python机器学习 转
    开源GIS有用
    sql 语句
    调试windows服务最简单的方法之一
    sqlserver2008 win7下安装 windows installer错误
    高德地图AmapSDKDemo运行
    google mapsDemo示例运行
    android开发环境搭建遇到的问题
  • 原文地址:https://www.cnblogs.com/chang1024/p/12313765.html
Copyright © 2020-2023  润新知