两种方式(xml+代码)构建SqlSessionFactory+完整实现
首先创建类、接口、数据库:
entity包下Admin类:

package com.wbg.springJavaConfig.entity; public class Admin { private int aId; private String aAccount; private String aPassword; private String aRank; public Admin(int aId, String aAccount, String aPassword, String aRank) { this.aId = aId; this.aAccount = aAccount; this.aPassword = aPassword; this.aRank = aRank; } public int getaId() { return aId; } public void setaId(int aId) { this.aId = aId; } public String getaAccount() { return aAccount; } public void setaAccount(String aAccount) { this.aAccount = aAccount; } public String getaPassword() { return aPassword; } public void setaPassword(String aPassword) { this.aPassword = aPassword; } public String getaRank() { return aRank; } public void setaRank(String aRank) { this.aRank = aRank; } @Override public String toString() { return "Admin{" + "aId=" + aId + ", aAccount='" + aAccount + '\'' + ", aPassword='" + aPassword + '\'' + ", aRank='" + aRank + '\'' + '}'; } }
dao包下的AdminDao接口

public interface AdminDao { List<Admin> listAll(); Admin getById(int aId); }
service包下AdminService

public interface AdminService { List<Admin> listAll(); Admin getById(int aId); }
impl包下AdminServiceImpl

public class AdminServiceImpl implements AdminService { @Override public List<Admin> listAll() { return null; } @Override public Admin getById(int aId) { return null; } }
一、使用xml构建SqlSessionFactory

<!-- 数据库连接池 --> <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"> <property name="driverClass" value="org.mariadb.jdbc.Driver" /> <property name="jdbcUrl" value="jdbc:mariadb://localhost:3306/wbg_logistics" /> <property name="user" value="root" /> <property name="password" value="123456" /> <!-- c3p0连接池的私有属性 --> <property name="maxPoolSize" value="30" /> <property name="minPoolSize" value="10" /> <!-- 关闭连接后不自动commit --> <property name="autoCommitOnClose" value="false" /> <!-- 获取连接超时时间 --> <property name="checkoutTimeout" value="10000" /> <!-- 当获取连接失败重试次数 --> <property name="acquireRetryAttempts" value="2" /> </bean> <!-- 配置SqlSessionFactory对象 --> <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"> <!-- 注入数据库连接池 --> <property name="dataSource" ref="dataSource" /> <!-- 配置MyBaties全局配置文件:mybatis-config.xml --> <property name="configLocation" value="classpath:mybatis-config.xml" /> <!-- 扫描entity包 使用别名 --> <property name="typeAliasesPackage" value="com.wbg.springJavaConfig.dao" /> <!-- 扫描sql配置文件:mapper需要的xml文件 --> <property name="mapperLocations" value="classpath:mapper/*.xml" /> </bean>
二、使用代码构建SqlSessionFactory
第一步:配置DataSource
有三种方式,推荐使用C3p0

/** * C3p0的连接池 * @return * @throws PropertyVetoException */ @Bean public DataSource getC3p0DataSource() throws PropertyVetoException { ComboPooledDataSource dataSource=new ComboPooledDataSource(); dataSource.setDriverClass("org.mariadb.jdbc.Driver"); dataSource.setJdbcUrl("jdbc:mariadb://localhost:3306/wbg_logistics"); dataSource.setUser("root"); dataSource.setPassword("123456"); dataSource.setMaxPoolSize(30); return dataSource; } /** * MyBatis的连接池 * @return */ //@Bean public DataSource getMyBatisDataSource(){ //数据库连接池 PooledDataSource dataSource = new PooledDataSource(); //设驱动 dataSource.setDriver("org.mariadb.jdbc.Driver"); //用户名 dataSource.setUsername("root"); //密码 dataSource.setPassword("123456"); //数据库连接 dataSource.setUrl("jdbc:mariadb://localhost:3306/wbg_logistics"); dataSource.setDefaultAutoCommit(false); return dataSource; } /** * Spring自带的SimpleDriverDataSource * @return */ //@Bean public DataSource getSimpleDriverDataSource(){ SimpleDriverDataSource dataSource=new SimpleDriverDataSource(); return dataSource; }
第二步:配置SqlSessionFactoryBean
需要xml配置的代码:

/** * 获取SqlSessionFactoryBean * * @return */ @Bean public SqlSessionFactoryBean getSqlSessionFactory(DataSource dataSource){ SqlSessionFactoryBean sqlSessionFactoryBean=new SqlSessionFactoryBean(); //注入数据库连接池 sqlSessionFactoryBean.setDataSource(dataSource); //配置MyBaties全局配置文件:mybatis-config.xml sqlSessionFactoryBean.setConfigLocation(new ClassPathResource("mybatis-config.xml")); //扫描entity包 使用别名 sqlSessionFactoryBean.setTypeAliasesPackage("com.wbg.springJavaConfig.dao"); //扫描sql配置文件:mapper需要的xml文件 sqlSessionFactoryBean.setMapperLocations(new Resource[]{new ClassPathResource("classpath:mapper/*.xml")}); return sqlSessionFactoryBean; }
不需要xml的方式:
MySqlSessionFactory 类

package com.wbg.springJavaConfig.Mybatis; import com.mchange.v2.c3p0.ComboPooledDataSource; import com.wbg.springJavaConfig.dao.AdminDao; import com.wbg.springJavaConfig.entity.Admin; import org.apache.ibatis.datasource.pooled.PooledDataSource; import org.apache.ibatis.mapping.Environment; import org.apache.ibatis.session.*; import org.apache.ibatis.transaction.TransactionFactory; import org.apache.ibatis.transaction.jdbc.JdbcTransactionFactory; import javax.sql.DataSource; import java.beans.PropertyVetoException; public class MySqlSessionFactory { public static SqlSession getopenSession() throws PropertyVetoException { SqlSessionFactory sqlSessionFactory=getSqlSessionFactory(getC3p0DataSource()); sqlSessionFactory.openSession(); SqlSession sqlSession=null; try { //打开SqlSession会话 sqlSession = sqlSessionFactory.openSession(); sqlSession.commit();//提交事务 }catch (Exception ex){ sqlSession.rollback();//回滚 } return sqlSession; } public static DataSource getC3p0DataSource() throws PropertyVetoException { ComboPooledDataSource dataSource=new ComboPooledDataSource(); dataSource.setDriverClass("org.mariadb.jdbc.Driver"); dataSource.setJdbcUrl("jdbc:mariadb://localhost:3306/wbg_logistics"); dataSource.setUser("root"); dataSource.setPassword("123456"); dataSource.setMaxPoolSize(30); return dataSource; } public static SqlSessionFactory getSqlSessionFactory(DataSource dataSource){ TransactionFactory transactionFactory = new JdbcTransactionFactory(); Environment environment = new Environment("development", transactionFactory, dataSource); //创建Configuration对象 org.apache.ibatis.session.Configuration configuration = new org.apache.ibatis.session.Configuration(environment); //注册一个MyBatis上下文别名 configuration.getTypeAliasRegistry().registerAlias("admin", Admin.class); //加入一个映射器 configuration.addMapper(AdminDao.class); //使用SqlSessionFactoryBuilder构建SqlSessionFactory //构建SqlSessionFactory SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(configuration); return sqlSessionFactory; } }
进行使用:
1、修改AdminDao首先使用@Select注解
@Select("select * from Admin")
List<Admin> listAll();
2、加入配置
SqlSession sqlSession = new MySqlSessionFactory().getopenSession(); public AdminServiceImpl() throws PropertyVetoException { } public List<Admin> listAll() { AdminDao adminDao = sqlSession.getMapper(AdminDao.class); return adminDao.listAll(); }
调用:
AdminServiceImpl adminService = new AdminServiceImpl(); List<Admin> list=adminService.listAll(); for (Admin admin : list) { System.out.println(admin); }
运行:
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
· C#/.NET/.NET Core优秀项目和框架2025年2月简报
· 一文读懂知识蒸馏
· Manus爆火,是硬核还是营销?
· 终于写完轮子一部分:tcp代理 了,记录一下