溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點(diǎn)擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

SpringBoot?Mybatis怎么配置文件

發(fā)布時間:2023-03-23 14:00:30 來源:億速云 閱讀:125 作者:iii 欄目:開發(fā)技術(shù)

這篇文章主要介紹“SpringBoot Mybatis怎么配置文件”,在日常操作中,相信很多人在SpringBoot Mybatis怎么配置文件問題上存在疑惑,小編查閱了各式資料,整理出簡單好用的操作方法,希望對大家解答”SpringBoot Mybatis怎么配置文件”的疑惑有所幫助!接下來,請跟著小編一起來學(xué)習(xí)吧!

    開發(fā)環(huán)境: IDEA 2022.1.4+ Mybatis

    1. 概述

            在之前BiliBili學(xué)習(xí)SprintBoot時候,按照視頻敲代碼,SpringBoot集成MyBatis,是單獨(dú)寫了一個mybatis-config.xml文件。配置數(shù)據(jù)連接以及mapper等信息。后來問了下從事Java得同事,告知mybatis-config.xml文件其實(shí)可以寫到application.yml。當(dāng)時也沒弄清楚。后來摸索中,也就漸漸明白了。

    2. 單獨(dú)配置mybatis-config.xml

    2.1 配置內(nèi)容

            當(dāng)時視頻學(xué)習(xí),也寫下學(xué)習(xí)得總結(jié)。

    <?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>
     
        <!--設(shè)置mybatis輸出日志 Mybatis默認(rèn)就是STDOUT_LOGGING-->
        <settings>
            <setting name="logImpl" value="STDOUT_LOGGING"/>
        </settings>
     
        <!--  類型別名 默認(rèn)為類名 指定這個后 mapper的xml文件指定返回值時候 可直接寫類名(不區(qū)分大小寫) 建議直接拷貝類名  -->
        <typeAliases>
            <package name="com.ceaning.crudp.entity"/>
        </typeAliases>
     
        <!-- 環(huán)境配置 -->
        <!-- development IDEA默認(rèn) 開發(fā)環(huán)境 -->
        <!-- 可以自定義 比如定義test formal 看心情 每個SqlSessionFactory實(shí)例只能選擇一種環(huán)境 這個可隨時配置 -->
        <!-- test 測試環(huán)境 -->
        <!-- formal 正式環(huán)境 -->
        <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內(nèi)容如下:

            單獨(dú)寫jdbc得配置,是擔(dān)心以后要是部署成WAR形式,修改mybatis-config.xml內(nèi)容得話,內(nèi)容太多,防止修改錯,就單獨(dú)搞個jdbc配置。(其實(shí)我想多了)

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

    2.2 輔助類

            輔助類得作用在于初始調(diào)用類得時候,實(shí)現(xiàn)配置加載,并創(chuàng)建SqlSessionFactory,方便后面進(jìn)行SQL查詢。

    public class MybatisUtils {
        //SqlSessionFactory 靜態(tài)單例模式
        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實(shí)例
        //該實(shí)例包含了面向數(shù)據(jù)庫執(zhí)行sql命令所需要的所有方法
        public static SqlSession getSqlSession(){
            return sqlSessionFactory.openSession();
        }
    }

    2.3 調(diào)用操作

            此處我以登錄操作為例。這樣就可以連接數(shù)據(jù)庫進(jìn)行操作。

    @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);
                    //返回數(shù)據(jù)
                    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 配置內(nèi)容

            多余得內(nèi)容不用管它。主要是配置數(shù)據(jù)源spring.datasource。配置數(shù)據(jù)庫連接信息。

     Server:
      port: 8090
     
    spring:
      # quartz定時任務(wù)配置
      quartz:
        # 數(shù)據(jù)庫存儲方式
        job-store-type: jdbc
        org:
          quartz:
            jobStore:
              class: org.springframework.scheduling.quartz.LocalDataSourceJobStore
      #配置數(shù)據(jù)源
      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 輔助類

    @Component
    public class SpringUtils implements BeanFactoryPostProcessor {
        /**
         * Spring應(yīng)用上下文環(huán)境
         */
        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。
         * 如果與給定名字相應(yīng)的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 調(diào)用操作

            此處還是以登錄操作為例。同樣可以進(jìn)行數(shù)據(jù)庫連接操作。

    @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);
                    //返回數(shù)據(jù)
                    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());
            } 
        }

    到此,關(guān)于“SpringBoot Mybatis怎么配置文件”的學(xué)習(xí)就結(jié)束了,希望能夠解決大家的疑惑。理論與實(shí)踐的搭配能更好的幫助大家學(xué)習(xí),快去試試吧!若想繼續(xù)學(xué)習(xí)更多相關(guān)知識,請繼續(xù)關(guān)注億速云網(wǎng)站,小編會繼續(xù)努力為大家?guī)砀鄬?shí)用的文章!

    向AI問一下細(xì)節(jié)

    免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報,并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

    AI