[MyBatis] 通过代码配置+XML文件构建SqlSessionFactory

  • 问题描述
  • 版本说明
    • 数据库
    • 依赖
  • 相关代码
    • XML文件:
      • mybatis-config.xml
      • FbPlayerMapper.xml
    • Java代码
      • MyBatisConfigure.java
      • FbPlayerMapper.java
      • FbPlayer.java
      • App.java
    • 运行结果

问题描述

最近由于项目中的特殊需求,在构建SqlSessionFactory时,数据库连接参数需要在代码中动态获取,同时也需要在XML文件(mybatis-config.xml)中配置映射文件信息(借助XMLConfigBuilder 类读取配置)。在此作为笔记记录。示例代码的目录结构如下:

/src/main/java/**/configuration/MyBatisConfigure.java    # 构建SqlSessionFactory/mapper/FbPlayerMapper.java    # 映射接口/entity/FbPlayer.java         # 实体类/App.java                  # 测试主程序/resources/mapper/FbPlayer.xml/mybatis-config.xml

数据表为:fb_players,其数据如下:

版本说明

数据库

MariaDB:10.4.16

依赖

mybatis:3.5.6
mysql-connector-java:8.0.23

数据源为:

HikariCP:4.0.2

相关代码

XML文件:

mybatis-config.xml

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configurationPUBLIC "-//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 mapperPUBLIC "-//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();// 在代码中配置连接参数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中载入映射文件的相关信息try (InputStream is = MyBatisConfigure.class.getClassLoader().getResourceAsStream("mybatis-config.xml");InputStreamReader isr = new InputStreamReader(Objects.requireNonNull(is), StandardCharsets.UTF_8)) {// 借助XMLConfigBuilder类载入mybatis-config.xml中的相关配置XMLConfigBuilder configBuilder = new XMLConfigBuilder(isr);Configuration configuration = configBuilder.parse();// 将连接参数写入configuration中configuration.setEnvironment(environment);// 构建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!");}}
}

运行结果

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!

参考:
1、HikariCP连接示例;
2、MyBatis相关构建;
3、数据来源。

[MyBatis] 通过代码配置+XML文件构建SqlSessionFactory相关推荐

  1. spring配置xml文件_XML配置文件中的Spring配置文件

    spring配置xml文件 我的上一个博客非常简单,因为它涵盖了我从Spring 3.0.x到Spring 3.1.x的轻松升级,最后我提到可以将Spring模式升级到3.1,以利用Spring的最新 ...

  2. JAVA:Eclipse代码和xml文件的智能提示

    Eclipse代码和xml文件的智能提示 一.代码智能提示 Windows → Preferences → Java→ Editor → Content Assist 将 Auto activatio ...

  3. mybatis入门实例(xml文件配置)

    官网:mybatis – MyBatis 3 | 简介 先做实例如下: 一:数据库建表(自己有的话可以不用创建) CREATE  TABLE  USER( id INT(20)  NOT  NULL  ...

  4. 扩展Mybatis,免配XML文件自动实现增删改和随意查询

    写在前面 以前有点懒,一直没有分享技术新的的习惯,这次居然有心情写点东西分享出来. 作为一个从很老很老的jdk就开始码java代码的码农,对Mybatis却一直都是一无所知,一直固守在Hibernat ...

  5. SpringBoot+Mybatis加载Mapper.xml文件的两种方式

    前言:我们在平常工作中用到mybatis去加载Mapper.xml文件,可能mapper文件放的路径不一样,由此我们需要配置多个路径,幸运的是Mybatis支持我们配置多个不同路径.现在介绍两种方法. ...

  6. MyBatis中的Mapper.xml文件解析

    具体可以参见MyBatis中文开发文档:https://mybatis.org/mybatis-3/zh/sqlmap-xml.html 我所述的主要有常用的几个标签和属性 一.parameterTy ...

  7. AutowireCapableBeanFactory,实现不必配置xml文件,动态加载bean

    场景 今天遇见一个问题,如何能做到一个类,没有在spring的配置文件中配置,但是还能通过某种方式加载进来.通过查看一些代码,查看stackoverflow,了解了一些知识. 如果一个类并没有在app ...

  8. C#代码创建Xml文件

    扩展标记语言XML(eXtensible Markup Language),是由W3C组织制定的.做为用于替代HTML语言的一种新型的标记语言,XML内部有着很多基本标准,XML就是通过与这些相关标准 ...

  9. 随机生成游戏角色昵称(使用Excel配置XML文件)上

    在游戏开发中,基本上每一个游戏都有 随机生成游戏角色昵称的模块儿,游戏昵称这个东西是由策划来进行完成的,而策划一般情况下是不会写代码的,如果他写的不好还行,如果写好了咱们就失业了,so 咱们都是让策划 ...

最新文章

  1. python中choicebox_学习python的第四天笔记
  2. M站开发规范——By Klax
  3. Windows文件被占用解决办法
  4. 用opencv抽取视频的帧并保存为连续的图片
  5. Hadoop常见错误解析
  6. CSS3 - 清除浮动
  7. 指定rviz的点启动_好消息!武汉已经启动新冠疫苗紧急接种工作
  8. android 图片传递,如何使用包在Android活动之间传递图像(位图)?
  9. 信息安全的技术研究相关站点
  10. 文博项目-终端网口测试-软件
  11. 安卓 开源 挣钱_在开源中赚钱并享受乐趣
  12. (转)服务器控件三个ID
  13. Linux CentOS修改网卡IP/网关设置
  14. [转]Javascript 中 String.replace( ) 的妙用
  15. K-Means算法的Java实现
  16. Fragment使用简单示例
  17. Essay-One Piece海贼王每集剧情介绍
  18. 投资理财-基金基本术语概念整理
  19. 计算机必须设置默认打印机,win10系统禁止更改默认打印机设置的还原技巧
  20. xorg方式在无图形环境安装oracle,告别静默安装

热门文章

  1. jsbox 导入_JSBox脚本分享
  2. 自我管理能力提升-角色定位
  3. 七牛云:用人工智能为内容安全保驾护航
  4. 如何把微信公众号中的图文复制出来
  5. 三角函数之角度与弧度
  6. HC-SR04超声波模块
  7. HCSR04超声波传感器驱动
  8. 【C++】引用、内联函数、函数重载、函数默认参数(缺省参数)与占位参数、extern “C“ 浅析
  9. Tello无人机的使用笔记之dji-sdk/Tello-Python
  10. 【模型压缩】Channel Pruning for Accelerating Very Deep Neural Networks算法笔记