MyBatis学习笔记--入门的增删改查

前言:MyBatis是一个支持普通SQL查询,存储过程以及高级映射的持久层框架,也被称为ORM(Object/Relational Mapping,即对象关系映射)框架。以面向对象的方式来操作持久化对象


1. MyBatis的工作原理

  1. 读取MyBatis配置文件(如:mybatis-config.xml),作为MyBatis的全局配置文件,配置了MyBatis的运行环境等,主要是获取数据库连接。
  2. 加载映射文件(如:StudentMapper),StudentMapper文件即SQL映射文件,改文件中配置了操作数据库的SQL语句,需要在mybatis-config.xml中加载才能执行。
  3. 构造会话工厂(SqlSessionFactory)
  4. 构造会话对象(SqlSession),包含了执行SQL的所有方法
  5. Executor执行器,MyBatis底层定义了Executor接口来操作数据库
  6. MapperedStatement对象,StudentMapper文件中一个SQL对应一个MapperedStatement,SQL的id即是MapperedStatement的id
  7. 输入参数映射
  8. 输出结果映射

2. MyBatis的入门程序

  1. 在mariaDB中创建mybatis的数据库,创建表t_student,并插入几行数据

在这里插入图片描述

  1. Eclipse中创建一个web项目,导入已经下好的mybastis的jar包,包括连接数据库的jar包

在这里插入图片描述

  1. 在src目录下,创建一个com.xhh.po包,创建持久化类Student,与数据库字段对应

student.java

package com.xhh.po;

public class Student {
	private Integer id;
	private String name;
	private String age;
	private String sex;
	public Integer getId() {
		return id;
	}
	public void setId(Integer id) {
		this.id = id;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public String getAge() {
		return age;
	}
	public void setAge(String age) {
		this.age = age;
	}
	public String getSex() {
		return sex;
	}
	public void setSex(String sex) {
		this.sex = sex;
	}
	@Override
	public String toString() {
		return "Student [id=" + id + ", name=" + name + ", age=" + age + ", sex=" + sex + "]";
	}
	
}

  1. 在src目录下,创建com.xhh.mapper包,并在包中创建映射文件StudentMapper.xml
    文件中的约束配置在MyBatis使用手册中可以找到

在这里插入图片描述

在这里插入图片描述
StudentMapper.xml

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper  PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"  
	"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
	
<mapper namespace="com.xhh.mapper.StudentMapper">
	<select id="selectStudentById" parameterType="Integer" resultType="com.xhh.po.Student"> 
		select * from t_student where id = #{id}  
	</select>
</mapper>
  • namespace该属性为这个<mapper>指定了唯一的命名空间,通常会设置成包名+SQL映射文件名
  • <select>中的信息用于执行查询操作的配置,id属性是 <select>元素在映射文件中的唯一标识,parameterType属性用于指定传入的参数的类型,resultType属性用于指定返回结果的类型
  • #{id}表示该占位符待接收参数的名称为id
  1. 在src目录下,创建MyBatis的核心配置文件mybatis-config.xml
    同样在使用手册中也可以找到约束配置,它将配置分为两个步骤,第一步配置了环境,第二步配置了Mapper的位置

mybatis-config.xml

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration  PUBLIC "-//mybatis.org//DTD Config 3.0//EN"  
	"http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
	<properties resource="db.properties"></properties>
	<environments default="mariadb">
		<environment id="mariadb">
			<transactionManager type="JDBC" />
			<dataSource type="POOLED">
				<property name="driver" value="${jdbc.driver}" />
				<property name="url" value="${jdbc.url}" />
				<property name="username" value="${jdbc.username}" />
				<property name="password" value="${jdbc.password}" />
			</dataSource>
		</environment>
	</environments>
	<mappers>
		<mapper resource="com/xhh/mapper/StudentMapper.xml" />
	</mappers>
</configuration>

<properties resource="db.properties"></properties>
如上所示,可以创建在src目录下db.properties,将连接数据库的信息写在db.properties中,然后通过${}使用,它可以让我们更灵活的修改信息。

db.properties

jdbc.driver=org.mariadb.jdbc.Driver
jdbc.url=jdbc:mariadb://localhost:3306/mybatis
jdbc.username=root
jdbc.password=123456
  1. 在src目录下,创建com.xhh.test包,创建测试类DBTest,并编写测试方法
package com.xhh.test;

import java.io.IOException;
import java.io.InputStream;
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 com.xhh.po.Student;

public class DBTest {

	// id查找一个学生
	
	@Test
	public void findStudentById() throws IOException {
		// 1.读取配置文件
		String resource = "mybatis-config.xml";
		InputStream inputStream = Resources.getResourceAsStream(resource);

		// 2.根据配置文件构建SqlSessionFactory
		SqlSessionFactory build = new SqlSessionFactoryBuilder().build(inputStream);

		// 3.构建会话
		SqlSession sqlSession = build.openSession();
		
		Student student = sqlSession.selectOne("com.xhh.mapper.StudentMapper.selectStudentById",1);
		System.out.println(student.toString());
		sqlSession.close();
	}

	
}

结果:
在这里插入图片描述

  1. 因为MyBatis默认使用log4j输出日志信息,所以如果要查看控制台输出的SQL语句,那么就需要配置日志文件,在src中创建log4j.properties文件

文件的内容可以在刚才下载的mybatis中的pdf查看
在这里插入图片描述

创建的配置文件如下:

log4j.properties

# Global logging configuration
log4j.rootLogger=ERROR, stdout
# MyBatis logging configuration...
log4j.logger.com.xhh=DEBUG
# Console output...
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%5p [%t] - %m%n

其中log4j.logger.com.xhh=DEBUG用于将com.xhh包下所有类的日志级别设置为DEBUG

结果:
在这里插入图片描述

3. MyBatis进行增删改查

在入门程序的基础上

  1. 添加学生信息

在MyBatis的映射文件中,添加操作是通过<insert>元素来实现的,向t_student中插入一条数据,在StudentMapper.xml添加如下配置

<insert id="addStudent" parameterType="com.xhh.po.Student">
		insert into t_student(name,age,sex)
		values(#{name},#{age},#{sex})
</insert>

在测试类DBTest中,添加测试方法

	@Test
	public void addStudent() throws Exception {
		// 1.读取配置文件
		String resource = "mybatis-config.xml";
		InputStream inputStream = Resources.getResourceAsStream(resource);

		// 2.根据配置文件构建SqlSessionFactory
		SqlSessionFactory build = new SqlSessionFactoryBuilder().build(inputStream);

		// 3.构建会话
		SqlSession sqlSession = build.openSession();
		Student student = new Student();
		student.setName("赵五");
		student.setSex("男");
		student.setAge("20");
		int row = sqlSession.insert("com.xhh.mapper.StudentMapper.addStudent", student);
		if (row > 0) {
			System.out.println("添加" + row + "个学生成功");
		} else {
			System.out.println("添加失败");
		}
		sqlSession.commit();
		sqlSession.close();

	}

可以使用@Ignore添加在之前的测试方法上,这样就不会执行之前的测试方法。

发现这两个方法前3个步骤基本相同,所以可以写一个工具类,减少代码量

  • 在src中创建包com.xhh.util,创建MyBatisUtils类

MyBatisUtils.java

package com.xhh.util;

import java.io.IOException;
import java.io.Reader;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

public class MyBatisUtils {

	private static SqlSessionFactory sqlSessionFactory = null;
	static {
		try {
			Reader reader = Resources.getResourceAsReader("mybatis-config.xml");
			sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	public static SqlSession getSession() {
		return sqlSessionFactory.openSession();
	}
}

把前3个步骤改成: SqlSession sqlSession = MyBatisUtils.getSession();

  1. 删除学生信息

在MyBatis的映射文件中,删除操作是通过<delete>元素来实现的,在StudentMapper.xml添加如下配置

<delete id="deleteStudent" parameterType="Integer">
		delete from t_student where id = #{id}
</delete>

在测试类DBTest中,添加测试方法

	@Test
	public void deleteStudentById() {
		SqlSession sqlSession = MyBatisUtils.getSession();
		int row = sqlSession.delete("com.xhh.mapper.StudentMapper.deleteStudent", 3);
		if (row > 0) {
			System.out.println("删除一个学生成功");
		} else {
			System.out.println("删除失败");
		}
		sqlSession.commit();
		sqlSession.close();
	}
  1. 查询所有学生信息

跟查询一个学生信息基本相同,在StudentMapper.xml添加如下配置

<select id="selectStudentAll" resultType="com.xhh.po.Student">
		select * from t_student
</select>

编写测试方法

	@Test
	public void findStudentAll() {
		SqlSession sqlSession = MyBatisUtils.getSession();
		List<Student> students = sqlSession.selectList("com.xhh.mapper.StudentMapper.selectStudentAll");
		for (Student student : students) {
			System.out.println(student.toString());
		}
		sqlSession.close();
	}
  1. 更新学生信息

在MyBatis的映射文件中,更新操作是通过<update>元素来实现的,在StudentMapper.xml添加如下配置

<update id="updateStudent" parameterType="com.xhh.po.Student">
		update t_student set
		name = #{name},age = #{age},sex = #{sex}
		where id = #{id}
</update>

编写测试方法

	@Test
	// 更新学生信息
	public void updateStudent() {
		SqlSession sqlSession = MyBatisUtils.getSession();
		Student student = new Student();
		student.setId(3);
		student.setName("赵五");
		student.setSex("女");
		student.setAge("17");
		int row = sqlSession.update("com.xhh.mapper.StudentMapper.updateStudent", student);
		if (row > 0) {
			System.out.println("更新学生信息成功");
		} else {
			System.out.println("更新学生信息失败");
		}
		sqlSession.close();
	}

完成。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章