1.配置mybatis

1.1 引入依赖

mybatis依赖

<dependency><groupId>org.mybatis</groupId><artifactId>mybatis</artifactId><version>3.5.1</version></dependency>

数据库依赖

<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.19</version>
<!--版本具体看自己主机上安装的是哪个版本的mysql-->
</dependency>

1.2配置mybatis-config.xml文件

<?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><settings><!-- goods_id ==> goodsId 驼峰命名转换 --><setting name="mapUnderscoreToCamelCase" value="true"/></settings><!--启用Pagehelper分页插件--><plugins><plugin interceptor="com.github.pagehelper.PageInterceptor"><!--设置数据库类型--><property name="helperDialect" value="mysql"/><!--分页合理化--><property name="reasonable" value="true"/></plugin></plugins><!--设置默认指向的数据库--><environments default="dev"><!--配置环境,不同的环境不同的id名字--><environment id="dev"><!-- 采用JDBC方式对数据库事务进行commit/rollback --><transactionManager type="JDBC"></transactionManager><!--采用连接池方式管理数据库连接--><!--<dataSource type="POOLED">--><dataSource type="com.imooc.mybatis.datasource.C3P0DataSourceFactory"><property name="driverClass" value="com.mysql.jdbc.Driver"/><property name="jdbcUrl" value="jdbc:mysql://localhost:3306/babytun?useUnicode=true&amp;characterEncoding=UTF-8"/><property name="user" value="root"/><property name="password" value="root"/><property name="initialPoolSize" value="5"/><property name="maxPoolSize" value="20"/><property name="minPoolSize" value="5"/><!--...--></dataSource></environment><environment id="prd"><!-- 采用JDBC方式对数据库事务进行commit/rollback --><transactionManager type="JDBC"></transactionManager><!--采用连接池方式管理数据库连接--><dataSource type="POOLED"><property name="driver" value="com.mysql.jdbc.Driver"/><property name="url" value="jdbc:mysql://192.168.1.155:3306/babytun?useUnicode=true&amp;characterEncoding=UTF-8"/><property name="username" value="root"/><property name="password" value="root"/></dataSource></environment></environments><mappers><mapper resource="mappers/goods.xml"/><mapper resource="mappers/goods_detail.xml"/></mappers>
</configuration>

1.3创建sqlSession进行增删改查

这里通过创建单元测试用例来对数据库进行增删改查的演示:

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 org.junit.Test;import java.io.IOException;
import java.io.Reader;
import java.sql.Connection;
import java.util.*;//JUNIT单元测试类
public class MyBatisTestor {/*** 初始化SqlSessionFactory* @throws IOException*/@Testpublic void testSqlSessionFactory() throws IOException {//利用Reader加载classpath下的mybatis-config.xml核心配置文件Reader reader = Resources.getResourceAsReader("mybatis-config.xml");//初始化SqlSessionFactory对象,同时解析mybatis-config.xml文件SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader);System.out.println("SessionFactory加载成功");SqlSession sqlSession = null;try {//创建SqlSession对象,SqlSession是JDBC的扩展类,用于与数据库交互sqlSession = sqlSessionFactory.openSession();//创建数据库连接(测试用)Connection connection = sqlSession.getConnection();System.out.println(connection);}catch (Exception e){e.printStackTrace();}finally {if(sqlSession != null){//如果type="POOLED",代表使用连接池,close则是将连接回收到连接池中//如果type="UNPOOLED",代表直连,close则会调用Connection.close()方法关闭连接sqlSession.close();}}}/*** MyBatisUtils使用指南* @throws Exception*/@Testpublic void testMyBatisUtils() throws Exception {SqlSession sqlSession = null;try {sqlSession = MyBatisUtils.openSession();Connection connection = sqlSession.getConnection();System.out.println(connection);}catch (Exception e){throw e;} finally {MyBatisUtils.closeSession(sqlSession);}}/*** select查询语句执行* @throws Exception*/@Testpublic void testSelectAll() throws Exception {SqlSession session = null;try{session = MyBatisUtils.openSession();List<Goods> list = session.selectList("goods.selectAll");for(Goods g : list){System.out.println(g.getTitle());}}catch (Exception e){throw e;}finally {MyBatisUtils.closeSession(session);}}/*** 传递单个SQL参数* @throws Exception*/@Testpublic void testSelectById() throws Exception {SqlSession session = null;try{session = MyBatisUtils.openSession();Goods goods = session.selectOne("goods.selectById" , 1603);System.out.println(goods.getTitle());}catch (Exception e){throw e;}finally {MyBatisUtils.closeSession(session);}}/*** 传递多个SQL参数* @throws Exception*/@Testpublic void testSelectByPriceRange() throws Exception {SqlSession session = null;try{session = MyBatisUtils.openSession();Map param = new HashMap();param.put("min",100);param.put("max" , 500);param.put("limt" , 10);List<Goods> list = session.selectList("goods.selectByPriceRange", param);for(Goods g:list){System.out.println(g.getTitle() + ":" + g.getCurrentPrice());}}catch (Exception e){throw e;}finally {MyBatisUtils.closeSession(session);}}/*** 利用Map接收关联查询结果* @throws Exception*/@Testpublic void testSelectGoodsMap() throws Exception {SqlSession session = null;try{session = MyBatisUtils.openSession();List<Map> list = session.selectList("goods.selectGoodsMap");for(Map map : list){System.out.println(map);}}catch (Exception e){throw e;}finally {MyBatisUtils.closeSession(session);}}/*** 利用ResultMap进行结果映射* @throws Exception*/@Testpublic void testSelectGoodsDTO() throws Exception {SqlSession session = null;try{session = MyBatisUtils.openSession();List<GoodsDTO> list = session.selectList("goods.selectGoodsDTO");for (GoodsDTO g : list) {System.out.println(g.getGoods().getTitle());}}catch (Exception e){throw e;}finally {MyBatisUtils.closeSession(session);}}/*** 新增数据* @throws Exception*/@Testpublic void testInsert() throws Exception {SqlSession session = null;try{session = MyBatisUtils.openSession();Goods goods = new Goods();goods.setTitle("测试商品");goods.setSubTitle("测试子标题");goods.setOriginalCost(200f);goods.setCurrentPrice(100f);goods.setDiscount(0.5f);goods.setIsFreeDelivery(1);goods.setCategoryId(43);//insert()方法返回值代表本次成功插入的记录总数int num = session.insert("goods.insert", goods);session.commit();//提交事务数据System.out.println(goods.getGoodsId());}catch (Exception e){if(session != null){session.rollback();//回滚事务}throw e;}finally {MyBatisUtils.closeSession(session);}}/*** 更新数据* @throws Exception*/@Testpublic void testUpdate() throws Exception {SqlSession session = null;try{session = MyBatisUtils.openSession();Goods goods = session.selectOne("goods.selectById", 739);goods.setTitle("更新测试商品");int num = session.update("goods.update" , goods);session.commit();//提交事务数据}catch (Exception e){if(session != null){session.rollback();//回滚事务}throw e;}finally {MyBatisUtils.closeSession(session);}}/*** 删除数据* @throws Exception*/@Testpublic void testDelete() throws Exception {SqlSession session = null;try{session = MyBatisUtils.openSession();int num = session.delete("goods.delete" , 739);session.commit();//提交事务数据}catch (Exception e){if(session != null){session.rollback();//回滚事务}throw e;}finally {MyBatisUtils.closeSession(session);}}/*** 预防SQL注入* @throws Exception*/@Testpublic void testSelectByTitle() throws Exception {SqlSession session = null;try{session = MyBatisUtils.openSession();Map param = new HashMap();/*${}原文传值select * from t_goodswhere title = '' or 1 =1 or title = '【德国】爱他美婴幼儿配方奶粉1段800g*2罐 铂金版'*//*#{}预编译select * from t_goodswhere title = "'' or 1 =1 or title = '【德国】爱他美婴幼儿配方奶粉1段800g*2罐 铂金版'"*/param.put("title","'' or 1=1 or title='【德国】爱他美婴幼儿配方奶粉1段800g*2罐 铂金版'");param.put("order" , " order by title desc");List<Goods> list = session.selectList("goods.selectByTitle", param);for(Goods g:list){System.out.println(g.getTitle() + ":" + g.getCurrentPrice());}}catch (Exception e){throw e;}finally {MyBatisUtils.closeSession(session);}}/*** 动态SQL语句* @throws Exception*/@Testpublic void testDynamicSQL() throws Exception {SqlSession session = null;try{session = MyBatisUtils.openSession();Map param = new HashMap();param.put("categoryId", 44);param.put("currentPrice", 500);//查询条件List<Goods> list = session.selectList("goods.dynamicSQL", param);for(Goods g:list){System.out.println(g.getTitle() + ":" +g.getCategoryId()  + ":" + g.getCurrentPrice());}}catch (Exception e){throw e;}finally {MyBatisUtils.closeSession(session);}}/*** 测试一级缓存* @throws Exception*/@Testpublic void testLv1Cache() throws Exception {SqlSession session = null;try{session = MyBatisUtils.openSession();Goods goods = session.selectOne("goods.selectById" , 1603);Goods goods1 = session.selectOne("goods.selectById" , 1603);System.out.println(goods.hashCode() + ":" + goods1.hashCode());}catch (Exception e){throw e;}finally {MyBatisUtils.closeSession(session);}try{session = MyBatisUtils.openSession();Goods goods = session.selectOne("goods.selectById" , 1603);session.commit();//commit提交时对该namespace缓存强制清空Goods goods1 = session.selectOne("goods.selectById" , 1603);System.out.println(goods.hashCode() + ":" + goods1.hashCode());}catch (Exception e){throw e;}finally {MyBatisUtils.closeSession(session);}}/*** 测试二级缓存* @throws Exception*/@Testpublic void testLv2Cache() throws Exception {SqlSession session = null;try{session = MyBatisUtils.openSession();Goods goods = session.selectOne("goods.selectById" , 1603);System.out.println(goods.hashCode());}catch (Exception e){throw e;}finally {MyBatisUtils.closeSession(session);}try{session = MyBatisUtils.openSession();Goods goods = session.selectOne("goods.selectById" , 1603);System.out.println(goods.hashCode());}catch (Exception e){throw e;}finally {MyBatisUtils.closeSession(session);}}/*** 一对多对象关联查询* @throws Exception*/@Testpublic void testOneToMany() throws Exception {SqlSession session = null;try {session = MyBatisUtils.openSession();List<Goods> list = session.selectList("goods.selectOneToMany");for(Goods goods:list) {System.out.println(goods.getTitle() + ":" + goods.getGoodsDetails().size());}} catch (Exception e) {throw e;} finally {MyBatisUtils.closeSession(session);}}/*** 测试多对一对象关联映射*/@Testpublic void testManyToOne() throws Exception {SqlSession session = null;try {session = MyBatisUtils.openSession();List<GoodsDetail> list = session.selectList("goodsDetail.selectManyToOne");for(GoodsDetail gd:list) {System.out.println(gd.getGdPicUrl() + ":" + gd.getGoods().getTitle());}} catch (Exception e) {throw e;} finally {MyBatisUtils.closeSession(session);}}@Test/*** PageHelper分页查询*/public void testSelectPage() throws Exception {SqlSession session = null;try {session = MyBatisUtils.openSession();/*startPage方法会自动将下一次查询进行分页*/PageHelper.startPage(2,10);Page<Goods> page = (Page) session.selectList("goods.selectPage");System.out.println("总页数:" + page.getPages());System.out.println("总记录数:" + page.getTotal());System.out.println("开始行号:" + page.getStartRow());System.out.println("结束行号:" + page.getEndRow());System.out.println("当前页码:" + page.getPageNum());List<Goods> data = page.getResult();//当前页数据for (Goods g : data) {System.out.println(g.getTitle());}System.out.println("");} catch (Exception e) {throw e;} finally {MyBatisUtils.closeSession(session);}}/*** 批量插入测试* @throws Exception*/@Testpublic void testBatchInsert() throws Exception {SqlSession session = null;try {long st = new Date().getTime();session = MyBatisUtils.openSession();List list = new ArrayList();for (int i = 0; i < 10000; i++) {Goods goods = new Goods();goods.setTitle("测试商品");goods.setSubTitle("测试子标题");goods.setOriginalCost(200f);goods.setCurrentPrice(100f);goods.setDiscount(0.5f);goods.setIsFreeDelivery(1);goods.setCategoryId(43);//insert()方法返回值代表本次成功插入的记录总数list.add(goods);}session.insert("goods.batchInsert", list);session.commit();//提交事务数据long et = new Date().getTime();System.out.println("执行时间:" + (et - st) + "毫秒");
//            System.out.println(goods.getGoodsId());} catch (Exception e) {if (session != null) {session.rollback();//回滚事务}throw e;} finally {MyBatisUtils.closeSession(session);}}/*** 10000次数据插入对比测试用例* @throws Exception*/@Testpublic void testInsert1() throws Exception {SqlSession session = null;try{long st = new Date().getTime();session = MyBatisUtils.openSession();List list = new ArrayList();for(int i = 0 ; i < 10000 ; i++) {Goods goods = new Goods();goods.setTitle("测试商品");goods.setSubTitle("测试子标题");goods.setOriginalCost(200f);goods.setCurrentPrice(100f);goods.setDiscount(0.5f);goods.setIsFreeDelivery(1);goods.setCategoryId(43);//insert()方法返回值代表本次成功插入的记录总数session.insert("goods.insert" , goods);}session.commit();//提交事务数据long et = new Date().getTime();System.out.println("执行时间:" + (et-st) + "毫秒");
//            System.out.println(goods.getGoodsId());}catch (Exception e){if(session != null){session.rollback();//回滚事务}throw e;}finally {MyBatisUtils.closeSession(session);}}/*** 批量删除测试* @throws Exception*/@Testpublic void testBatchDelete() throws Exception {SqlSession session = null;try {long st = new Date().getTime();session = MyBatisUtils.openSession();List list = new ArrayList();list.add(1920);list.add(1921);list.add(1922);session.delete("goods.batchDelete", list);session.commit();//提交事务数据long et = new Date().getTime();System.out.println("执行时间:" + (et - st) + "毫秒");
//            System.out.println(goods.getGoodsId());} catch (Exception e) {if (session != null) {session.rollback();//回滚事务}throw e;} finally {MyBatisUtils.closeSession(session);}}
}

如何使用mybatis框架对数据库进行增删改查?相关推荐

  1. Springboot使用JPA框架对数据库实现增删改查(附详细代码)

    前言 1.本文将详细阐述如何使用JPA框架对数据库实现增删改查操作,业务中比较常见的应用场景几乎在这里都能看到,并且有详尽的代码可供直观演示,其中遇到的坑也进行了实时标注. 2.JPA的环境配置在前面 ...

  2. MyBatis框架的基础用法(增删改查)

    其主要用到MyBatis jar包,也可以搜索其官网进行下载,这里我给一个我自己用的MyBatis版本MyBatis-3.5.7提取码为"fs33"以及相应的配置文件,如有不懂请看 ...

  3. mybatis从零基础到增删改查数据库

    本文是mybatis框架一个初步的入门总结,最全的最好的资料应该参考这个:http://mybatis.github.io/mybatis-3/zh/index.html 本文在Eclipse下搭建一 ...

  4. jdbc增删改查有哪些步骤_用Mybatis如何实现对数据库的增删改查步骤

    使用Mybatiss实现对数据库的增删改查 文件目录 1.导入jar包,这里使用maven <dependencies><!--mybatis依赖--><!-- org. ...

  5. Mybatis学习笔记(二) 之实现数据库的增删改查

    开发环境搭建 mybatis 的开发环境搭建,选择: eclipse j2ee 版本,mysql 5.1 ,jdk 1.7,mybatis3.2.0.jar包.这些软件工具均可以到各自的官方网站上下载 ...

  6. ❤️使用Mybatis对数据库进行增删改查!!!

    ❤️使用Mybatis对数据库进行增删改查!!! ❤️namespace的用法 namespace中的包名要和接口一致: ❤️select用法 id:就是对应的namespace的方法名 result ...

  7. java jdbc 连接mysql数据库 实现增删改查

    好久没有写博文了,写个简单的东西热热身,分享给大家. jdbc相信大家都不陌生,只要是个搞java的,最初接触j2ee的时候都是要学习这么个东西的,谁叫程序得和数据库打交道呢!而jdbc就是和数据库打 ...

  8. Django实现对数据库数据增删改查(二)

    目录 1.基本框架 1.1.路由分发 1.2.视图函数-逻辑处理 1.3.模板 2.查询功能 2.1.视图函数 2.2.模板函数 3.添加功能 3.1.路由分发 3.2视图函数 3.3.模板 4.编辑 ...

  9. C#语言连接Mysql数据库实现增删改查

    C#语言连接Mysql数据库实现增删改查 实现效果如图 在此之前先下载一个mysql.dll 库 如下 链接:https://pan.baidu.com/s/17Nv_1W3KbXfWgdOvWf_S ...

最新文章

  1. 这个上古语言最近火了,80岁码农再就业;《终结者》里的代码也是它
  2. Linux同步自己的配置,Linux学习心得之——Rsync同步配置
  3. adobe photoshop cc 复制css链接
  4. php在线编辑器fckeditor,[原创]继续给力:PHP中使用FckEditor在线编辑器详解
  5. Tomcat 7 的domain域名配置,Tomcat 修改JSESSIONID
  6. centos网卡错误Device eth0 does not seem to be present
  7. 40个Java多线程问题总结【转】
  8. Matlab中FracLab计算分形维数方法
  9. 蓝桥杯 方格问题 6x6的方格,沿着格子的边线剪开成两部分。 要求这两部分的形状完全相同
  10. Error connecting to database: Access denied for user ‘zabbix‘@‘locahost‘
  11. 01-初探MQ-MQ的三大使用场景:应用解耦、异步提速、削峰填谷
  12. css英文文本不换行,CSS样式表让英文文本自动换行
  13. java实训报告前言_Java学习第一阶段总结
  14. 什么是BFC?BFC可以解决什么问题
  15. SpringBoot整合MybatisPlus遇到的大坑!
  16. bernoulli_Python-Bernoulli发行
  17. JS实现简单的网页新闻无缝滚动
  18. Backup Backup Backup
  19. LabVIEW同时使用NI 的GPIB和Keysight 的HPIB控制器
  20. 简书python_使用 Python 爬取简书网的所有文章

热门文章

  1. Eclipse安装PyDev插件后不显示问题解决方案
  2. 打印机SMB链接、共享文件夹
  3. BugKu-CTF(解密篇Crypto)---道友不来算一算凶吉?
  4. js string转uint8array
  5. freeswitch系列二 kamailio 5.0安装及实现kamailio集成freeswitch
  6. 基于安卓的学生学习互帮互助系统设计与实现
  7. 驱动中有关ioctl[宏]_IO, _IOR, _IOW, _IOWR 宏的用法与解析
  8. 高职高考计算机专业知识整合,2014高职高考计算机专业试卷4.doc
  9. 微信小程序input为数字键盘
  10. div标签以及网页设计中的一些知识点