两种方式(xml+代码)构建SqlSessionFactory+完整实现
两种方式(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;}@Overridepublic String toString() {return "Admin{" +"aId=" + aId +", aAccount='" + aAccount + '\'' +", aPassword='" + aPassword + '\'' +", aRank='" + aRank + '\'' +'}';} }
View Code
dao包下的AdminDao接口
public interface AdminDao {List<Admin> listAll();Admin getById(int aId); }
View Code
service包下AdminService
public interface AdminService {List<Admin> listAll();Admin getById(int aId); }
View Code
impl包下AdminServiceImpl
public class AdminServiceImpl implements AdminService {@Overridepublic List<Admin> listAll() {return null;}@Overridepublic Admin getById(int aId) {return null;} }
View Code
一、使用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>
View Code
二、使用代码构建SqlSessionFactory
第一步:配置DataSource
有三种方式,推荐使用C3p0
/*** C3p0的连接池* @return* @throws PropertyVetoException*/@Beanpublic 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*///@Beanpublic 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*///@Beanpublic DataSource getSimpleDriverDataSource(){SimpleDriverDataSource dataSource=new SimpleDriverDataSource();return dataSource;}
View Code
第二步:配置SqlSessionFactoryBean
需要xml配置的代码:
/*** 获取SqlSessionFactoryBean** @return*/@Beanpublic SqlSessionFactoryBean getSqlSessionFactory(DataSource dataSource){SqlSessionFactoryBean sqlSessionFactoryBean=new SqlSessionFactoryBean();//注入数据库连接池 sqlSessionFactoryBean.setDataSource(dataSource);//配置MyBaties全局配置文件:mybatis-config.xmlsqlSessionFactoryBean.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;}
View Code
不需要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//构建SqlSessionFactorySqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(configuration);return sqlSessionFactory;}}
View Code
进行使用:
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);}
运行:
两种方式(xml+代码)构建SqlSessionFactory+完整实现相关推荐
- 批量插入数据库语句java_java相关:MyBatis批量插入数据到Oracle数据库中的两种方式(实例代码)...
java相关:MyBatis批量插入数据到Oracle数据库中的两种方式(实例代码) 发布于 2020-7-22| 复制链接 本文通过实例代码给大家分享了MyBatis批量插入数据到Oracle数据库 ...
- 如何将横向滚动条加粗css,css实现横向滚动条的两种方式(代码实例)
本章给大家介绍用css实现横向滚动条的两种方式.有一定的参考价值,有需要的朋友可以参考一下,希望对你有所帮助. html代码: 全部 Adobe 微软 会计 绘画 Adobe 微软 会计 绘画 一. ...
- 基于aspectj实现AOP操作的两种方式——xml配置
1. 要导入的 jar 包: 常用的aspectj表达式: 权限修饰符可以省略,以下表示:返回值类型为任意,com.chy.service包以及其子包下的.任意类的.参数任意的.任意方法 execut ...
- Xml解析常用的两种方式
Xml解析常用的两种方式 Xml解析常用的两种方式dom. DOM4J 下面我们先看一下这两种方式的优缺点: 1.DOM解析的特点是将整个xml文档以树形结构放入到内存中,是官方推荐标准,优点是在内存 ...
- VMware虚拟机直连物理网络的两种方式
VMware虚拟机直连物理网络的两种方式 使用VMware构建虚拟机,通常虚拟机都使用NAT模式.这时,虚拟机有独立的网段.使用NAT模式,虚拟机之间数据都通过虚拟网络传输,不会影响实体机所在的实体网 ...
- ajax加载vue数据,详解使用Vue.Js结合Jquery Ajax加载数据的两种方式
整理文档,搜刮出一个使用vue.js结合jquery ajax加载数据的两种方式的代码,稍微整理精简一下做下分享. 废话不多说,直接上代码 html代码 demo {{message }} 测试jqu ...
- 将Eclipse代码导入到Android Studio的两种方式
转: http://www.jcodecraeer.com/a/anzhuokaifa/androidkaifa/2015/0104/2259.html 说到使用Android Studio,除了新建 ...
- QtCreator与catkin命令两种方式开发ROS程序(图示加代码)
QtCreator与catkin命令两种方式开发ROS程序(图示加代码) 一.Qt Creator安装及开发ROS 1.安装Qt Creator 2.使用Qt Creator开发ROS 1.创建工作空 ...
- ABAP和XML数据格式互相转换的两种方式
ABAP和XML数据格式互相转换是广大开发人员经常遇到的需求.本文介绍两种方式. 1. ABAP提供了一个工具类cl_proxy_xml_transform,通过它的两个方法abap_to_xml_x ...
- iOS 通过URL网络获取XML数据的两种方式
下面简单介绍如何通过url获取xml的两种方式. 第一种方式相对简单,使用NSData的构造函数dataWithContentsOfURL:不多解释,直接上代码咯. NSURL *url = [NSU ...
最新文章
- MyBatis 框架概述
- 以获客为目标 ,首席增长官从0到1实现用户增长
- NandFlash详述
- maven添加外部jar,以及springboot打包
- 带你掌握4种Python 排序算法
- vs2012 编译cocos2d-x项目报error MSB3073
- beego mysql session_Go语言之高级篇beego框架之cookie与session
- 编程基础(一)——计算机中的数
- 员工请假审批系统 php,php073企业考勤请假系统
- qq互联登录授权php配置,开通qq互联开放平台登陆功能的步骤
- 上市商业银行手机银行App月活增长及应用对标分析
- nas存储如何做远程服务器数据备份_NAS存储与数据备份方案
- android 魔力锁屏源码,打造最炫手机锁屏桌面 10款安卓魔力锁屏主题推荐
- 键盘符号中英文名称大全
- android 动画引擎,用 Android 实现一条小金鱼游动动画(超棒)
- idea热部署插件JRebel激活(强烈推荐,试试就离不开了)
- hihocoder1081
- 【JokerのZYNQ7020】TIMER。
- coda2怎么连接mysql_Coda 2.7.7 - Web管理通用工具包
- 中序遍历解决二叉搜索树问题
热门文章
- 数据挖掘之Apriori算法详解和Python实现代码分享_python
- python+gensim︱jieba分词、词袋doc2bow、TFIDF文本挖掘
- keyup常用事件_KeyUp 事件
- php显示上一次登陆的时间长,cookie实现显示上次登录时间的问题
- C++ shared_ptr make_shared是什么意思
- kubernetes资源类型和kubectl命令总结
- 微信小程序云开发教程-WXSS入门-常用样式
- bootstrap 文字不换行
- JavaWeb学习(二)Maven
- 51单片机mysql_[学习笔记]15个QA让你快速入门51单片机开发