mybatis 04: mybatis对象分析 + 测试代码简化 + 配置优化
MyBatis对象分析
- 测试代码示例
package com.example.test;
import com.example.pojo.Student;
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.InputStream;
import java.util.List;
public class TestStudent {
@Test
public void testGetAll() throws IOException {
//使用文件流获取核心配置文件SqlMapConfig.xml
InputStream in = Resources.getResourceAsStream("SqlMapConfig.xml");
//创建SqlSessionFactory工厂
SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(in);
//取出sqlSession对象
SqlSession sqlSession = factory.openSession();
//完成查询操作
List<Student> list = sqlSession.selectList("wangxun.getAll");
list.forEach(System.out::println);
//关闭sqlSession
sqlSession.close();
}
@Test
public void testGetById() throws IOException {
//读取核心配置文件
InputStream in = Resources.getResourceAsStream("SqlMapConfig.xml");
//创建SqlSessionFactory对象
SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(in);
//获取SqlSession
SqlSession sqlSession = factory.openSession();
//按主键查询
Student student = sqlSession.selectOne("wangxun.getById", 3);
System.out.println(student);
//关闭SqlSession
sqlSession.close();
}
@Test
public void testGetByName() throws IOException {
//读取核心配置文件
InputStream in = Resources.getResourceAsStream("SqlMapConfig.xml");
//创建SqlSessionFactory对象
SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(in);
//获取SqlSession
SqlSession sqlSession = factory.openSession();
//按照姓名模糊查询
List<Student> students = sqlSession.selectList("wangxun.getByName", "三");
students.forEach(System.out::println);
//关闭SqlSession
sqlSession.close();
}
@Test
public void testInsert() throws IOException {
//读取核心配置文件
InputStream in = Resources.getResourceAsStream("SqlMapConfig.xml");
//创建SqlSessionFactory对象
SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(in);
//获取SqlSession
SqlSession sqlSession = factory.openSession();
//插入数据
int num = sqlSession.insert("wangxun.insert", new Student("小涵", "0321@qq.com", 20));
//切记:在所有的增删改后,必须手动提交
sqlSession.commit();
if (num == 1) {
System.out.println("插入成功!");
}else{
System.out.println("插入失败!");
}
//关闭SqlSession
sqlSession.close();
}
@Test
public void testDelete() throws IOException {
//读取核心配置文件
InputStream in = Resources.getResourceAsStream("SqlMapConfig.xml");
//创建SqlSessionFactory对象
SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(in);
//获取SqlSession对象
SqlSession sqlSession = factory.openSession();
//执行删除语句
int num = sqlSession.delete("wangxun.delete", 5);
sqlSession.commit();
if(num == 1){
System.out.println("删除成功!");
}else{
System.out.println("删除失败!");
}
//关闭SqlSession
sqlSession.close();
}
@Test
public void testUpdate() throws IOException {
//读取核心配置文件
InputStream in = Resources.getResourceAsStream("SqlMapConfig.xml");
//创建SqlSessionFactory对象
SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(in);
//获取SqlSession
SqlSession sqlSession = factory.openSession();
//执行更新语句
int num = sqlSession.update("wangxun.update", new Student(1, "小何", "hehe@qq.com", 20));
sqlSession.commit();
if(num == 1){
System.out.println("更新成功!");
}else{
System.out.println("更新失败!");
}
//关闭SqlSession
sqlSession.close();
}
}
- Resources类
- 解析SqlMapConfig,xml文件,创建出相应的对象
- InputStream = Resources.getResourceAsStream("SqlMapConfig.xml");
- SqlSessionFactory接口
- DefaultSqlSessionFactory是其一个实现类
- ctrl + h 可以快捷查看本接口的子接口及其实现类
- SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(in);
- DefaultSqlSessionFactory是其一个实现类
- SqlSession接口
- DefaultSqlSession是其一个实现类
测试代码简化
- 简化后的测试代码
package com.example.test;
import com.example.pojo.Student;
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.After;
import org.junit.Before;
import org.junit.Test;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
public class TestStudent {
//SqlSession对象
SqlSession sqlSession;
//获取SqlSession对象
@Before
public void createSqlSession() throws IOException {
//使用文件流获取核心配置文件SqlMapConfig.xml
InputStream in = Resources.getResourceAsStream("SqlMapConfig.xml");
//创建SqlSessionFactory工厂
SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(in);
//取出sqlSession对象
sqlSession = factory.openSession();
}
//归还SqlSession对象
@After
public void closeSqlSession(){
sqlSession.close();
}
@Test
public void testGetAll() throws IOException {
//完成查询操作
List<Student> list = sqlSession.selectList("wangxun.getAll");
list.forEach(System.out::println);
}
@Test
public void testGetById() throws IOException {
//按主键查询
Student student = sqlSession.selectOne("wangxun.getById", 3);
System.out.println(student);
}
@Test
public void testGetByName() throws IOException {
//按照姓名模糊查询
List<Student> students = sqlSession.selectList("wangxun.getByName", "三");
students.forEach(System.out::println);
}
@Test
public void testInsert() throws IOException {
//插入数据
int num = sqlSession.insert("wangxun.insert", new Student("小涵", "0321@qq.com", 20));
//切记:在所有的增删改后,必须手动提交
sqlSession.commit();
if (num == 1) {
System.out.println("插入成功!");
}else{
System.out.println("插入失败!");
}
}
@Test
public void testDelete() throws IOException {
//执行删除语句
int num = sqlSession.delete("wangxun.delete", 5);
sqlSession.commit();
if(num == 1){
System.out.println("删除成功!");
}else{
System.out.println("删除失败!");
}
}
@Test
public void testUpdate() throws IOException {
//执行更新语句
int num = sqlSession.update("wangxun.update", new Student(1, "小何", "hehe@qq.com", 20));
sqlSession.commit();
if(num == 1){
System.out.println("更新成功!");
}else{
System.out.println("更新失败!");
}
}
}
实体类别名注册
- 单个实体类起别名
<!-- 为实体类注册别名
注意标签的出现顺序
-->
<typeAliases>
<typeAlias type="com.example.pojo.Student" alias="student"/>
</typeAliases>
- 批量为实体类起别名
<typeAliases>
<!-- 包下的所有实体类自动起别名(规范):
别名是实体类类名的驼峰命名法
-->
<package name="com.example.pojo"/>
</typeAliases>
<!-- 例如:
com.example.pojo包下有实体类:Studnet
则使用到该实体类的sql标签可以如下表示:
-->
<select id="getAll" resultType="student">
select
id, name, email, age
from
student
</select>
设置日志输出
- 配置示例
<!-- 设置日志输出sql语句底层执行的代码-->
<settings>
<setting name="logImpl" value="STDOUT_LOGGING"/>
</settings>
- 测试示例
package com.example.test;
import com.example.pojo.Student;
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.After;
import org.junit.Before;
import org.junit.Test;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
public class TestStudent {
//SqlSession对象
SqlSession sqlSession;
//获取SqlSession对象
@Before
public void createSqlSession() throws IOException {
//使用文件流获取核心配置文件SqlMapConfig.xml
InputStream in = Resources.getResourceAsStream("SqlMapConfig.xml");
//创建SqlSessionFactory工厂
SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(in);
//取出sqlSession对象
sqlSession = factory.openSession();
}
//归还SqlSession对象
@After
public void closeSqlSession(){
sqlSession.close();
}
@Test
public void testGetAll() throws IOException {
//完成查询操作
List<Student> list = sqlSession.selectList("wangxun.getAll");
list.forEach(System.out::println);
}
}
/*
输出结果的部分:
Checking to see if class com.example.pojo.Student matches criteria [is assignable to Object]
PooledDataSource forcefully closed/removed all connections.
PooledDataSource forcefully closed/removed all connections.
PooledDataSource forcefully closed/removed all connections.
PooledDataSource forcefully closed/removed all connections.
Opening JDBC Connection
Created connection 1806880779.
Setting autocommit to false on JDBC Connection [com.mysql.cj.jdbc.ConnectionImpl@6bb2d00b]
==> Preparing: select id, name, email, age from student
==> Parameters:
<== Columns: id, name, email, age
<== Row: 1, 小何, hehe@qq.com, 20
<== Row: 2, 李四, lisi@126.com, 21
<== Row: 3, 王五, wangwu@163.com, 22
<== Row: 4, 赵六, zhaoliun@qq.com, 24
<== Row: 6, 小涵, 0321@qq.com, 20
<== Total: 5
Student{id=1, name='小何', email='hehe@qq.com', age=20}
Student{id=2, name='李四', email='lisi@126.com', age=21}
Student{id=3, name='王五', email='wangwu@163.com', age=22}
Student{id=4, name='赵六', email='zhaoliun@qq.com', age=24}
Student{id=6, name='小涵', email='0321@qq.com', age=20}
Resetting autocommit to true on JDBC Connection [com.mysql.cj.jdbc.ConnectionImpl@6bb2d00b]
Closing JDBC Connection [com.mysql.cj.jdbc.ConnectionImpl@6bb2d00b]
Returned connection 1806880779 to pool.
Process finished with exit code 0
*/
mybatis 04: mybatis对象分析 + 测试代码简化 + 配置优化的更多相关文章
- Java&Selenium自动化测试实现页面元素、页面对象及测试代码分离
一.摘要 本篇博文将介绍自动化测试实现页面元素.页面对象及测试代码分离在自动化框架中的实现 二.解析页面元素定位信息 首先,将页面元素与实际的代码分离,首先我们将页面元素定位信息和定位表达式保存在属性 ...
- 轻量级封装DbUtils&Mybatis之四MyBatis主键
MyBatis主键 不支持对象列表存储时对自增id字段的赋值(至少包括3.2.6和3.3.0版本),如果id不是采用底层DB自增主键赋值,不必考虑此问题 温馨提示:分布式DB环境下,DB主键一般会采用 ...
- 【Mybatis】MyBatis之缓存(七)
MyBatis缓存介绍 Mybatis 使用到了两种缓存:一级缓存(本地缓存.local cache)和二级缓存(second level cache). 一级缓存:基于PerpetualCache ...
- Mybatis+mysql批量插入性能分析测试
前言 今天在网上看到一篇文章(后文中的文章指的就是它) https://www.jianshu.com/p/cce617be9f9e 发现了一种有关于mybatis批量插入的新方法,而且看了文章发现我 ...
- Mybatis执行流程源码分析
第一部分:项目结构 user_info表:只有id和username两个字段 User实体类: public class User { private String username; private ...
- mybatis入门 配置文件解释 及测试
这里介绍一下mybatis 根据mybatis的官网说明,mybatis是一款优秀的持久层框架,它支持定制化 SQL.存储过程以及高级映射.MyBatis 避免了几乎所有的 JDBC 代码和手动设置 ...
- myBatis 基础测试 表关联关系配置 集合 测试
myBatis 基础测试 表关联关系配置 集合 测试 测试myelipse项目源码 sql 下载 http://download.csdn.net/detail/liangrui1988/599388 ...
- MyBatis框架及原理分析
MyBatis 是支持定制化 SQL.存储过程以及高级映射的优秀的持久层框架,其主要就完成2件事情: 封装JDBC操作 利用反射打通Java类与SQL语句之间的相互转换 MyBatis的主要设计目的就 ...
- mybatis与spring的整合(代码实现)
mybatis与spring的整合(代码实现) 需要jar包: mybatis核心包:依赖包:log4j包:spring croe;beans;tx;aop;aspects;context;expre ...
随机推荐
- 以圆类 Circle 及立体图形类 Solid 为基础设计圆柱类 Cylinder
学习内容:以圆类 Circle 及立体图形类 Solid 为基础设计圆柱类 Cylinder 代码示例: import java.util.Scanner;class Point3{ private ...
- declare-声明限定类型变量
用于声明变量并设置变量的属性. 语法 declare [+/-][rxi][变量名称=设置值] declare -f 特殊符号 +/- "-"可用来指定变量的属性,"+& ...
- Fail2ban 命令详解 fail2ban-regex
fail2ban-regex是fail2ban提供的用来测试正则表达式的一个小工具,我们可以用它来测试正则表达式是否能够匹配到日志文件中的要禁止的IP行. fail2ban-regex默认情况下自动匹 ...
- Numpy的一些操作
1.什么是Numpy 简单来说: Numpy(Numerical Python)是一个开源的Python科学计算库,用于快速处理任意维度的数组. Numpy支持常见的数组和矩阵操作.对于同样的数值计算 ...
- 一文带你看懂Java中的Lock锁底层AQS到底是如何实现的
前言 相信大家对Java中的Lock锁应该不会陌生,比如ReentrantLock,锁主要是用来解决解决多线程运行访问共享资源时的线程安全问题.那你是不是很好奇,这些Lock锁api是如何实现的呢?本 ...
- ptorch常用代码梯度篇(梯度裁剪、梯度累积、冻结预训练层等)
梯度裁剪(Gradient Clipping) 在训练比较深或者循环神经网络模型的过程中,我们有可能发生梯度爆炸的情况,这样会导致我们模型训练无法收敛. 我们可以采取一个简单的策略来避免梯度的爆炸,那 ...
- GDB的简单使用一
GDB的简单使用一 一.概念 二.GDB的基本使用方法一 调试前预备知识 获取进程的内核转储 启动gdb调试 1.启动 2.设置断点 3.运行程序 4.显示栈帧 5.显示变量 6.显示寄存器 7.单步 ...
- 钉钉登录二维码嵌套在vue页面中
转自 https://www.csdn.net/tags/OtDacg3sMjQ2NTgtYmxvZwO0O0OO0O0O.html 钉钉登录二维码嵌套在vue页面中 2021-09-04 14:42 ...
- FTPClient处理中文乱码问题,实测通过了
使用FTPClient 操作FTP时,遇到路径或文件名中文乱码问题: 其中的一种处理方式: 在new FTPClient()后,可以设置编码, ftpClient=new FTPClient( ...
- stm32f103ve+BH1750使用教程+oled(HAL库)
1.硬件:BH1750模块+oled 2.代码:BH1750是标准的iic协议的外设,我这里单独有iic的文件,之后想要实现多个设备共用一个iic. BH1750.c 1 #include " ...