mybatis实现CRUD详解(使用mapper映射文件实现增删改查)
创建maven项目:项目结构如图所示
准备数据库表:
准备pom.xml所需的依赖:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.etime</groupId>
<artifactId>day09</artifactId>
<version>1.0-SNAPSHOT</version>
<properties>
<maven.compiler.source>8</maven.compiler.source>
<maven.compiler.target>8</maven.compiler.target>
</properties>
<dependencies>
<!-- 添加lombok依赖工具使用其中的注解方法可以让实体类中get,set,以及实体类中操作少一些-->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.16</version>
</dependency>
<!-- 添加和引入mybatis的版本号等依赖-->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.5.1</version>
</dependency>
<!-- 这里添加mysql依赖-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.11</version>
<scope>runtime</scope>
</dependency>
<!-- 如果不需要也可不进行单元测试的依赖引入-->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
</dependencies>
</project>
编写核心配置文件加载所需要的资源
编写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>
<!-- 配置 mybatis的环境-->
<environments default="development">
<!-- 配置环境-->
<environment id="development">
<!-- 配置事物类型-->
<transactionManager type="JDBC"></transactionManager>
<!-- 配置连接数据库的信息:用的是数据源[连接池]-->
<dataSource type="POOLED">
<property name="driver" value="com.mysql.cj.jdbc.Driver"/>
<!-- jdbc:mysql://localhost:3306/db_school?useUnicode=true&characterEncoding=utf-8&useSSL=false&serverTimezone=UTC-->
<!-- 和javaWeb servlet三层架构中的区别这里是只需要设置时区就可以了-->
<property name="url" value="jdbc:mysql://localhost:3306/db_school?serverTimezone=UTC"/>
<property name="username" value="root"/>
<property name="password" value="h123456"/>
</dataSource>
</environment>
</environments>
<!-- 注册StudentDao接口映射文件位置-->
<mappers>
<mapper resource="mapper/StudentMapper.xml"/>
</mappers>
</configuration>
创建工厂连接数据处理工具SqlSessionUtil.java
SqlSessionUtil.java
package com.etime.util;
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 java.io.IOException;
import java.io.InputStream;
public class SqlSessionUtil {
private static SqlSession sqlSession =null;
static {
//加载配置文件
InputStream inputStream = null;
try {
inputStream = Resources.getResourceAsStream("config.xml");
} catch (IOException e) {
e.printStackTrace();
}
//用于读取配置文件内容,生成SqlSessionFactory
SqlSessionFactoryBuilder sqlSessionFactoryBuilder = new SqlSessionFactoryBuilder();
SqlSessionFactory sqlSessionFactory = sqlSessionFactoryBuilder.build(inputStream);
//获取SqlSession对象
sqlSession = sqlSessionFactory.openSession();
}
public SqlSession getSqlSession(){
return sqlSession;
}
}
创建学生实体类对象Student.java
package com.etime.pojo;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
//添加无参构造函数
@NoArgsConstructor
//添加全参数构造函数
@AllArgsConstructor
//添加所有需要的get,set等方法
@Data
public class Student {
private int sid;
private String sname;
private String sgender;
private int sage;
private String semail;
private String sphoto;
}
实现增、删、改、查
1、查询所有学生信息:
创建接口StudentDao.java:向其中添加查询所有学生信息
package com.etime.dao;
import com.etime.pojo.QueryVo;
import com.etime.pojo.Student;
import java.util.List;
import java.util.Map;
public interface StudentDao {
//查询所有学生信息
List<Student> getAllStudents();
}
创建StudentMapper.xml文件编写sql映射
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">
<!--namespace是当前mapper对应的dao接口-->
<mapper namespace="com.etime.dao.StudentDao">
<!-- select指定当前进行数据库操作的是查询-->
<!-- id的值对应的是当前dao层接口中的方法名字-->
<!-- resultType指定当前查询得到的数据要封装成的类型-->
<select id="getAllStudents" resultType="com.etime.pojo.Student">
select * from student
</select>
</mapper>
编写MybatisTest.java文件编写测试方法:因在上述中已经将SqlSession的操作提成一个工具类所以测试类中就不需要再些SqlSession.java的部分操作,只需要在测试类中创建 该类对象,进行引用
package com.etime.test;
import com.etime.dao.StudentDao;
import com.etime.pojo.QueryVo;
import com.etime.pojo.Student;
import com.etime.pojo.Teacher;
import com.etime.util.SqlSessionUtil;
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 org.junit.experimental.theories.suppliers.TestedOn;
import javax.annotation.Resource;
import java.io.IOException;
import java.io.InputStream;
import java.util.*;
import java.util.stream.Collectors;
public class MybatisTest {
SqlSessionUtil sqlSessionUtil = new SqlSessionUtil();
//查询所有学生信息
@Test
public void t01(){
SqlSession sqlSession = sqlSessionUtil.getSqlSession();
//获取StudentDao对象
StudentDao studentDao = sqlSession.getMapper(StudentDao.class);
//调用方法获取结果
List<Student> list = studentDao.getAllStudents();
for (Student student:list
) {
System.out.println(student);
}
sqlSession.close();
}
}
运行结果:
2、实现对学生进行信息添加
向StudentDao.java接口中添加学生方法:
//添加学生
int addStudent(Student student);
向StudentMapper.xml映射文件中添加添加学生的sql映射
<insert id="addStudent" parameterType="com.etime.pojo.Student">
insert into student(sname,sage,sgender,semail,sphoto) values (#{sname},#{sage},#{sgender},#{semail},#{sphoto});
</insert>
向测试类中编写添加学生信息方法:
//添加学生
@Test
public void t02() throws IOException {
SqlSession sqlSession = sqlSessionUtil.getSqlSession();
StudentDao studentDao = sqlSession.getMapper(StudentDao.class);
int rows = studentDao.addStudent(new Student(0,"阿坤","男",18,"shhfifw@qq.com","djia.jpg"));
System.out.println(rows);
//SqlSession在做增删改操作时,需要手动提交
sqlSession.commit();
sqlSession.close();
}
运行结果:
3、根据学生id删除学生信息
向StudentDao.java接口中添加根据学生id删除学生信息
//根据学生id删除学生信息
int delStudent(int sid);
向StudentMapper.xml映射文件中添加根据学生id删除学生信息sql映射
<delete id="delStudent" parameterType="int">
delete from student where sid=#{sid}
</delete>
向测试类中MybatisTest.java中编写根据学生id删除学生信息sql映射
//根据学生id删除学生
@Test
public void t03(){
SqlSession sqlSession = sqlSessionUtil.getSqlSession();
StudentDao studentDao = sqlSession.getMapper(StudentDao.class);
int rows = studentDao.delStudent(34);
System.out.println(rows);
//SqlSession在做增删改操作时,需要手动提交
sqlSession.commit();
sqlSession.close();
}
运行结果:
4、更新学生信息
向StudentDao.java接口中编写修改学生信息方法
//更新学生信息
int updateStudent(Student student);
向映射文件StudentMapper.xml文件中添加学生信息更新sql映射
<update id="updateStudent" parameterType="com.etime.pojo.Student">
update student set sname=#{sname},sage=#{sage},sgender=#{sgender},semail=#{sphoto}
</update>
向测试类中编写测试学生信息更新的方法
//根据学生id更新学生信息
@Test
public void t04(){
SqlSession sqlSession = sqlSessionUtil.getSqlSession();
StudentDao studentDao = sqlSession.getMapper(StudentDao.class);
int rows = studentDao.updateStudent(new Student(12,"坤坤","男",19,"djwoie@qq.com","dag.jpg"));
System.out.println(rows);
//SqlSession在做增删改操作时,需要手动提交
sqlSession.commit();
sqlSession.close();
}
运行结果:
5、根据学生id获取学生信息
向StudentDao.java中编写根据学生id获取学生信息的方法
//根据学生id获取学生信息
Student getStuBySid(int sid);
向映射文件StudentMapper.xml中编写根据学生id获取学生信息
<select id="getStuBySid" parameterType="int" resultType="com.etime.pojo.Student">
select * from student where sid=#{sid}
</select>
向测试文件中编写根据学生id获取学生信息
//根据学生id获取学生信息
@Test
public void t05(){
SqlSession sqlSession = sqlSessionUtil.getSqlSession();
StudentDao studentDao = sqlSession.getMapper(StudentDao.class);
Student student = studentDao.getStuBySid(33);
System.out.println(student);
sqlSession.close();
}
运行结果:
6、获取学生表中的所有数据条数
向StudentDao.java接口中编写查询所有数据条数方法
//获取学生数据条数
int getCountRows();
向映射文件中编写查询获取学生数据条数的sql映射
<select id="getCountRows" resultType="int">
select count(*) from student
</select>
向测试类MybatisTest.java中编写查询所有学生数据条数的测试方法
//获取学生表的所有数据条数
@Test
public void t06(){
SqlSession sqlSession = sqlSessionUtil.getSqlSession();
StudentDao studentDao = sqlSession.getMapper(StudentDao.class);
int rows=studentDao.getCountRows();
System.out.println(rows);
sqlSession.close();
}
运行结果: