MyBatis--3.实现CRUD

354 阅读4分钟

​ 本章的内容是在前一篇文章的基础上添加的,如果有不懂的可以先看一下上一篇的内容《MyBatis的第一个程序》。本章具体的内容是使用MyBatis实现对Student的增删改查。

目录结构:

1572569882976

​ 在上一章时我们插入数据时需要在StudentDaoImpl中添加以下的代码

	private SqlSession sqlSession;

	@Override
	public void insertStudent(Student student) {
		try {
			InputStream inputStream = Resources.getResourceAsStream("mybatis.xml");
			SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
			sqlSession = sqlSessionFactory.openSession();
			sqlSession.insert("insertStudent", student);
			sqlSession.commit();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if (sqlSession != null) {
				sqlSession.close();
			}
		}
	}

​ 不难发现,如果我们想要进行增删改查的话,就每次都要去实例化一个SQLSession对象,然后调用对应的方法,再将SQLSession提交后关闭,很明显真正起作用的代码只有一句sqlSession.insert("insertStudent", student);,这样就显得我们的代码不够简洁,所以 我们使用一个工具类,将获取SQLSession和提交关闭的操作封装在其中,需要的时候直接调用就行了;

public class SqlSessionUtil {
	private static SqlSession sqlSession;
	private static SqlSessionFactory sqlSessionFactory = null;
	public static SqlSession getSqlSession(){
		try {
			//3.通过读取主配置文件获取输入流
			InputStream inputStream = Resources.getResourceAsStream("mybatis.xml");
			if(sqlSessionFactory == null){
				sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
			}
			//1.sqlSession是通过SqlSessionFactory创建的
			sqlSession = sqlSessionFactory.openSession();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return sqlSession;
	}
	public static void closeSqlSession(SqlSession sqlSession){
		sqlSession.commit();
		if (sqlSession != null) {
			sqlSession.close();
		}
	}
}

​ 编写好工具类后,我们在StudentDaoImpl中的insertStudent方法就可以更改成以下的代码就可以了;这样一相比,我们的代码就更加简洁明了。

	@Override
	public void insertStudent(Student student) {
		sqlSession = SqlSessionUtil.getSqlSession();
		sqlSession.insert("insertStudent", student);
		SqlSessionUtil.closeSqlSession(sqlSession);
	}
接下来就开始实现对Student的增删改查
1.修改StudentDao
public interface StudentDao {
	void insertStudent(Student student);
	void insertStudenCacheId(Student student);
	void delectStudentById(int id);
	void updateStudent(Student student);
	List<Student> selectAllStudent();
	Student selectStudentById(int id);
	List<Student> selectStudentByStudentName(String name);
}
2.修改StudentDaoImpl
package com.mybatis.dao;

import java.util.List;

import org.apache.ibatis.session.SqlSession;

import com.mybatis.beans.Student;
import com.mybatis.utils.SqlSessionUtil;

public class StudentDaoImpl implements StudentDao {

	private SqlSession sqlSession;
	
	@Override
	public void insertStudent(Student student) {
		sqlSession = SqlSessionUtil.getSqlSession();
		sqlSession.insert("insertStudent", student);
		SqlSessionUtil.closeSqlSession(sqlSession);
	}
	//将student插入到数据库之后将该student的id重新返回到student中
    //这是上一个方法insertStudent无法实现的
	@Override
	public void insertStudenCacheId(Student student) {
		sqlSession = SqlSessionUtil.getSqlSession();
		sqlSession.insert("insertStudentCacheId", student);
		SqlSessionUtil.closeSqlSession(sqlSession);
	}
	
	@Override
	public void delectStudentById(int id) {
		sqlSession = SqlSessionUtil.getSqlSession();
		sqlSession.delete("delectStudentById", id);
		SqlSessionUtil.closeSqlSession(sqlSession);
	}

	@Override
	public void updateStudent(Student student) {
		sqlSession = SqlSessionUtil.getSqlSession();
		sqlSession.update("updateStudent", student);
		SqlSessionUtil.closeSqlSession(sqlSession);
	}

	@Override
	public List<Student> selectAllStudent() {
		List<Student> studentList = null;
		sqlSession = SqlSessionUtil.getSqlSession();
		studentList = sqlSession.selectList("selectAllStudent","");
		SqlSessionUtil.closeSqlSession(sqlSession);
		return studentList;
	}

	@Override
	public Student selectStudentById(int id) {
		Student student = null;
		sqlSession = SqlSessionUtil.getSqlSession();
		student = sqlSession.selectOne("selectStudentById", id);
		SqlSessionUtil.closeSqlSession(sqlSession);
		return student;
	}
	//该功能实现的是模糊查询,根据传入的name,将包含该name的记录查找出来
	@Override
	public List<Student> selectStudentByStudentName(String name) {
		List<Student> studentList = null;
		sqlSession = SqlSessionUtil.getSqlSession();
		studentList = sqlSession.selectList("selectStudentByName", name);
		SqlSessionUtil.closeSqlSession(sqlSession);
		return studentList;
	}

}

3.修改mapper.xml,在编写SQL语句时,可以在数据库中先使用对应的SQL语句进行测试一下,以防止代码写错;
<!DOCTYPE mapper
 PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
 "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="xxx">
	<insert id="insertStudent" parameterType="com.mybatis.beans.Student">
		INSERT INTO student(name,age,score) VALUES(#{name},#{age},#{score})
	</insert>
	<insert id="insertStudentCacheId">
		INSERT INTO student(name,age,score) VALUES(#{name},#{age},#{score})
		<selectKey resultType="int" keyProperty="id"  order="AFTER">
			select @@Identity
		</selectKey>
	</insert>
	<delete id="delectStudentById" parameterType="int">
		DELETE FROM student WHERE id = #{id}
	</delete>
	<update id="updateStudent">
		UPDATE student SET name=#{name},age=#{age},score=#{score} WHERE id = #{id}
	</update>
	<select id="selectAllStudent" resultType="com.mybatis.beans.Student">
		select id,name,age,score from student
	</select>
	<select id="selectStudentById" resultType="com.mybatis.beans.Student">
		select id,name,age,score from student where id=#{id}
	</select>
	<select id="selectStudentByName" resultType="com.mybatis.beans.Student">
		select id,name,age,score from student where name like '%' #{name} '%'
	</select>
</mapper>

在数据库中测试时insertStudentCacheId的SQL语句时需要注意的问题

/*第一行的代码后面必须要有";",因为第二行的代码需要在第一行的代码执行后才起作用,所以第一行代码必须马上执行*/
INSERT INTO student(name,age,score) VALUES("张三",23,94.5);
SELECT @@Identity
4.修改StudentDaoTest,这里使用了@Ignore这个注解,它的作用是忽视掉对应@Test的,这样做的目的是为了让其他的操作不会干扰到当前所需要测试的操作,如果你的当前测试不需要借助其他测试的内容,可以先将其他的测试用例@Ignore掉。
package com.mybatis.test;

import java.util.List;

import org.junit.Ignore;
import org.junit.Test;

import com.mybatis.beans.Student;
import com.mybatis.dao.StudentDao;
import com.mybatis.dao.StudentDaoImpl;

public class TestStudentDao {
	private StudentDao dao = new StudentDaoImpl();
	@Test
	public void testInsertStudent(){
		Student student = new Student("张三",23,93.5);
		dao.insertStudent(student);
	}
	@Test
	@Ignore
	public void testInsertStudentCacheId(){
		Student student = new Student("张三",23,93.5);
		System.out.println("插入之前的student: "+ student);
		dao.insertStudenCacheId(student);
		System.out.println("插入之后的student: " + student);
	}
	@Test
	@Ignore
	public void testDelectStudentById(){
		dao.delectStudentById(19);
	}
	@Test
	@Ignore
	public void testUpdateStudent(){
		Student student = new Student("王五",22,94.5);
		student.setId(20);
		dao.updateStudent(student);
	}
	@Test
	@Ignore
	public void testSelectAllStudent(){
		List<Student> studentList = dao.selectAllStudent();
		for (Student student : studentList) {
			System.out.println(student);
		}
	}
	@Test
	@Ignore
	public void testSelectStudentById(){
		Student student = dao.selectStudentById(20);
		System.out.println(student);
	}
	@Test
	public void testSelectStudentByName(){
		List<Student> studentList = dao.selectStudentByStudentName("张");
		for (Student student : studentList) {
			System.out.println(student);
		}
	}
}