当前位置: 代码网 > it编程>编程语言>Java > MyBatis通过代码配置+XML文件构建SqlSessionFactory实践

MyBatis通过代码配置+XML文件构建SqlSessionFactory实践

2026年01月25日 Java 我要评论
问题描述最近由于项目中的特殊需求,在构建sqlsessionfactory时,数据库连接参数需要在代码中动态获取,同时也需要在xml文件(mybatis-config.xml)中配置映射文件信息(借助

问题描述

最近由于项目中的特殊需求,在构建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 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();
        // 在代码中配置连接参数
        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!

总结

以上为个人经验,希望能给大家一个参考,也希望大家多多支持代码网。

(0)

相关文章:

版权声明:本文内容由互联网用户贡献,该文观点仅代表作者本人。本站仅提供信息存储服务,不拥有所有权,不承担相关法律责任。 如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 2386932994@qq.com 举报,一经查实将立刻删除。

发表评论

验证码:
Copyright © 2017-2026  代码网 保留所有权利. 粤ICP备2024248653号
站长QQ:2386932994 | 联系邮箱:2386932994@qq.com