首先创建类、接口、数据库:

  1. entity包下Admin类:
  1. package com.wbg.springJavaConfig.entity;
  2.  
  3. public class Admin {
  4. private int aId;
  5. private String aAccount;
  6. private String aPassword;
  7. private String aRank;
  8.  
  9. public Admin(int aId, String aAccount, String aPassword, String aRank) {
  10. this.aId = aId;
  11. this.aAccount = aAccount;
  12. this.aPassword = aPassword;
  13. this.aRank = aRank;
  14. }
  15.  
  16. public int getaId() {
  17. return aId;
  18. }
  19.  
  20. public void setaId(int aId) {
  21. this.aId = aId;
  22. }
  23.  
  24. public String getaAccount() {
  25. return aAccount;
  26. }
  27.  
  28. public void setaAccount(String aAccount) {
  29. this.aAccount = aAccount;
  30. }
  31.  
  32. public String getaPassword() {
  33. return aPassword;
  34. }
  35.  
  36. public void setaPassword(String aPassword) {
  37. this.aPassword = aPassword;
  38. }
  39.  
  40. public String getaRank() {
  41. return aRank;
  42. }
  43.  
  44. public void setaRank(String aRank) {
  45. this.aRank = aRank;
  46. }
  47.  
  48. @Override
  49. public String toString() {
  50. return "Admin{" +
  51. "aId=" + aId +
  52. ", aAccount='" + aAccount + '\'' +
  53. ", aPassword='" + aPassword + '\'' +
  54. ", aRank='" + aRank + '\'' +
  55. '}';
  56. }
  57. }

 dao包下的AdminDao接口

  1. public interface AdminDao {
  2.  
  3. List<Admin> listAll();
  4. Admin getById(int aId);
  5. }

service包下AdminService

  1. public interface AdminService {
  2. List<Admin> listAll();
  3.  
  4. Admin getById(int aId);
  5. }

impl包下AdminServiceImpl

  1. public class AdminServiceImpl implements AdminService {
  2.  
  3. @Override
  4. public List<Admin> listAll() {
  5. return null;
  6. }
  7.  
  8. @Override
  9. public Admin getById(int aId) {
  10. return null;
  11. }
  12. }

一、使用xml构建SqlSessionFactory

  1. <!-- 数据库连接池 -->
  2. <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
  3. <property name="driverClass" value="org.mariadb.jdbc.Driver" />
  4. <property name="jdbcUrl" value="jdbc:mariadb://localhost:3306/wbg_logistics" />
  5. <property name="user" value="root" />
  6. <property name="password" value="123456" />
  7.  
  8. <!-- c3p0连接池的私有属性 -->
  9. <property name="maxPoolSize" value="30" />
  10. <property name="minPoolSize" value="10" />
  11. <!-- 关闭连接后不自动commit -->
  12. <property name="autoCommitOnClose" value="false" />
  13. <!-- 获取连接超时时间 -->
  14. <property name="checkoutTimeout" value="10000" />
  15. <!-- 当获取连接失败重试次数 -->
  16. <property name="acquireRetryAttempts" value="2" />
  17. </bean>
  18.  
  19. <!-- 配置SqlSessionFactory对象 -->
  20. <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
  21. <!-- 注入数据库连接池 -->
  22. <property name="dataSource" ref="dataSource" />
  23. <!-- 配置MyBaties全局配置文件:mybatis-config.xml -->
  24. <property name="configLocation" value="classpath:mybatis-config.xml" />
  25. <!-- 扫描entity包 使用别名 -->
  26. <property name="typeAliasesPackage" value="com.wbg.springJavaConfig.dao" />
  27. <!-- 扫描sql配置文件:mapper需要的xml文件 -->
  28. <property name="mapperLocations" value="classpath:mapper/*.xml" />
  29. </bean>

二、使用代码构建SqlSessionFactory

第一步:配置DataSource

有三种方式,推荐使用C3p0

  1. /**
  2. * C3p0的连接池
  3. * @return
  4. * @throws PropertyVetoException
  5. */
  6. @Bean
  7. public DataSource getC3p0DataSource() throws PropertyVetoException {
  8. ComboPooledDataSource dataSource=new ComboPooledDataSource();
  9. dataSource.setDriverClass("org.mariadb.jdbc.Driver");
  10. dataSource.setJdbcUrl("jdbc:mariadb://localhost:3306/wbg_logistics");
  11. dataSource.setUser("root");
  12. dataSource.setPassword("123456");
  13. dataSource.setMaxPoolSize(30);
  14. return dataSource;
  15. }
  16. /**
  17. * MyBatis的连接池
  18. * @return
  19. */
  20. //@Bean
  21. public DataSource getMyBatisDataSource(){
  22. //数据库连接池
  23. PooledDataSource dataSource = new PooledDataSource();
  24. //设驱动
  25. dataSource.setDriver("org.mariadb.jdbc.Driver");
  26. //用户名
  27. dataSource.setUsername("root");
  28. //密码
  29. dataSource.setPassword("123456");
  30. //数据库连接
  31. dataSource.setUrl("jdbc:mariadb://localhost:3306/wbg_logistics");
  32. dataSource.setDefaultAutoCommit(false);
  33. return dataSource;
  34. }
  35. /**
  36. * Spring自带的SimpleDriverDataSource
  37. * @return
  38. */
  39. //@Bean
  40. public DataSource getSimpleDriverDataSource(){
  41. SimpleDriverDataSource dataSource=new SimpleDriverDataSource();
  42. return dataSource;
  43. }

第二步:配置SqlSessionFactoryBean

需要xml配置的代码:

  1. /**
  2. * 获取SqlSessionFactoryBean
  3. *
  4. * @return
  5. */
  6. @Bean
  7. public SqlSessionFactoryBean getSqlSessionFactory(DataSource dataSource){
  8. SqlSessionFactoryBean sqlSessionFactoryBean=new SqlSessionFactoryBean();
  9. //注入数据库连接池
  10. sqlSessionFactoryBean.setDataSource(dataSource);
  11. //配置MyBaties全局配置文件:mybatis-config.xml
  12. sqlSessionFactoryBean.setConfigLocation(new ClassPathResource("mybatis-config.xml"));
  13. //扫描entity包 使用别名
  14. sqlSessionFactoryBean.setTypeAliasesPackage("com.wbg.springJavaConfig.dao");
  15. //扫描sql配置文件:mapper需要的xml文件
  16. sqlSessionFactoryBean.setMapperLocations(new Resource[]{new ClassPathResource("classpath:mapper/*.xml")});
  17. return sqlSessionFactoryBean;
  18. }

不需要xml的方式:

MySqlSessionFactory 类

  1. package com.wbg.springJavaConfig.Mybatis;
  2.  
  3. import com.mchange.v2.c3p0.ComboPooledDataSource;
  4. import com.wbg.springJavaConfig.dao.AdminDao;
  5. import com.wbg.springJavaConfig.entity.Admin;
  6. import org.apache.ibatis.datasource.pooled.PooledDataSource;
  7. import org.apache.ibatis.mapping.Environment;
  8. import org.apache.ibatis.session.*;
  9. import org.apache.ibatis.transaction.TransactionFactory;
  10. import org.apache.ibatis.transaction.jdbc.JdbcTransactionFactory;
  11.  
  12. import javax.sql.DataSource;
  13. import java.beans.PropertyVetoException;
  14.  
  15. public class MySqlSessionFactory {
  16.  
  17. public static SqlSession getopenSession() throws PropertyVetoException {
  18. SqlSessionFactory sqlSessionFactory=getSqlSessionFactory(getC3p0DataSource());
  19. sqlSessionFactory.openSession();
  20. SqlSession sqlSession=null;
  21. try {
  22. //打开SqlSession会话
  23. sqlSession = sqlSessionFactory.openSession();
  24. sqlSession.commit();//提交事务
  25. }catch (Exception ex){
  26. sqlSession.rollback();//回滚
  27. }
  28. return sqlSession;
  29. }
  30.  
  31. public static DataSource getC3p0DataSource() throws PropertyVetoException {
  32. ComboPooledDataSource dataSource=new ComboPooledDataSource();
  33. dataSource.setDriverClass("org.mariadb.jdbc.Driver");
  34. dataSource.setJdbcUrl("jdbc:mariadb://localhost:3306/wbg_logistics");
  35. dataSource.setUser("root");
  36. dataSource.setPassword("123456");
  37. dataSource.setMaxPoolSize(30);
  38. return dataSource;
  39. }
  40.  
  41. public static SqlSessionFactory getSqlSessionFactory(DataSource dataSource){
  42.  
  43. TransactionFactory transactionFactory = new JdbcTransactionFactory();
  44. Environment environment = new Environment("development", transactionFactory, dataSource);
  45. //创建Configuration对象
  46. org.apache.ibatis.session.Configuration configuration = new org.apache.ibatis.session.Configuration(environment);
  47. //注册一个MyBatis上下文别名
  48. configuration.getTypeAliasRegistry().registerAlias("admin", Admin.class);
  49. //加入一个映射器
  50. configuration.addMapper(AdminDao.class);
  51. //使用SqlSessionFactoryBuilder构建SqlSessionFactory
  52. //构建SqlSessionFactory
  53. SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(configuration);
  54.  
  55. return sqlSessionFactory;
  56. }
  57.  
  58. }

进行使用:

1、修改AdminDao首先使用@Select注解

  1. @Select("select * from Admin")
  2. List<Admin> listAll();

2、加入配置

  1. SqlSession sqlSession = new MySqlSessionFactory().getopenSession();
  2.  
  3. public AdminServiceImpl() throws PropertyVetoException {
  4. }
  5. public List<Admin> listAll() {
  6. AdminDao adminDao = sqlSession.getMapper(AdminDao.class);
  7. return adminDao.listAll();
  8. }

调用:

  1. AdminServiceImpl adminService = new AdminServiceImpl();
  2.  
  3. List<Admin> list=adminService.listAll();
  4. for (Admin admin : list) {
  5. System.out.println(admin);
  6. }

运行:

两种方式(xml+代码)构建SqlSessionFactory+完整实现的更多相关文章

  1. Spring IOC 依赖注入的两种方式XML和注解

    依赖注入的原理 依赖注入的方式---XML配置 依赖注入的方式---注解的方式 Spring 它的核心就是IOC和AOP.而IOC中实现Bean注入的实现方式之一就是DI(依赖注入). 一 DI的原理 ...

  2. 基于aspectj实现AOP操作的两种方式——xml配置

    1. 要导入的 jar 包: 常用的aspectj表达式: 权限修饰符可以省略,以下表示:返回值类型为任意,com.chy.service包以及其子包下的.任意类的.参数任意的.任意方法 execut ...

  3. VMware虚拟机直连物理网络的两种方式

    VMware虚拟机直连物理网络的两种方式   使用VMware构建虚拟机,通常虚拟机都使用NAT模式.这时,虚拟机有独立的网段.使用NAT模式,虚拟机之间数据都通过虚拟网络传输,不会影响实体机所在的实 ...

  4. 将Eclipse代码导入到AndroidStudio的两种方式

    版权声明: 欢迎转载,但请保留文章原始出处 作者:GavinCT 出处:http://www.cnblogs.com/ct2011/p/4183553.html 说到使用AndroidStudio,除 ...

  5. XFire构建服务端Service的两种方式(转)

    XFire构建服务端service的两种方式,一是用xfire构建,二是和spring集成构建. 一,xifre构建,确保把xfire的jar包导入到工程中或classpath. 1,service的 ...

  6. 将Eclipse代码导入到Android Studio的两种方式

    转: http://www.jcodecraeer.com/a/anzhuokaifa/androidkaifa/2015/0104/2259.html 说到使用Android Studio,除了新建 ...

  7. 转: 将Eclipse代码导入到AndroidStudio的两种方式 ,测试了方法2,成功。

    蛋疼,不知道为什么我的eclipse的logcat总是莫名其妙的显示一堆黄色字体的字,看不懂的那种,如下图: 然后查了一下资料,说可能是adt版本太低,手机系统太高. 然后本来想升级adt,但是各种折 ...

  8. 转: 将Eclipse代码导入到AndroidStudio的两种方式

    评注: 讲解的非常之详细 转自:    http://www.cnblogs.com/ct2011/p/4183553.html 说到使用AndroidStudio,除了新建的项目,我们都会面临的问题 ...

  9. 简介C#读取XML的两种方式

    简介C#读取XML的两种方式 作者: 字体:[增加 减小] 类型:转载 时间:2013-03-03 在程序中访问进而操作XML文件一般有两种模型,分别是使用DOM(文档对象模型)和流模型,使用DOM的 ...

随机推荐

  1. Oracle PL/SQL Developer 上传下载Excel

    接到需求,Oracle数据库对Excel数据进行上传和下载,百度后没有很全的方案,整理搜到的资料,以备不时之需. 一.下载Oracle数据到Excel中. 下载数据到Excel在MSSql中很简单,直 ...

  2. Java基础(七)常用类

    一.Math类 1.Math类介绍 Math类属于java.lang包下面,里面包含用于执行基本数学运算的方法,如初等指数,对数,平方根和三角函数,该类被final修饰. 常用字段: 1.E 表示自然 ...

  3. java.lang.UnsupportedClassVersionError: action/Login : Unsupported major.minor version 52.0 (unable to load class action.Login)异常

    用myeclipse新建一个web项目,用了struts2框架,tomcat启动的时候报了这个错误. 我的问题原因是tomcat7的运行环境不知道为什么设置成了myeclipse1.7的jre,我给它 ...

  4. python使用元类

    原文:https://blog.csdn.net/youzhouliu/article/details/51906158 type() 动态语言和静态语言最大的不同,就是函数和类的定义,不是编译时定义 ...

  5. jQuery源码分析系列 : 整体架构

    query这么多年了分析都写烂了,老早以前就拜读过, 不过这几年都是做移动端,一直御用zepto, 最近抽出点时间把jquery又给扫一遍 我也不会照本宣科的翻译源码,结合自己的实际经验一起拜读吧! ...

  6. $.each遍历JSON字符串和 Uncaught TypeError: Cannot use 'in' operator to search for '156错误

    现在页面和后端交互都流行使用json了  自己记录一下解析字符串的方法,要不老是忘记!!!! success: function (data) { //data是后台传过来的字符串 $.each(JS ...

  7. webpack2-webpack.config.js配置

     写在前面: 了解更多:https://github.com/miaowwwww/webpack-learn 贴一个webpack.ocnfig.js 的配置属性表 一.代码分割: 1.插件 Comm ...

  8. html 页面清浏览器缓存

    <meta http-equiv="Pragma" content="no-cache" /> <meta http-equiv=" ...

  9. classifier.cc-recv() [ns2.35]

    //without comments int chooseECNSlot() { ; ;i<=nslot_;i++) { *count) { *count); )*ti; ;j<=nslo ...

  10. 高精度定时器实现 z

    1背景Permalink .NET Framework 提供了四种定时器,然而其精度都不高(一般情况下 15ms 左右),难以满足一些场景下的需求. 在进行媒体播放.绘制动画.性能分析以及和硬件交互时 ...