java学习总结(四):MyBatis

devtools/2025/3/15 1:10:27/

一、MyBatis介绍

像MyBatis、Hibernate都是属于ORM框架

对象关系映射(英语:(Object Relational Mapping,简称ORM)

MySql、Oracle、SqlServer都是关系型数据库

1、O->R add/insert/save

studentDao.insert(student)

把一个java对象保存到数据库中的一行记录

2、R->O selectById/findById/listById

Student student = sudentDao.findById(id)

把数据库里面的一行记录封装成一个java对象

二、MyBatis执行流程

MappedStatement是MyBatis框架中的一个重要类,用于表示映射配置文件(Mapper XML文件)中的SQL语句。在MyBatis中,每个SQL语句都会被解析成一个MappedStatement对象,它包含了SQL语句的相关信息,如ID、参数映射、结果映射、SQL语句类型等。

<select id="selectAll" resultType="Student">SELECT id, name, age, gender, banji_id FROM student
</select>
、读取MyBatis配置文件:mybatis-config.xml加载运行环境和映射文件
2、构造会话工厂SqlSessionFactory
3、会话工厂创建SqlSession对象(包含了执行SQL语句的所有方法)
4、操作数据库的接口,Executor执行器,同时负责查询缓存的维护
5、Executor接口的执行方法中有一个MappedStatement类型的参数,封装了映射信息
6、输入参数映射(Java类型转换为数据库支持的类型)
7、输出结果映射(数据库类型转化为Java类型)

三、MyBatis快速入门

@Test
public void testSelectById() throws IOException {String resource = "mybatis.xml";InputStream inputStream = Resources.getResourceAsStream(resource);// 创建 SqlSessionFactory    Session:会话 (连接数据库后就建立了一次会话,有了会话就可以操作数据库)SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);// 得到SqlSessionSqlSession sqlSession = sqlSessionFactory.openSession();// 执行sql语句Student student = sqlSession.selectOne("student.selectById", 59);System.out.println(student);
}

四、封装工具类

public class MyBatisUtil {private static SqlSessionFactory sqlSessionFactory;//静态代码块中的代码只会执行一次static {try {String resource = "mybatis.xml";InputStream inputStream;inputStream = Resources.getResourceAsStream(resource);// 创建 SqlSessionFactory    Session:会话 (连接数据库后就建立了一次会话,有了会话就可以操作数据库)sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);} catch (IOException e) {e.printStackTrace();}}public static SqlSession getSqlSession() {// 得到SqlSessionSqlSession sqlSession = sqlSessionFactory.openSession();return sqlSession;}
}@Test
public void testSelectById1() throws IOException {SqlSession sqlSession = MyBatisUtil.getSqlSession();// 执行sql语句Student student = sqlSession.selectOne("student.selectById", 66);System.out.println(student);
}

五、typeAliases类型别名

上图是mybatis3.3.0官方文档上提供的别名和java类型的映射关系

int/Integer/ineger

在配置int时通过上表可以看出,即可以是java中的基本类型int,也可以是java中的包装类型Integer,不过在配置为包装类型是必须是java.lang.Integer,所以在配置为int是我们的java接口中的参数类型最好是Integer的。

string/String :对应java中的java.lang.String

map :对应java.util.Map

hashmap :对应java.util.HashMap

list :对应java.util.List

arraylist :对应java.util.ArrayList

<settings><!-- 下划线字段对应实体类驼峰命名 数据库表:banji_id 映射到类里面:banjiId --><setting name="mapUnderscoreToCamelCase" value="true"/>
</settings><typeAliases><!--<typeAlias alias="Student" type="com.situ.mybatis.pojo.Student"/><typeAlias alias="Banji" type="com.situ.mybatis.pojo.Banji"/> --><!-- 扫描包里面的类,批量起别名,别名即类名,不区分大小写 --><package name="com.situ.mybatis.pojo"/>
</typeAliases>

六、基本增删改查的操作

<mapper namespace="student"><!-- public Student selectById(Integer id) {}parameterType="java.lang.Integer"resultType="com.situ.mybatis.pojo.Student"--><select id="selectById"  parameterType="Integer" resultType="Student">SELECT id,name,age,gender,banji_id FROM student where id=#{id}</select><!--public List<Student> selectAll();--><select id="selectAll" resultType="Student">SELECT id,name,age,gender,banji_id FROM student</select><!-- 对于更新类的操作返回的是影响的行数,但是resultType不需要写public int deleteById(Integer id)更新类返回影响的行数,在这里不用写返回值类型--><delete id="deleteById" parameterType="Integer">DELETE FROM student WHERE id=#{id}</delete><!--public int add(Student student)--><insert id="add" parameterType="Student" useGeneratedKeys="true" keyProperty="id">INSERT INTOstudent(name,age,gender,banji_id)VALUES(#{name},#{age},#{gender},#{banjiId})</insert><update id="update" parameterType="Student">UPDATEstudentSETname=#{name},age=#{age},gender=#{gender},banji_id=#{banjiId}WHEREid=#{id}</update>
</mapper>
@Test
public void testDeleteById() throws IOException {// Setting autocommit to false on JDBC Connection// JDBC默认autocommit值是true,MyBatis把JDBC的autocommit设置为false,// 当执行delete的时候并没有真正提交到数据库,对于更新类的操作需要手动提交。// 在JDBC里面默认不需要用户手动提交因为autocommit 默认就是true,执行executeUpdate// 的时候直接修改了数据库SqlSession sqlSession = MyBatisUtil.getSqlSession();int count = sqlSession.delete("student.deleteById", 59);System.out.println("count: " + count);// 对于更新类的操作需要手动提交sqlSession.commit();sqlSession.close();
}

七、Sql片段

<sql id="studentColumns">id,name,age,gender,banji_id
</sql><!-- 通过id查找学生 refid reference-->
<select id="selectById" parameterType="Integer" resultType="Student">SELECT <include refid="studentColumns"/>FROM studentWHERE id = #{id}
</select>

八、输入映射

parameterType(输入类型)
  1. 传递简单类型:selectById(Integer id)
使用时候#{id}
  1. 传递实体类:add(Student student)
使用时候#{age}括号中的值为实体类中属性的名字。
  1. 传递Map(传递过个参数)
@Test
public void testSelectByPage() throws IOException {SqlSession sqlSession = MyBatisUtil.getSqlSession();int pageNo = 2;int pageSize = 3;int offset = (pageNo - 1) * pageSize;Map<String, Integer> map = new HashMap<String, Integer>();map.put("offset", offset);map.put("pageSize", pageSize);List<Student> list = sqlSession.selectList("student.selectByPage", map);for (Student student : list) {System.out.println(student);}
}
<select id="selectByPage" parameterType="Map" resultType="Student">SELECT <include refid="studentColumns"/> FROM  student LIMIT #{offset},#{pageSize}
</select>

九、输出映射

1、基本数据类型:

查找一共有多少学生

<select id="selectTotalCount" resultType="Integer">SELECT count(*) FROM student
</select>@Test
public void testSelectTotalCount() throws IOException {SqlSession sqlSession = MyBatisUtil.getSqlSession();int count = sqlSession.selectOne("student.selectTotalCount");System.out.println("count: " + count);
}

2、输出实体类:Student

3、输出集合:List

resultMap

如果查询出来的列名和实体类的属性不一致,通过定义一个resultMap对列名和实体类属性名做一个映射关系。

resultMap 元素是 MyBatis 中最重要最强大的元素。

结果集的映射是 MyBatis 最强大的特性,对其有一个很好的理解的话,许多复杂映射的情形都能迎刃而解。使用 resultMap 或 resultType,但不能同时使用。

<!-- resultMap最终是要将结果映射到Student上
当实体类的属性名和表的字段名不一致的时候,必须要写这个映射 -->
<resultMap type="Student" id="studentMap"><!-- 映射主键属性:如果有多个主键字段,则定义多个id --><!-- property:类的属性名 --><!-- column:表的字段名 --><id column="id" property="id" /><!-- result定义普通属性 --><result column="student_name"  property="name" /><result column="age" property="age" /><result column="gender" property="gender" />
</resultMap><select id="selectAll" resultMap="studentMap">select id,student_name,age,gender from student
</select>


http://www.ppmy.cn/devtools/167164.html

相关文章

React hook钩子性能优化Hooks的面试常考题目

根据,提到了常用的Hooks有useState、useEffect、useContext、useReducer、useCallback、useMemo、useRef,还有其他如useLayoutEffect和useImperativeHandle。和也提到了类似的Hooks,并且强调了useEffect的重要性。详细解释了useState、useEffect、useMemo和useCallback的区别…

PHP与数据库连接常见问题及解决办法

PHP与数据库连接常见问题及解决办法 在现代Web开发中&#xff0c;PHP与数据库的连接是不可或缺的一部分。无论是构建动态网站、内容管理系统&#xff08;CMS&#xff09;还是电子商务平台&#xff0c;PHP与数据库的交互都是核心功能之一。然而&#xff0c;在实际开发过程中&am…

第27周JavaSpringboot 前后端联调

电商前后端联调课程笔记 一、项目启动与环境搭建 1.1 项目启动 在学习电商项目的前后端联调之前&#xff0c;需要先掌握如何启动项目。项目启动是整个开发流程的基础&#xff0c;只有成功启动项目&#xff0c;才能进行后续的开发与调试工作。 1.1.1 环境安装 环境安装是项…

SpringBoot3+Lombok如何配置logback输出日志到文件

Background/Requirement SpringBoot3Lombok如何配置logback输出日志到文件&#xff0c;因为我需要对这些日志进行输出&#xff0c;控制台输出和文件输出&#xff0c;文件输出是为了更好的作为AuditLog且支持滚动式备份&#xff0c;每天一个文件。 Technical Solution 1.确保你…

Python 入门教程(2)搭建环境 2.4、VSCode配置Node.js运行环境

文章目录 一、VSCode配置Node.js运行环境 1、软件安装2、安装Node.js插件3、配置VSCode4、创建并运行Node.js文件5、调试Node.js代码 一、VSCode配置Node.js运行环境 1、软件安装 安装下面的软件&#xff1a; 安装Node.js&#xff1a;Node.js官网 下载Node.js安装包。建议选…

如何利用Python爬虫获取微店商品详情数据:实战指南

微店作为知名的电商平台&#xff0c;提供了丰富的商品资源。通过Python爬虫技术&#xff0c;可以高效地获取微店商品的详情数据&#xff0c;用于数据分析、研究或其他用途。本文将详细介绍如何使用Python编写爬虫程序&#xff0c;获取微店商品的详情数据&#xff0c;并确保爬虫…

Smart contract -- 工厂合约

在区块链开发领域&#xff0c;Solidity 语言以其强大的功能和灵活性&#xff0c;为开发者提供了构建复杂智能合约系统的可能性。其中&#xff0c;工厂合约模式是一种常见的设计模式&#xff0c;它能够高效地创建和管理多个具有相似功能的合约实例。本文将通过一个具体的代码示例…

【Linux】:进程间通信

进程间通信目的 数据传输&#xff1a;一个进程需要将它的数据发送给另一个进程 资源共享&#xff1a;多个进程之间共享同样的资源。 通知事件&#xff1a;一个进程需要向另一个或一组进程发送消息&#xff0c;通知它&#xff08;它们&#xff09;发生了某种事件&#xff08;如…