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

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);
}

运行:

两种方式(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. Rabbit的事务

    加入事务的方法: txSelect()  txCommit()  txRollback() 生产者: package com.kf.queueDemo.transactions; import jav ...

  2. 5、springboot之修改端口号

    在resources中加入application.properties文件,里面加入 servier.port = 端口号 访问的时候,就用localhost:端口号 完事

  3. PAT 1044. Shopping in Mars

    #include <cstdio> #include <cstdlib> #include <vector> #include <climits> #i ...

  4. html 之 position用法

    引用: position的四个属性值: 1.relative2.absolute3.fixed4.static下面分别讲述这四个属性. <div id="parent"> ...

  5. Memcache 学习笔记(一)----Memcache — Linux部署

    Memcache 一.Memcache简介(内容摘自 --百度百科) memcache是一套分布式的高速缓存系统,由LiveJournal的Brad Fitzpatrick开发,但目前被许多网站使用以 ...

  6. ArrayList的使用方法详解(转)

    1.什么是ArrayList    ArrayList就是传说中的动态数组,用MSDN中的说法,就是Array的复杂版本,它提供了如下一些好处: 动态的增加和减少元素 实现了ICollection和I ...

  7. JDBC连接数据库方法的封装,以及查询数据方法的封装

    (在上一篇文章中,我们详细的介绍了连接数据库的方法,以及eclipse操作数据库信息的相关方法,在这里我们将主要讲封装.) 主要内容: 一般的连接数据库测试 把连接数据库的方法封装成一个类和测试 一个 ...

  8. web安全-XSS

    了解XSS的定义 跨站脚本攻击(Cross Site Scripting),为了不和层叠样式表(Cascading Style Sheets, CSS)的缩写混淆,故将跨站脚本攻击缩写为XSS.恶意攻 ...

  9. arm汇编学习(五)

    新增个手写GNU语法arm的方法,以后可以狂逆狂写 hello.S文件 .data msg: .ascii "Hello, ARM!\n" len = . - msg .text ...

  10. 鲁棒图(Robustness Diagram)

    鲁棒图与系统需求分析 鲁棒图(Robustness Diagram)是由Ivar Jacobson于1991年发明的,用以回答“每个用例需要哪些对象”的问题.后来的UML并没有将鲁棒图列入UML标准, ...