最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

MyBatis通過(guò)代碼配置+XML文件構(gòu)建SqlSessionFactory實(shí)踐

 更新時(shí)間:2026年01月25日 10:29:32   作者:gavinpanhuster  
本文介紹了在構(gòu)建SqlSessionFactory時(shí),如何在代碼中動(dòng)態(tài)獲取數(shù)據(jù)庫(kù)連接參數(shù),并在XML文件中配置映射文件信息,通過(guò)示例代碼,展示了如何在Java和XML文件中實(shí)現(xiàn)這些功能,運(yùn)行結(jié)果總結(jié)了整個(gè)過(guò)程的實(shí)現(xiàn)效果

問(wèn)題描述

最近由于項(xiàng)目中的特殊需求,在構(gòu)建SqlSessionFactory時(shí),數(shù)據(jù)庫(kù)連接參數(shù)需要在代碼中動(dòng)態(tài)獲取,同時(shí)也需要在XML文件(mybatis-config.xml)中配置映射文件信息(借助XMLConfigBuilder 類讀取配置)。在此作為筆記記錄。

示例代碼的目錄結(jié)構(gòu)如下:

/src
	/main
		/java
			/**
				/configuration
					/MyBatisConfigure.java	# 構(gòu)建SqlSessionFactory
				/mapper
					/FbPlayerMapper.java	# 映射接口
				/entity
					/FbPlayer.java			# 實(shí)體類
				/App.java					# 測(cè)試主程序
		/resources
			/mapper/FbPlayer.xml
			/mybatis-config.xml

數(shù)據(jù)表為:fb_players,其數(shù)據(jù)如下:


版本說(shuō)明

數(shù)據(jù)庫(kù)

MariaDB:10.4.16

依賴

mybatis:3.5.6
mysql-connector-java:8.0.23

數(shù)據(jù)源為:

HikariCP:4.0.2

相關(guān)代碼

XML文件

  • mybatis-config.xml
<?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>
	<settings>
        <!-- 開(kāi)啟駝峰自動(dòng)映射 -->
        <setting name="mapUnderscoreToCamelCase" value="true"/>
    </settings>
    <mappers>
        <mapper resource="mapper/FbPlayerMapper.xml"/>
    </mappers>
</configuration>
  • FbPlayerMapper.xml
<?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="com.gavin11.action.mybatis.mapper.FbPlayerMapper">
    <select id="selectCount" resultType="java.lang.Long">
        select count(1) from fb_players
    </select>

    <select id="getAllPlayers" resultType="com.gavin11.action.mybatis.entity.FbPlayer">
        select id,name,gender,age,uniform_number,height,weight,habitual_foot,team_id from fb_players
    </select>
</mapper>

Java代碼

  • MyBatisConfigure.java
import com.zaxxer.hikari.HikariConfig;
import com.zaxxer.hikari.HikariDataSource;
import org.apache.ibatis.builder.xml.XMLConfigBuilder;
import org.apache.ibatis.mapping.Environment;
import org.apache.ibatis.session.Configuration;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.apache.ibatis.transaction.TransactionFactory;
import org.apache.ibatis.transaction.jdbc.JdbcTransactionFactory;

import javax.sql.DataSource;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import java.util.Objects;

/**
 * @project ActionInMyBatis
 * @package com.gavin11.action.mybatis.configuration
 * @description: MyBatisConfigure <br>
 * @date: 2021/3/4 20:13 <br>
 * @author: Gavin <br>
 * @version: 1.0 <br>
 */
public class MyBatisConfigure {

    private static SqlSessionFactory sqlSessionFactory = null;

    private MyBatisConfigure() {}

    static {
        HikariConfig config = new HikariConfig();
        // 在代碼中配置連接參數(shù)
        config.setDriverClassName("com.mysql.cj.jdbc.Driver");
        config.setJdbcUrl("jdbc:mysql://192.168.0.101:3306/football?useUnicode=true&characterEncoding=utf8");
        config.setUsername("root");
        config.setPassword("123456");
        config.setConnectionTimeout(60000);
        config.setIdleTimeout(5000);
        config.setMaximumPoolSize(10);
        DataSource dataSource = new HikariDataSource(config);

        TransactionFactory transactionFactory = new JdbcTransactionFactory();
        Environment environment = new Environment("development", transactionFactory, dataSource);

        // 以下為從mybatis-config.xml中載入映射文件的相關(guān)信息
        try (
                InputStream is = MyBatisConfigure.class.getClassLoader().getResourceAsStream("mybatis-config.xml");
                InputStreamReader isr = new InputStreamReader(Objects.requireNonNull(is), StandardCharsets.UTF_8)
                ) {
            // 借助XMLConfigBuilder類載入mybatis-config.xml中的相關(guān)配置
            XMLConfigBuilder configBuilder = new XMLConfigBuilder(isr);
            Configuration configuration = configBuilder.parse();
            // 將連接參數(shù)寫(xiě)入configuration中
            configuration.setEnvironment(environment);

            // 構(gòu)建
            sqlSessionFactory = new SqlSessionFactoryBuilder().build(configuration);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static SqlSessionFactory getSqlSessionFactory() {
        return sqlSessionFactory;
    }
}
  • FbPlayerMapper.java
import java.util.List;

/**
 * @project ActionInMyBatis
 * @package com.gavin11.action.mybatis.mapper
 * @description: FbPlaerMapper <br>
 * @date: 2021/3/4 20:01 <br>
 * @author: Gavin <br>
 * @version: 1.0 <br>
 */
@Mapper
public interface FbPlayerMapper {

    long selectCount();

    List<FbPlayer> getAllPlayers();
}
  • FbPlayer.java
```java
import java.io.Serializable;

/**
 * @project ActionInMyBatis
 * @package com.gavin11.action.mybatis.entity
 * @description: FbPlayer <br>
 * @date: 2021/3/4 19:58 <br>
 * @author: Gavin <br>
 * @version: 1.0 <br>
 */
public class FbPlayer implements Serializable {

    private static final long serialVersionUID = 3L;
    private long id;
    private String name;
    private String gender;
    private int age;
    private int uniformNumber;
    private double height;
    private double weight;
    private String habitualFoot;
    private long teamId;
   
   // 省略getter/setter
}
  • App.java
import com.gavin11.action.mybatis.configuration.MyBatisConfigure;
import com.gavin11.action.mybatis.entity.FbPlayer;
import com.gavin11.action.mybatis.mapper.FbPlayerMapper;
import org.apache.ibatis.session.SqlSession;

import java.util.List;

/**
 * Hello world!
 *
 */
public class App 
{
    public static void main( String[] args )
    {
        try (
                SqlSession sqlSession = MyBatisConfigure.getSqlSessionFactory().openSession()
                ) {
            FbPlayerMapper mapper = sqlSession.getMapper(FbPlayerMapper.class);
            long count = mapper.selectCount();
            List<FbPlayer> allPlayers = mapper.getAllPlayers();

            System.out.printf("total: %d\n", count);

            if (allPlayers != null) {
                allPlayers.forEach(System.out::println);
            }

            System.out.println("complete!");
        }
    }
}

運(yùn)行結(jié)果

total: 28
FbPlayer{id=85, name='Antonio Rüdiger', gender='male', age=27, uniformNumber=2, height=190.0, weight=85.0, habitualFoot='right', teamId=1}
FbPlayer{id=86, name='Reece James', gender='male', age=20, uniformNumber=24, height=182.0, weight=87.0, habitualFoot='right', teamId=1}
FbPlayer{id=87, name='Benjamin Chilwell', gender='male', age=23, uniformNumber=21, height=178.0, weight=77.0, habitualFoot='left', teamId=1}
FbPlayer{id=88, name='Olivier Giroud', gender='male', age=34, uniformNumber=18, height=193.0, weight=92.0, habitualFoot='left', teamId=1}
FbPlayer{id=89, name='Kurt Zouma', gender='male', age=26, uniformNumber=15, height=190.0, weight=95.0, habitualFoot='right', teamId=1}
FbPlayer{id=90, name='Ngolo Kante', gender='male', age=29, uniformNumber=7, height=168.0, weight=71.0, habitualFoot='right', teamId=1}
FbPlayer{id=91, name='Danny Drinkwater', gender='male', age=30, uniformNumber=0, height=177.0, weight=70.0, habitualFoot='right', teamId=1}
FbPlayer{id=92, name='Abdul Rahman Baba', gender='male', age=26, uniformNumber=0, height=179.0, weight=70.0, habitualFoot='left', teamId=1}
FbPlayer{id=93, name='César Azpilicueta', gender='male', age=31, uniformNumber=28, height=178.0, weight=77.0, habitualFoot='right', teamId=1}
FbPlayer{id=94, name='Marcos Alonso', gender='male', age=29, uniformNumber=3, height=188.0, weight=85.0, habitualFoot='left', teamId=1}
FbPlayer{id=95, name='Andreas Christensen', gender='male', age=24, uniformNumber=4, height=188.0, weight=82.0, habitualFoot='right', teamId=1}
FbPlayer{id=96, name='Wilfredo Caballero', gender='male', age=39, uniformNumber=13, height=186.0, weight=83.0, habitualFoot='right', teamId=1}
FbPlayer{id=97, name='Mateo Kovacic', gender='male', age=26, uniformNumber=17, height=177.0, weight=78.0, habitualFoot='right', teamId=1}
FbPlayer{id=98, name='Fikayo Tomori', gender='male', age=22, uniformNumber=14, height=184.0, weight=75.0, habitualFoot='right', teamId=1}
FbPlayer{id=99, name='Christian Pulisic', gender='male', age=22, uniformNumber=10, height=172.0, weight=63.0, habitualFoot='right', teamId=1}
FbPlayer{id=100, name='Thiago Emiliano da S', gender='male', age=36, uniformNumber=6, height=183.0, weight=79.0, habitualFoot='right', teamId=1}
FbPlayer{id=101, name='Kai Havertz', gender='male', age=21, uniformNumber=29, height=189.0, weight=77.0, habitualFoot='left', teamId=1}
FbPlayer{id=102, name='Kepa Arrizabalaga', gender='male', age=26, uniformNumber=1, height=186.0, weight=88.0, habitualFoot='right', teamId=1}
FbPlayer{id=103, name='Jorge Luiz Frello Fi', gender='male', age=28, uniformNumber=5, height=180.0, weight=67.0, habitualFoot='right', teamId=1}
FbPlayer{id=104, name='Emerson', gender='male', age=26, uniformNumber=33, height=181.0, weight=79.0, habitualFoot='left', teamId=1}
FbPlayer{id=105, name='Timo Werner', gender='male', age=24, uniformNumber=11, height=181.0, weight=75.0, habitualFoot='right', teamId=1}
FbPlayer{id=106, name='Edouard Mendy', gender='male', age=28, uniformNumber=16, height=196.0, weight=86.0, habitualFoot='right', teamId=1}
FbPlayer{id=107, name='Mason Mount', gender='male', age=21, uniformNumber=19, height=178.0, weight=65.0, habitualFoot='right', teamId=1}
FbPlayer{id=108, name='Billy Gilmour', gender='male', age=19, uniformNumber=23, height=170.0, weight=65.0, habitualFoot='right', teamId=1}
FbPlayer{id=109, name='Callum Hudson-Odoi', gender='male', age=19, uniformNumber=20, height=177.0, weight=74.0, habitualFoot='right', teamId=1}
FbPlayer{id=110, name='Tammy Abraham', gender='male', age=23, uniformNumber=9, height=191.0, weight=81.0, habitualFoot='right', teamId=1}
FbPlayer{id=111, name='Charly Musonda Jr.', gender='male', age=24, uniformNumber=0, height=173.0, weight=0.0, habitualFoot='right', teamId=1}
FbPlayer{id=112, name='Hakim Ziyech', gender='male', age=27, uniformNumber=22, height=181.0, weight=70.0, habitualFoot='left', teamId=1}
complete!

總結(jié)

以上為個(gè)人經(jīng)驗(yàn),希望能給大家一個(gè)參考,也希望大家多多支持腳本之家。

相關(guān)文章

  • SpringBoot整合OpenClaw技能系統(tǒng)的實(shí)戰(zhàn)指南

    SpringBoot整合OpenClaw技能系統(tǒng)的實(shí)戰(zhàn)指南

    OpenClaw 雖然能直接通過(guò)聊天軟件指揮 AI 干活,但在企業(yè)場(chǎng)景里,我們總不能指望財(cái)務(wù)大姐在 Telegram 里敲命令來(lái)跑報(bào)表吧?本文教你用 SpringBoot 搭建一個(gè)企業(yè)級(jí)技能中臺(tái),把 OpenClaw 的 5700+ 技能收編進(jìn) Java 體系,需要的朋友可以參考下
    2026-03-03
  • 使用HttpClient調(diào)用接口的實(shí)例講解

    使用HttpClient調(diào)用接口的實(shí)例講解

    下面小編就為大家?guī)?lái)一篇使用HttpClient調(diào)用接口的實(shí)例講解。小編覺(jué)得挺不錯(cuò)的,現(xiàn)在就分享給大家,也給大家做個(gè)參考。一起跟隨小編過(guò)來(lái)看看吧
    2017-10-10
  • WebClient拋UnsupportedMediaTypeException異常解決

    WebClient拋UnsupportedMediaTypeException異常解決

    這篇文章主要為大家介紹了WebClient拋UnsupportedMediaTypeException異常的解決方案,文中給大家介紹了六中方案,有需要的朋友可以借鑒參考下,希望能夠有所幫助
    2022-02-02
  • jenkins+maven+svn自動(dòng)部署和發(fā)布的詳細(xì)圖文教程

    jenkins+maven+svn自動(dòng)部署和發(fā)布的詳細(xì)圖文教程

    Jenkins是一個(gè)開(kāi)源的、可擴(kuò)展的持續(xù)集成、交付、部署的基于web界面的平臺(tái)。這篇文章主要介紹了jenkins+maven+svn自動(dòng)部署和發(fā)布的詳細(xì)圖文教程,需要的朋友可以參考下
    2020-09-09
  • Java NIO實(shí)戰(zhàn)之聊天室功能詳解

    Java NIO實(shí)戰(zhàn)之聊天室功能詳解

    這篇文章主要介紹了Java NIO實(shí)戰(zhàn)之聊天室功能,結(jié)合實(shí)例形式詳細(xì)分析了java NIO聊天室具體的服務(wù)端、客戶端相關(guān)實(shí)現(xiàn)方法與操作注意事項(xiàng),需要的朋友可以參考下
    2019-11-11
  • Java中實(shí)現(xiàn)漢字生成拼音首拼和五筆碼

    Java中實(shí)現(xiàn)漢字生成拼音首拼和五筆碼

    這篇文章主要介紹了Java中實(shí)現(xiàn)漢字生成拼音首拼和五筆碼方式,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教
    2022-03-03
  • MongoDB中yaml模式配置文件實(shí)現(xiàn)方式

    MongoDB中yaml模式配置文件實(shí)現(xiàn)方式

    MongoDB 3.x版本后使用YAML格式配置文件,需要注意使用空格而非Tab鍵,配置文件涵蓋系統(tǒng)日志、數(shù)據(jù)存儲(chǔ)、進(jìn)程控制、網(wǎng)絡(luò)、安全驗(yàn)證、復(fù)制集、分片集、configsvr和mongos等各個(gè)方面
    2026-02-02
  • Java的CopyOnWriteArrayList操作詳解

    Java的CopyOnWriteArrayList操作詳解

    這篇文章主要介紹了Java的CopyOnWriteArrayList操作詳解,  CopyOnWriteArrayList是ArrayList 的一個(gè)線程安全的變體,其中所有可變操作(add、set等等)都是通過(guò)對(duì)底層數(shù)組進(jìn)行一次新的復(fù)制來(lái)實(shí)現(xiàn)的,需要的朋友可以參考下
    2023-12-12
  • java swing實(shí)現(xiàn)貪吃蛇雙人游戲

    java swing實(shí)現(xiàn)貪吃蛇雙人游戲

    這篇文章主要為大家詳細(xì)介紹了java swing實(shí)現(xiàn)貪吃蛇雙人小游戲,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下
    2021-01-01
  • Java實(shí)現(xiàn)月餅的制作、下單和售賣功能

    Java實(shí)現(xiàn)月餅的制作、下單和售賣功能

    這篇文章主要介紹了Java實(shí)現(xiàn)月餅的制作、下單和售賣,借此機(jī)會(huì),我們用Lambda實(shí)現(xiàn)一遍月餅制作,下單,售賣的開(kāi)發(fā)設(shè)計(jì)模式,主要有制作月餅的工廠模式,結(jié)合實(shí)例代碼給大家介紹的非常詳細(xì),需要的朋友可以參考下
    2022-09-09

最新評(píng)論

乐陵市| 嘉峪关市| 呼伦贝尔市| 称多县| 江永县| 绥棱县| 赤水市| 沈阳市| 延边| 乡城县| 东兴市| 铜梁县| 广南县| 凌海市| 天气| 龙门县| 景德镇市| 大名县| 漳浦县| 喀喇沁旗| 固原市| 宁阳县| 屏山县| 鄢陵县| 长葛市| 阿坝| 根河市| 大悟县| 政和县| 莲花县| 海口市| 龙州县| 合水县| 衡阳市| 吉林省| 饶阳县| 达州市| 新和县| 河源市| 色达县| 略阳县|