优点:
- 不用每次实例化SqlSession
- 配置优于硬编码
- 减少sql书写错误的概率
- 规范代码,面向接口服务
文章目录
- 一、回顾
- 二、如何通过接口操作MyBatis
- 2.1. 文件结构
- 2.2. 依赖jar包
- 2.3. 表结构
- 2.4. mybatis配置文件
- 2.5. db配置文件
- 2.6. 获取SqlSession工具类
- 2.7. 基础常量类
- 2.8. 增删改查案例
- 2.9. 基础文件
- 2.10. 源码地址
一、回顾
为什么要通过接口操作MyBatis?
在以往的情况下,我们通过MyBatis操作数据库,每执行一条SQL语句就要实例化一个SqlSession,并且要调用相应的SQL映射文件信息。比如:
String statement = "com.gblfy.datatrans.mapper.HeroMapper.selectHeroList";
操作有点麻烦,所以我们采用接口的形式,通过约定,进行更为简单的操作。
有一句话特别重要:约定优于配置,配置优于硬编码
。
二、如何通过接口操作MyBatis
2.1. 文件结构
2.2. 依赖jar包
mybatis-3.5.6.jar
mysql-connector-java-5.1.45.jar
ojdbc6.jar
2.3. 表结构
oracle 初始化表结构
-- CREATE TABLE
DROP TABLE HERO;
CREATE TABLE HERO
(
SNO VARCHAR2(20) NOT NULL,
USER_NAME VARCHAR2(20),
AGE NUMBER(3),
PRIMARY KEY (SNO)
);--COMMENT EXPLAIN 字段说明
COMMENT ON TABLE HERO IS '英雄信息表';
COMMENT ON COLUMN HERO.SNO IS '英雄编码';
COMMENT ON COLUMN HERO.USER_NAME IS '英雄名称';
COMMENT ON COLUMN HERO.AGE IS '英雄年龄';insert into HERO (SNO, USER_NAME, AGE) values ('1', '盖伦', '1');
insert into HERO (SNO, USER_NAME, AGE) values ('2', '小丑', '1');
insert into HERO (SNO, USER_NAME, AGE) values ('3', '莫甘娜', '1');
insert into HERO (SNO, USER_NAME, AGE) values ('4', '寒冰', '1');
insert into HERO (SNO, USER_NAME, AGE) values ('5', '剑圣', '5');
insert into HERO (SNO, USER_NAME, AGE) values ('6', '剑圣', '1');
mysql 初始化表结构
DROP TABLE hero;
CREATE TABLE `hero` (`sno` bigint(20) not null comment '英雄编码',`user_name` varchar(50) NOT NULL COMMENT '英雄名称',`age` varchar(3) COLLATE utf8_bin NOT NULL COMMENT '英雄年龄',PRIMARY KEY (`sno`) USING BTREE
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_bin ROW_FORMAT=DYNAMIC COMMENT='英雄信息表';insert into fis_hero (SNO, USER_NAME, AGE) values ('1', '盖伦', '1');
insert into fis_hero (SNO, USER_NAME, AGE) values ('2', '小丑', '1');
insert into fis_hero (SNO, USER_NAME, AGE) values ('3', '莫甘娜', '1');
insert into fis_hero (SNO, USER_NAME, AGE) values ('4', '寒冰', '1');
insert into fis_hero (SNO, USER_NAME, AGE) values ('5', '剑圣', '5');
insert into fis_hero (SNO, USER_NAME, AGE) values ('6', '剑圣', '1');
2.4. mybatis配置文件
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configurationPUBLIC "-//mybatis.org//DTD Config 3.0//EN""http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration><!--引入外部properties文件 --><properties resource="com/gblfy/datatrans/conf/db.properties"></properties><!--和Spring整合后 environments 配置将废除 --><environments default="development"><environment id="development"><!--使用JDBC事务管理 --><transactionManager type="JDBC"/><!--数据库连接池 --><dataSource type="POOLED"><property name="driver" value="${jdbc.driverClass}"/><property name="url" value="${jdbc.url}"/><property name="username" value="${jdbc.username}"/><property name="password" value="${jdbc.password}"/></dataSource></environment></environments><!--加载xml文件 --><mappers><mapper resource="com/gblfy/datatrans/mapper/mapping/HeroMapper.xml"/></mappers>
</configuration>
2.5. db配置文件
#Oracle 数据库驱动
jdbc.driverClass=oracle.jdbc.driver.OracleDriver
jdbc.url=jdbc:oracle:thin:@IP地址:端口:数据库名称
jdbc.username=用户名
jdbc.password=密码##Mysql数据库驱动 <= 5.x版本
#jdbc.driverClass=com.mysql.jdbc.Driver
#jdbc.url=jdbc:mysql://IP地址:端口/数据库名称?autoReconnect=true&useUnicode=true&characterEncoding=utf8&zeroDateTimeBehavior=CONVERT_TO_NULL&useSSL=false&serverTimezone=CTT
#jdbc.username=用户名
#jdbc.password=密码
#
##Mysql数据库驱动 6.x及以上版本
#jdbc.driverClass=com.mysql.cj.jdbc.Driver
#jdbc.url=jdbc:mysql://IP地址:端口/数据库名称?autoReconnect=true&useUnicode=true&characterEncoding=utf8&zeroDateTimeBehavior=CONVERT_TO_NULL&useSSL=false&serverTimezone=CTT
#jdbc.username=用户名
#jdbc.password=密码
2.6. 获取SqlSession工具类
package com.gblfy.datatrans.util;import com.gblfy.datatrans.consts.BaseConst;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;import java.io.IOException;
import java.io.InputStream;/*** 获取SqlSession** @author gblfy* @date 2020-12-18*/
public class SqlSessionUtils {/*** 获取SqlSession** @return* @throws IOException*/public static SqlSession getSqlSession() throws IOException {//mybatis的配置文件String resource = BaseConst.MYBATIS_CONF;//使用类加载器加载mybatis的配置文件(它也加载关联的映射文件)InputStream is = Resources.getResourceAsStream(resource);//构建sqlSession的工厂SqlSessionFactory sessionFactory = new SqlSessionFactoryBuilder().build(is);return sessionFactory.openSession();}
}
2.7. 基础常量类
package com.gblfy.datatrans.consts;/*** 获取SqlSession** @author gblfy* @date 2020-12-18*/
public class BaseConst {public static final String MYBATIS_CONF = "com/gblfy/datatrans/conf/mybatis-conf.xml";
}
2.8. 增删改查案例
package com.gblfy.datatrans.controller;import com.gblfy.datatrans.mapper.HeroMapper;
import com.gblfy.datatrans.pojo.Hero;
import com.gblfy.datatrans.pojo.HeroExample;
import com.gblfy.datatrans.util.SqlSessionUtils;
import org.apache.ibatis.session.SqlSession;import java.io.IOException;
import java.util.List;/*** @author gblfy* @ClassNme test* @Description TODO* @Date 2020/12/16 14:41* @version1.0*/
public class TestMybatis {// 测试mybatis数据库public static void main(String[] args) throws IOException {TestMybatis m = new TestMybatis();//1.添加新英雄// FisHero hero = new FisHero();// hero.setSno("3");// hero.setUserName("剑圣");// hero.setAge((short) 1);// m.addHero(hero);// //2.查询英雄列表 支持多条件查询m.selectHeroList();// FisHero hero2 = new FisHero();// hero2.setUserName("剑圣");// m.selectHeroListByname(hero2);////3.查询英雄编码查询指定英雄信息// String sno = "1";// m.selectHeroBySno(sno);////4.更新英雄信息// FisHero hero3 = new FisHero();// hero3.setSno("1");// hero3.setUserName("雨昕2");// hero3.setAge((short) 1);// m.updateHero(hero3);//////5.删除指定英雄信息// String sno = "1";// m.deleteHeroBySno(sno);}/*** 查询英雄列表*/public void selectHeroList() {SqlSession session = null;try {session = SqlSessionUtils.getSqlSession();HeroMapper heroMapper = session.getMapper(HeroMapper.class);List<Hero> heroList = heroMapper.selectByExample(null);for (Hero hero : heroList) {System.out.println("英雄列表:" + hero);}session.commit();//提交事务} catch (IOException e) {e.printStackTrace();session.rollback();} finally {session.close();}}/*** 根据英雄名称查询英雄列表** @param hero*/public void selectHeroListByname(Hero hero) {SqlSession session = null;try {session = SqlSessionUtils.getSqlSession();HeroMapper heroMapper = session.getMapper(HeroMapper.class);HeroExample example = new HeroExample();HeroExample.Criteria cri = example.createCriteria();if (!"".equals(hero.getUserName())) {cri.andUserNameEqualTo(hero.getUserName());}List<Hero> heroList = heroMapper.selectByExample(example);for (Hero fisHero : heroList) {System.out.println(fisHero);}session.commit();//提交事务} catch (IOException e) {e.printStackTrace();session.rollback();} finally {session.close();}}/*** 删除指定英雄信息** @param hero*/public void addHero(Hero hero) {SqlSession session = null;try {session = SqlSessionUtils.getSqlSession();HeroMapper heroMapper = session.getMapper(HeroMapper.class);int i = heroMapper.insertSelective(hero);if (i == 1) {System.out.println("添加英雄信息成功!");}session.commit();//提交事务} catch (IOException e) {e.printStackTrace();session.rollback();} finally {session.close();}}/*** 查询英雄编码查询指定英雄信息** @param sno*/public void selectHeroBySno(String sno) {SqlSession session = null;try {session = SqlSessionUtils.getSqlSession();HeroMapper heroMapper = session.getMapper(HeroMapper.class);Hero hero = heroMapper.selectByPrimaryKey(sno);System.out.println("查询到的英雄信息:" + hero);session.commit();//提交事务} catch (IOException e) {e.printStackTrace();session.rollback();} finally {session.close();}}/*** 添加新英雄** @param hero*/public void updateHero(Hero hero) {SqlSession session = null;try {session = SqlSessionUtils.getSqlSession();HeroMapper heroMapper = session.getMapper(HeroMapper.class);int i = heroMapper.updateByPrimaryKeySelective(hero);if (i == 1) {System.out.println("更新英雄信息成功!");}session.commit();//提交事务} catch (IOException e) {e.printStackTrace();session.rollback();} finally {session.close();}}/*** 删除指定英雄信息** @param sno*/public void deleteHeroBySno(String sno) {SqlSession session = null;try {session = SqlSessionUtils.getSqlSession();HeroMapper heroMapper = session.getMapper(HeroMapper.class);int i = heroMapper.deleteByPrimaryKey(sno);if (i == 1) {System.out.println("删除英雄信息成功!");}session.commit();//提交事务} catch (IOException e) {e.printStackTrace();session.rollback();} finally {session.close();}}
}
2.9. 基础文件
以下基础文件由模板生成
企业代码生成模板:
https://gitee.com/gb_90/Oracle_Mysql_Generate
xxxMapper.java
xxxMapper.xml
实体类
2.10. 源码地址
https://gitee.com/gb_90/mybatis-web