第四章 Spring集成MyBatis

第四章 Spring集成MyBatis,第1张


<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0modelVersion>

    <groupId>cn.webrxgroupId>
    <artifactId>spring-mybatisartifactId>
    <version>1.0version>
    <package>jarpackage>

    <properties>
        <maven.compiler.source>15maven.compiler.source>
        <maven.compiler.target>15maven.compiler.target>
    properties>

    <dependencies>
        <dependency>
            <groupId>org.springframeworkgroupId>
            <artifactId>spring-contextartifactId>
            <version>5.3.8version>
        dependency>
        <dependency>
            <groupId>org.springframeworkgroupId>
            <artifactId>spring-jdbcartifactId>
            <version>5.3.8version>
        dependency>

        <dependency>
            <groupId>org.springframeworkgroupId>
            <artifactId>spring-testartifactId>
            <version>5.3.8version>
        dependency>

        <dependency>
            <groupId>org.projectlombokgroupId>
            <artifactId>lombokartifactId>
            <version>1.18.20version>
            <scope>providedscope>
        dependency>
    
        <dependency>
            <groupId>org.mybatisgroupId>
            <artifactId>mybatis-springartifactId>
            <version>2.0.6version>
        dependency>

        <dependency>
            <groupId>org.mybatisgroupId>
            <artifactId>mybatisartifactId>
            <version>3.5.7version>
        dependency>
  
        <dependency>
            <groupId>mysqlgroupId>
            <artifactId>mysql-connector-javaartifactId>
            <version>8.0.25version>
        dependency>
     
        <dependency>
            <groupId>com.alibabagroupId>
            <artifactId>druidartifactId>
            <version>1.2.6version>
        dependency>

    dependencies>
project>

编写统计properties数据库配置文件,src/main/resources/db.properties 或 db.properties

druid.driverClassName=com.mysql.cj.jdbc.Driver
druid.url=jdbc:mysql://localhost:3306/wxdb?serverTimezone=PRC
druid.username=root
druid.password=nieps
druid.filters=stat
druid.initialSize=2
druid.maxActive=300
druid.maxWait=60000

编写配置类

/*
 * Copyright (c) 2006, 2021, webrx.cn All rights reserved.
 *
 */
package cn.webrx.wxs.config;

import com.alibaba.druid.pool.DruidDataSource;
import com.github.pagehelper.PageInterceptor;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.annotation.MapperScan;
import org.mybatis.spring.mapper.MapperScannerConfigurer;
import org.springframework.beans.factory.annotation.Qualifier;
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.Resource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.core.io.support.ResourcePatternResolver;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;

import javax.sql.DataSource;
import java.io.IOException;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Properties;

/**
 * 

Project: ssm0 - ApplicationContextConfig *

Description : 相当于 resources/applicationContext.xml spring IoC 框架核心配置文件 * * @author webrx [[email protected]] * @version 1.0 * @since 15 */ @Configuration @MapperScan("cn.webrx.wxs.mapper") //加载properties @PropertySource("classpath:db.properties") public class ApplicationContextConfig { //@Value("#{systemProperties['os.name']}") //@Value("#{ T(java.lang.Math).random() * 100.0 }") @Value("${db.url}") private String url; @Value("${db.username}") private String username; @Value("${db.driver}") private String driver; @Value("${db.filters}") private String filters; @Value("${db.password}") private String password; @Value("${db.publicKey}") private String publickey; @Bean("ds") public DataSource druidDataSource(@Value("${db.driver}") String driver, @Value("${db.password}") String password, @Value("${db.publicKey}") String publickey, @Value("${db.filters}") String filters, @Value("${db.url}") String url, @Value("${db.username}") String uname) throws SQLException { DruidDataSource ds = new DruidDataSource(); ds.setUrl(url); ds.setUsername(uname); ds.setPassword(password); ds.setFilters(filters); ds.setConnectionProperties("config.decrypt=true;config.decrypt.key=" + publickey); ds.setDriverClassName(driver); return ds; } /** * 配置事务管理器 */ //@Bean public DataSourceTransactionManager getDataSourceTransactionManager(@Qualifier("ds") DataSource ds) { DataSourceTransactionManager dataSourceTransactionManager = new DataSourceTransactionManager(); dataSourceTransactionManager.setDataSource(ds); return dataSourceTransactionManager; } /** * 配置分页插件(mybatis拦截器插件) * * @return */ public PageInterceptor pageInterceptor() { var pi = new PageInterceptor(); var prop = new Properties(); prop.setProperty("reasonable", "true"); pi.setProperties(prop); return pi; } /** * 注册SqlSessionFactory * * @param ds * @return */ @Bean("sf") public SqlSessionFactoryBean sqlSessionFactoryBean(@Qualifier("ds") DataSource ds) { SqlSessionFactoryBean sf = new SqlSessionFactoryBean(); sf.setDataSource(ds); //mybatis 分页插件注册 sf.setPlugins(pageInterceptor()); sf.setTypeAliasesPackage("cn.webrx.wxs.entity"); sf.setMapperLocations(resolveMapperLocations()); return sf; } public Resource[] resolveMapperLocations() { ResourcePatternResolver resourceResolver = new PathMatchingResourcePatternResolver(); List<String> mapperLocations = new ArrayList<>(); mapperLocations.add("classpath:cn/webrx/wxs/mapper/*Mapper.xml"); List<Resource> resources = new ArrayList<>(); for (String mapperLocation : mapperLocations) { try { Resource[] mappers = resourceResolver.getResources(mapperLocation); resources.addAll(Arrays.asList(mappers)); } catch (IOException ignored) { } } return resources.toArray(new Resource[0]); } @Bean public MapperScannerConfigurer mapperScannerConfigurer() { MapperScannerConfigurer msc = new MapperScannerConfigurer(); msc.setBasePackage("cn.webrx.wxs.mapper"); msc.setSqlSessionFactoryBeanName("sf"); return msc; } }

最新整合配置类代码

/*
 * Copyright (c) 2006, 2021, webrx.cn All rights reserved.
 *
 */
package cn.webrx.config;

import com.alibaba.druid.pool.DruidDataSource;
import com.github.pagehelper.PageInterceptor;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.core.env.Environment;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;

import java.io.IOException;
import java.util.Properties;

/**
 * 

Project: spring2021 - AppConfig *

Powered by webrx On 2021-11-02 20:35:13 *

Created by IntelliJ IDEA * * @author webrx [[email protected]] * @version 1.0 * @since 17 */ @Configuration @PropertySource("db.properties") @MapperScan(basePackages = "cn.webrx.mapper", sqlSessionFactoryRef = "sf") @ComponentScan(basePackages = {"cn.webrx.mapper", "cn.webrx.pojo"}) public class AppConfig { @Value("${db.url}") private String url; //读取外配置文件方法一 @Value("${db.username}") private String username; //读取外配置文件方法二 @Autowired private Environment env; @Bean(name = "ds", initMethod = "init", destroyMethod = "close") public DruidDataSource dataSource() { var ds = new DruidDataSource(); ds.setUrl(url); ds.setUsername(username); ds.setDriverClassName(env.getProperty("db.driver", "com.mysql.cj.jdbc.Driver")); return ds; } @Bean public SqlSessionFactoryBean sf(DruidDataSource ds) { var sf = new SqlSessionFactoryBean(); //设置数据连接池 sf.setDataSource(ds); //批量加载XxxMapper.xml映射文件 var resolver = new PathMatchingResourcePatternResolver(); try { sf.setMapperLocations(resolver.getResources("mapper/*Mapper.xml")); } catch (IOException ignored) { } //设置别名 sf.setTypeAliasesPackage("cn.webrx.pojo,cn.webrx.vo"); //注册分页插件 var pi = new PageInterceptor(); var prop = new Properties(); prop.setProperty("reasonable", "true"); pi.setProperties(prop); sf.setPlugins(pi); return sf; } }

测试类:

/*
 * Copyright (c) 2006, 2021, webrx.cn All rights reserved.
 *
 */
package cn;

import cn.webrx.config.AppConfig;
import cn.webrx.mapper.BookMapper;
import cn.webrx.mapper.DbMapper;
import cn.webrx.pojo.Book;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.ApplicationContext;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

import java.util.List;

/**
 * 

Project: spring2021 - Demo *

Powered by webrx On 2021-11-02 20:34:28 *

Created by IntelliJ IDEA * * @author webrx [[email protected]] * @version 1.0 * @since 17 */ @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(classes = AppConfig.class) public class Demo { @Autowired private ApplicationContext ctx; @Autowired private DbMapper dm; @Autowired private BookMapper bm; @Test public void t3(){ //未分页 //System.out.println(bm.queryAll()); System.out.println(bm.tbs()); //使用分页 int currpage = 0; int pagesize = 5; PageHelper.startPage(currpage,pagesize); var pi = PageInfo.of(bm.tbs()); for(String book : pi.getList()){ System.out.println(book); } currpage = pi.getPageNum(); int pagecount = pi.getPages(); pagesize = pi.getPageSize(); long recordcount = pi.getTotal(); String pinfo = String.format("第%d页,共%d页 每页%d条,共%d条",currpage,pagecount,pagesize,recordcount); System.out.println(pinfo); } @Test public void t2(){ //System.out.println(dm.tbs()); //System.out.println(dm.dbs()); System.out.println(bm.queryAll()); System.out.println(bm.query()); } @Test public void t1(){ for(String s : ctx.getBeanDefinitionNames()){ System.out.println(s); } } }

欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/langs/737124.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-04-28
下一篇 2022-04-28

发表评论

登录后才能评论

评论列表(0条)

保存