好得很程序员自学网

<tfoot draggable='sEl'></tfoot>

SpringBoot Mybatis 配置文件形式详解

开发环境: IDEA 2022.1.4+ Mybatis

1. 概述

        在之前BiliBili学习SprintBoot时候,按照视频敲代码,SpringBoot集成MyBatis,是单独写了一个mybatis-config.xml文件。配置数据连接以及mapper等信息。后来问了下从事Java得同事,告知mybatis-config.xml文件其实可以写到application.yml。当时也没弄清楚。后来摸索中,也就渐渐明白了。

2. 单独配置mybatis-config.xml

2.1 配置内容

        当时视频学习,也写下学习得总结。

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
<? 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核心配置文件-->
<!--顺序 properties->settings->typeAliases->typeHandlers->objectFactory->objectWrapperFactory->reflectorFactory->plugins->environments->databaseIdProvider->mappers-->
< configuration >
     <!--jdbc.properties配置文件-->
     < properties resource = "jdbc.properties" ></ properties >
 
     <!--设置mybatis输出日志 Mybatis默认就是STDOUT_LOGGING-->
     < settings >
         < setting name = "logImpl" value = "STDOUT_LOGGING" />
     </ settings >
 
     <!--  类型别名 默认为类名 指定这个后 mapper的xml文件指定返回值时候 可直接写类名(不区分大小写) 建议直接拷贝类名  -->
     < typeAliases >
         < package name = "com.ceaning.crudp.entity" />
     </ typeAliases >
 
     <!-- 环境配置 -->
     <!-- development IDEA默认 开发环境 -->
     <!-- 可以自定义 比如定义test formal 看心情 每个SqlSessionFactory实例只能选择一种环境 这个可随时配置 -->
     <!-- test 测试环境 -->
     <!-- formal 正式环境 -->
     < environments default = "development" >
         < environment id = "development" >
             < transactionManager type = "JDBC" />
             < dataSource type = "POOLED" >
                 < property name = "driver" value = "${driver}" />
                 < property name = "url" value = "${url}" />
                 < property name = "username" value = "${username}" />
                 < property name = "password" value = "${password}" />
             </ dataSource >
         </ environment >
     </ environments >
     <!-- 映射器 每一个mapper.xml都需要在Mybatis的核心文件中注册! -->
     <!-- 注册方式1 使用xml文件 <mapper resource="com/ceaning/efmis/mapper/UserMapper.xml"/> -->
     <!-- 注册方式2 使用class文件 <mapper class="com.ceaning.efmis.mapper.UserMapper"/> -->
     <!-- 注册方式3 mapper代理方式 <package name="com.ceaning.efmis.mapper"/> -->
     <!--
         注册方式2(使用class文件)和注册方式3(使用包扫描注册)
         1.接口和他的Mapper配置文件必须同名
         2.接口和他的Mapper配置文件必须在同一个包下
     -->
     < mappers >
         < package name = "com.ceaning.crudp.mapper" />
     </ mappers >
</ configuration >

        jdbc.properties内容如下:

        单独写jdbc得配置,是担心以后要是部署成WAR形式,修改mybatis-config.xml内容得话,内容太多,防止修改错,就单独搞个jdbc配置。(其实我想多了)

?
1
2
3
4
driver=com.microsoft.sqlserver.jdbc.SQLServerDriver
url=jdbc:sqlserver://127.0.0.1:1433;databaseName=EFMIS
username=sa
password=123qwe,.

2.2 辅助类

        辅助类得作用在于初始调用类得时候,实现配置加载,并创建SqlSessionFactory,方便后面进行SQL查询。

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
public class MybatisUtils {
     //SqlSessionFactory 静态单例模式
     private static SqlSessionFactory sqlSessionFactory;
 
     //使用Mybatis第一步 获取SqlSessionFactory对象
     static {
         try {
             String resource= "mybatis-config.xml" ;
             InputStream inputStream= Resources.getResourceAsStream(resource);
             sqlSessionFactory= new SqlSessionFactoryBuilder().build(inputStream);
         } catch (Exception e){
             e.printStackTrace();
         }
     }
 
     //获取SqlSession实例
     //该实例包含了面向数据库执行sql命令所需要的所有方法
     public static SqlSession getSqlSession(){
         return sqlSessionFactory.openSession();
     }
}

2.3 调用操作

        此处我以登录操作为例。这样就可以连接数据库进行操作。

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
@PostMapping ( "/user/login" )
     public Result<?> login( @RequestBody User user){
         SqlSession sqlSession= null ;
         Map<String, Object> map= new HashMap<>();
         try {
             sqlSession= MybatisUtils.getSqlSession();
             UserMapper mapper= sqlSession.getMapper(UserMapper. class );
             user= mapper.login(user);
             if (user!= null ){
                 //生成token
                 Map<String, String> tokenmap= new HashMap<>();
                 tokenmap.put( "loginname" , user.getLoginname());
                 tokenmap.put( "password" , user.getPassword());
                 String token= JwtUtils.getToken(tokenmap);
                 //返回数据
                 map.put( "user" , user);
                 map.put( "token" , token);
                 return Result.ok(map);
             } else {
                 return Result.error(CommonConstant.SYS_ERR_CODE, "用户不存在!" );
             }
         } catch (Exception e){
             e.printStackTrace();
             return Result.error( "异常!" + e.getMessage());
         } finally {
             if (sqlSession!= null ){
                 sqlSession.close();
             }
         }
     }

3. application.yml配置mybatis

3.1 配置内容

        多余得内容不用管它。主要是配置数据源spring.datasource。配置数据库连接信息。

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
Server:
   port: 8090
 
spring:
   # quartz定时任务配置
   quartz:
     # 数据库存储方式
     job-store-type: jdbc
     org:
       quartz:
         jobStore:
           class: org.springframework.scheduling.quartz.LocalDataSourceJobStore
   #配置数据源
   datasource:
     url: jdbc:sqlserver://127.0.0.1:1433;SelectMethod=cursor;databaseName=EFMIS
     username: sa
     password: 123qwe,.
     driver-class-name: com.microsoft.sqlserver.jdbc.SQLServerDriver
   #json
   jackson:
     date-format: yyyy-MM-dd HH:mm:ss
     time-zone: GMT+8
   #热部署
   devtools:
     restart:
       enabled: true
       additional-paths: src/main/java
       exclude: static/**
   jta:
     atomikos:
       properties:
         recovery:
           forget-orphaned-log-entries-delay:
mybatis:
   configuration:
     #开启驼峰映射
     map-underscore-to-camel-case: true
     #开启缓存
     cache-enabled: true
   #加载mapper.xml文件
   mapper-locations: classpath:com/ceaning/crudp/mapper/*.xml
   #别名扫描
   type-aliases-package: com.ceaning.crudp.entity
logging:
   config: classpath:logback-spring.xml

3.2 辅助类

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
@Component
public class SpringUtils implements BeanFactoryPostProcessor {
     /**
      * Spring应用上下文环境
      */
     private static ConfigurableListableBeanFactory beanFactory;
 
 
     @Override
     public void postProcessBeanFactory(ConfigurableListableBeanFactory configurableListableBeanFactory) throws BeansException {
         SpringUtils.beanFactory= configurableListableBeanFactory;
     }
 
     public static <T> T getBean(String name) throws BeansException{
         name= lowerCaseInit(name);
         if (containsBean(name)){
             return (T) beanFactory.getBean(name);
         } else {
             return null ;
         }
     }
 
     /**
      * 获取
      * @param cls
      * @return
      * @param <T>
      * @throws BeansException
      */
     public static <T> T getBean(Class<T> cls) throws BeansException{
         T result= (T) beanFactory.getBean(cls);
         return result;
     }
 
     /**
      * 判断 BeanFactory是否包含bean对象
      * @param name
      * @return
      */
     public static boolean containsBean(String name){
         return beanFactory.containsBean(name);
     }
 
     /**
      * 判断以给定名字注册的bean定义是一个singleton还是一个prototype。
      * 如果与给定名字相应的bean定义没有被找到,将会抛出一个异常(NoSuchBeanDefinitionException)
      * @param name
      * @return
      * @throws NoSuchBeanDefinitionException
      */
     public static boolean isSingleton(String name) throws NoSuchBeanDefinitionException{
         return beanFactory.isSingleton(name);
     }
 
     public static Class<?> getType(String name) throws NoSuchBeanDefinitionException{
         return beanFactory.getType(name);
     }
 
     public static String[] getAliases(String name) throws NoSuchBeanDefinitionException{
         return beanFactory.getAliases(name);
     }
 
     /**
      * 首字母小写
      * @param name
      * @return
      */
     private static String lowerCaseInit(String name){
         if (name.length()> 0 ){
             char c= name.charAt( 0 );
             if (c>= 65 && c<= 90 ){
                 int i= c+ 32 ;
                 return (( char )i)+ name.substring( 1 );
             } else {
                 return name;
             }
         } else {
             return null ;
         }
     }
}

3.3 调用操作

        此处还是以登录操作为例。同样可以进行数据库连接操作。

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
@PostMapping ( "/user/login" )
     public Result<?> login( @RequestBody User user){
         Map<String, Object> map= new HashMap<>();
         try {
             UserMapper mapper= SpringUtils.getBean(UserMapper. class );
             user= mapper.login(user);
             if (user!= null ){
                 //生成token
                 Map<String, String> tokenmap= new HashMap<>();
                 tokenmap.put( "loginname" , user.getLoginname());
                 tokenmap.put( "password" , user.getPassword());
                 String token= JwtUtils.getToken(tokenmap);
                 //返回数据
                 map.put( "user" , user);
                 map.put( "token" , token);
                 return Result.ok(map);
             } else {
                 return Result.error(CommonConstant.SYS_ERR_CODE, "用户不存在!" );
             }
         } catch (Exception e){
             e.printStackTrace();
             return Result.error( "异常!" + e.getMessage());
         }
     }

4. 结语

        实际项目中单独配置mybatis-config.xml较少。一般都写在application.yml里。

        后面继续学习druid得配置以及操作实现。

到此这篇关于SpringBoot Mybatis 配置文件形式的文章就介绍到这了,更多相关SpringBoot Mybatis 配置内容请搜索以前的文章或继续浏览下面的相关文章希望大家以后多多支持!

原文链接:https://blog.csdn.net/ceaningking/article/details/129718773

查看更多关于SpringBoot Mybatis 配置文件形式详解的详细内容...

  阅读:17次