MyBatis通過代碼配置+XML文件構(gòu)建SqlSessionFactory實踐
更新時間:2026年01月25日 10:29:32 作者:gavinpanhuster
本文介紹了在構(gòu)建SqlSessionFactory時,如何在代碼中動態(tài)獲取數(shù)據(jù)庫連接參數(shù),并在XML文件中配置映射文件信息,通過示例代碼,展示了如何在Java和XML文件中實現(xiàn)這些功能,運行結(jié)果總結(jié)了整個過程的實現(xiàn)效果
問題描述
最近由于項目中的特殊需求,在構(gòu)建SqlSessionFactory時,數(shù)據(jù)庫連接參數(shù)需要在代碼中動態(tài)獲取,同時也需要在XML文件(mybatis-config.xml)中配置映射文件信息(借助XMLConfigBuilder 類讀取配置)。在此作為筆記記錄。
示例代碼的目錄結(jié)構(gòu)如下:
/src /main /java /** /configuration /MyBatisConfigure.java # 構(gòu)建SqlSessionFactory /mapper /FbPlayerMapper.java # 映射接口 /entity /FbPlayer.java # 實體類 /App.java # 測試主程序 /resources /mapper/FbPlayer.xml /mybatis-config.xml
數(shù)據(jù)表為:fb_players,其數(shù)據(jù)如下:

版本說明
數(shù)據(jù)庫
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>
<!-- 開啟駝峰自動映射 -->
<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ù)寫入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!");
}
}
}
運行結(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é)
以上為個人經(jīng)驗,希望能給大家一個參考,也希望大家多多支持腳本之家。
您可能感興趣的文章:
- 使用Mybatis時SqlSessionFactory對象總是報空指針
- MyBatis-plus報錯Property ‘sqlSessionFactory‘ or ‘sqlSessionTemplate‘ are required的解決方法
- Mybatis中自定義實例化SqlSessionFactoryBean問題
- 詳解Mybatis核心類SqlSessionFactory的構(gòu)建
- SpringBoot3整合MyBatis出現(xiàn)異常:Property?'sqlSessionFactory'or?'sqlSessionTemplate'?are?required
- Mybatis SqlSessionFactory與SqlSession詳細講解
- 使用Mybatis-Plus時的SqlSessionFactory問題及處理
相關(guān)文章
java中synchronized Lock(本地同步)鎖的8種情況
本文主要介紹了java中synchronized Lock(本地同步)鎖的8種情況,文中通過示例代碼介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們可以參考一下2021-09-09
HTTP?與?SpringBoot?參數(shù)提交與接收協(xié)議方式
HTTP參數(shù)提交方式包括URL查詢、表單、JSON/XML、路徑變量、頭部、Cookie、GraphQL、WebSocket和SSE,依據(jù)請求方法和Content-Type差異,SpringBoot通過特定注解如@RequestParam、@RequestBody實現(xiàn)數(shù)據(jù)獲取,本文介紹HTTP與SpringBoot參數(shù)提交與接收協(xié)議方式,感興趣的一起看看2025-07-07

