当前位置: 首页 > news >正文

MyBatis:概念简章

1. hello world

配置文件:mybatis-config.xml(核心配置文件,用于配置连接的数据库信息)(一般一个)XxxMapper.xml 该文件用于操作表(执行sql语句)(一张表一个)
细节:执行的sql语句";"可以省略一般有resource这个单词都会从类的根路径开始扫描文件
  1. 配置mybatis-config.xml文件
  2. 配置配置xxxMapper.xml文件
  3. 对数据库进行CRUD操作 
<?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><environments default="development"><environment id="development"><transactionManager type="JDBC"/><dataSource type="POOLED"><property name="driver" value="com.mysql.cj.jdbc.Driver"/><property name="url" value="jdbc:mysql://localhost:3306/study"/><property name="username" value="root"/><property name="password" value="123456"/></dataSource></environment></environments><!--路径映射,要操作的表--><mappers><mapper resource="mapper/EmployeeMapper.xml"/></mappers>
</configuration>
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapperPUBLIC "-//mybatis.org//DTD Mapper 3.0//EN""http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<!--要进行CURD操作的表-->
<mapper namespace="EmployeeMapper"><!--<select id="selectUser" resultType="Blog">select * from Blog where id = 1</select>--><insert id="insertEmployee">insert into emp value (null, '姬如雪', 18, 2, '佛山');</insert>
</mapper>
    @Testpublic void testInsert() throws IOException {//获取对应的数据库配置信息(即要操作哪个数据库)InputStream is = Resources.getResourceAsStream("mybatis-config.xml");//Resources.getResourceAsStream默认从类的根路径开始寻找文件//获取SqlSessionFactoryBuilder(通过该对象创建工厂)(一般一个数据库对应一个SqlSessionFactory)SqlSessionFactoryBuilder sqlSessionFactoryBuilder = new SqlSessionFactoryBuilder();//获取SqlSessionFactory(通过该工厂创建SqlSession:Java程序和数据库之间的会话)SqlSessionFactory sqlSessionFactory = sqlSessionFactoryBuilder.build(is);//获取SqlSession执行sql语句(即要操作哪张表)SqlSession sqlSession = sqlSessionFactory.openSession();//执行sql语句int rows = sqlSession.insert("insertEmployee");//提交事务sqlSession.commit();System.out.println("rows:" + rows);}

上面测试代码的严谨写法

    @Testpublic void testSelectComplete() {SqlSession sqlSession = null;try {//获取SqlSessionFactoryBuild对象SqlSessionFactoryBuilder sqlSessionFactoryBuilder = new SqlSessionFactoryBuilder();//获取SqlSessionFactory工厂SqlSessionFactory sqlSessionFactory = sqlSessionFactoryBuilder.build(Resources.getResourceAsStream("mybatis-config.xml"));//获取SqlSession会话sqlSession = sqlSessionFactory.openSession();int rows = sqlSession.insert("insertEmployee");sqlSession.commit();System.out.println("rows:" + rows);} catch (IOException e) {if (sqlSession != null) {sqlSession.rollback();}e.printStackTrace();} finally {if (sqlSession != null) {sqlSession.close();}}}

2. 封装工具类SqlSessionUtil

由于每次都需要创建SqlSessionFactoryBuilder、SqlSessionFactory、SqlSession对象,可以直接封装成工具类方便调用 

public class SqlSessionUtil {private static SqlSessionFactory sqlSessionFactory;static {try {sqlSessionFactory = new SqlSessionFactoryBuilder().build(Resources.getResourceAsStream("mybatis-config.xml"));} catch (IOException e) {throw new RuntimeException(e);}}public static SqlSession openSession() {return sqlSessionFactory.openSession();}}
    @Testpublic void testSqlSessionUtil() {SqlSession sqlSession = SqlSessionUtil.openSession();int rows = sqlSession.insert("insertEmployee");sqlSession.commit();sqlSession.close();System.out.println("rows:" + rows);}

3. CRUD操作

3.1 增 

    #{} 占位符
1.如果传map对象:占位符里面的参数要和map集合中的键相一致才能获取map集合中的value值
2.如果传bean对象:占位符里面的参数要和bean对象的属性名保持一致才能获取bean对象的数据
<mapper namespace="EmployeeMapper"><insert id="insertEmployee">insert into emp values (null, #{name}, #{age}, #{deptId}, #{address})</insert>
</mapper>

方式一:通过传map对象

    @Testpublic void tesInsertEmployee() {SqlSession sqlSession = SqlSessionUtil.openSession();Map<String, Object> map = new HashMap<>();map.put("name", "肚肚龙");map.put("age", 3);map.put("deptId", 1);map.put("address", "广东");//执行sql语句  底层执行sql语句时会根据map集合的键占位符相匹配,若一致就将值赋给占位符#{}sqlSession.insert("insertEmployee", map);sqlSession.commit();sqlSession.close();}

方式二:通过传bean对象

public class Employee {private Integer id;private String name;private Integer age;private Integer deptId;private String address;
    @Testpublic void tesInsertEmployee() {SqlSession sqlSession = SqlSessionUtil.openSession();//执行sql语句  底层执行sql语句时会根据map集合的键占位符相匹配,若一致就将值赋给占位符#{}sqlSession.insert("insertEmployee", map);Employee e = new Employee(null, "肥奶龙", 2, 6, "江门");sqlSession.insert("insertEmployee", e);sqlSession.commit();sqlSession.close();}

3.2 删

<mapper namespace="EmployeeMapper"><delete id="deleteEmployee">delete from emp where id = #{id}</delete>
</mapper>
    @Testpublic void testDeleteEmployee() {//获取sql会话SqlSession sqlSession = SqlSessionUtil.openSession();//执行sql语句,由于删除只需要一个参数,故随便传即可,他会自动识别int rows = sqlSession.delete("deleteEmployee", 10028);sqlSession.commit();sqlSession.close();System.out.println("rows:" + rows);}

 3.3 改

<mapper namespace="EmployeeMapper"><update id="updateEmployee">update emp set name = #{name}, age= #{age}, dept_id = #{deptId}, address = #{address} where id = #{id}</update>
</mapper>
    @Testpublic void testUpdateEmployee() {//获取sql会话SqlSession sqlSession = SqlSessionUtil.openSession();Employee e = new Employee(10027, "胖胖龙", 1, 9, "长沙");//执行sql语句int rows = sqlSession.update("updateEmployee", e);sqlSession.commit();sqlSession.close();System.out.println("rows:" + rows);}

3.4 查

 

注意:因为查询的列大多要和bean对象的字段进行反射映射匹配赋值,故列要起别名保证和bean对象字段名一致
查询还有返回类型,要指定给查询标签,通过类型反射赋值为防止id冲突,需要引用命名空间,所有语句执行正确的写法为namespace.id

查询单个结果

<mapper namespace="EmployeeMapper"><select id="selectById" resultType="com.itgyl.mybatis.pojo.Employee">select id, name, age, dept_id deptId, address from emp where id = #{id}</select>
</mapper>
    @Testpublic void testSelectEmployeeById() {//获取sql会话SqlSession sqlSession = SqlSessionUtil.openSession();//执行sql语句 selectOne查询返回一个bean对象Object employee = sqlSession.selectOne("selectById", 1);sqlSession.close();System.out.println(employee);}

查询所有结果

<mapper namespace="EmployeeMapper"><select id="selectAll" resultType="com.itgyl.mybatis.pojo.Employee">select id, name, age, dept_id deptId, address from emp</select>
</mapper>
    @Testpublic void testSelectEmployeeAll() {SqlSession sqlSession = SqlSessionUtil.openSession();/*查询所有bean对象存入list集合中并返回 最严谨写法:namespace.id*/List<Object> employeeList = sqlSession.selectList("EmployeeMapper.selectAll");for (Object o : employeeList) {System.out.println(o);}sqlSession.close();}

4. 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><!--environments标签:环境可以有多个即可以同时配置多个数据库数据库不唯一,可以配置多个数据库信息即可以创建多个SqlSessionFactory工厂default的值为:不指定创建哪个SqlSessionFactory时默认使用id为default值的数据库--><environments default="development"><environment id="development"><!--在 MyBatis 中有两种类型的事务管理器(也就是 type="[JDBC|MANAGED]"):transactionManage标签:事务管理器1.作用:指定mybatis用什么方式进行管理事务2.有两个type类型:1.JDBC:使用原生的jdbc管理容器coon.setAutoCommit(false)...coon.commit()2.MANAGED:mybatis不再管理事务,将事务管理器交给其他容器管理如javaEE容器进行管理(spring)--><transactionManager type="JDBC"/><!--dataSource 元素使用标准的 JDBC 数据源接口来配置 JDBC 连接对象的资源。datasource:数据源1.作用:为程序提供Connection对象(但凡为程序提供Connection对象的都称为数据源)2.常见的数据源组件(常见的数据库连接池):druid等3.有三种内建的数据源类型(也就是 type="[UNPOOLED|POOLED|JNDI]"):1.UNPOOLED– 这个数据源的实现会每次请求时打开和关闭连接。2.POOLED:使用mybatis自带的数据库连接池3.JNDI:集成其他第三方连接池--><dataSource type="POOLED"><property name="driver" value="com.mysql.cj.jdbc.Driver"/><property name="url" value="jdbc:mysql://localhost:3306/study"/><property name="username" value="root"/><property name="password" value="123456"/></dataSource></environment></environments><!--Mappers标签:路径映射,要操作的表表不唯一,可以同时配置多个表进行操作即可以创建多少SqlSession--><mappers><mapper resource="mapper/EmployeeMapper.xml"/></mappers>
</configuration>

 

 

http://www.lryc.cn/news/369325.html

相关文章:

  • 有什么接码平台比较好用的
  • 微服务之负载均衡器
  • 《时间管理九段》前四阶段学习笔记
  • LLVM Cpu0 新后端5 静态重定位 动态重定位
  • 旅游卡是项目还是骗局?还是实实在在的旅游项目?
  • 大模型+RAG,全面介绍!
  • 智能合约中存储和计算效率漏洞
  • 软件测试基础知识总结
  • C语言 | Leetcode C语言题解之第143题重排链表
  • 探寻性能优化:如何衡量?如何决策?
  • Python Django 5 Web应用开发实战
  • H.264官方文档下载
  • minio多节点部署
  • 2024年工业设计与制造工程国际会议(ICIDME 2024)
  • 一次曝 9 个大模型,「字节 AI」这一年都在做什么?
  • PR基本概念数学知识
  • 信驰达蓝牙数字钥匙方案持续创新,助推智慧汽车生态发展
  • 校园生活服务平台的设计
  • gerrit 使用
  • 【GD32F303红枫派使用手册】第十二节 ADC-双轴按键摇杆多通道循环采样实验
  • Rust-03-数据类型
  • 代理IP使用api接
  • C++中的适配器模式
  • MySQL入门学习-聚合和分组.最大值(MAX()函数)
  • LLM大语言模型(十六):最新开源 GLM4-9B 本地部署,带不动,根本带不动
  • 【JVM】JVM 的内存区域
  • intel新CPU性能提升68%!却在内存上违反祖训
  • stm32MP135裸机编程:修改官方GPIO例程在DDR中点亮第一颗LED灯
  • 探索乡村振兴新模式:发挥科技创新在乡村振兴中的引领作用,构建智慧农业体系,助力美丽乡村建设
  • 机器学习笔记:focal loss