MyBatis快速上手
利用mybatis实现一个学生管理的增删改查
首先是配置文件
数据库连接配置文件
高版本大于5的数据库 连接时 需要加入时区
driver=com.mysql.cj.jdbc.Driver
url=jdbc:mysql://localhost:3306/db3?useUnicode=true&characterEncoding=gbk&useSSL=true&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=Hongkong
username=root
password=123456
日志文件配置
log4j.rootLogger=DEBUG, Console
#Console
log4j.appender.Console=org.apache.log4j.ConsoleAppender
log4j.appender.Console.layout=org.apache.log4j.PatternLayout
log4j.appender.Console.layout.ConversionPattern=5p [%t] - %m%n
mybatis配置映射文件
常规操作建立 对应的User封装类
MybatisConfig,xml
<!--DTD约束-->
<!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "http://mybatis.org/dtd/mybatis-3-config.dtd">
<!--核心跟标签-->
<configuration>
<!-- 引入数据库连接的配置文件-->
<properties resource="jdbc.properties"/>
<!-- 配置LOG4J-->
<settings>
<setting name="logImpl" value="log4j"/>
</settings>
<!-- 起别名 -->
<typeAliases>
<typeAlias type="bean.Student" alias="student"/>
<!-- 给这包下所有的类 起别名 别名就是这个类名 <package name="bean"/>-->
</typeAliases>
<!--集成分页助手插件-->
<plugins>
<plugin interceptor="com.github.pagehelper.PageHelper">
<!-- <property name="dialect" value="mysql"/>-->
<!-- <property name="reasonable" value="true" />-->
</plugin>
</plugins>
<!-- 和id保持对应 表示采用那个配置 配置数据库环境配置的 default 指定具体那个环境 id 唯一的标识-->
<environments default="mysql">
<environment id="mysql">
<!--采用JDBC的事务-->
<transactionManager type="JDBC"></transactionManager>
<!-- 数据源信息 代表数据库连接池-->
<dataSource type="POOLED">
<property name="driver" value="${driver}"/>
<property name="url" value="${url}"/>
<property name="username" value="${username}"/>
<property name="password" value="${password}"/>
</dataSource>
</environment>
</environments>
<!-- 引入映射配置文件-->
<mappers>
<!-- resource 属性指定映射配置文件的名称-->
<mapper resource="StudentMapper.xml"/>
</mappers>
</configuration>
在这里插入代码片
paging 一个分页的插件 用的是Pagehelper
package paging;
import bean.Student;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import mapper.StudentMapper;
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 java.io.InputStream;
import java.util.List;
// 通过mybatis 实现了 分页进行查询
// 分页的功能
// 对应的 分页sql语句 第一页 显示三条数据 当前页(当前页-1 * 每页显示条数) 每页显示条数
// SELECT * FROM student LIMIT 0,3
public class Test01 {
@Test
public void selectPaging() throws Exception{
InputStream is = Resources.getResourceAsStream("MybatisConfig.xml");
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(is);
// 相当于 一个 表单的提交
SqlSession sqlSession = sqlSessionFactory.openSession(true);
// 获取接口类 实现对象
StudentMapper mapper = sqlSession.getMapper(StudentMapper.class);
// 分页助手显示分页
// 分页可以将很多条结果 进行分页显示
// 第一页 显示三条数据
PageHelper.startPage(1,100); // 设置分页参数
List<Student> list = mapper.selectAll();
for (Student student : list) {
System.out.println(student);
}
// 获取分页参数 分页相关参数功能类
PageInfo info = new PageInfo<>(list);
System.out.println("总条数:"+info.getTotal());
System.out.println("总页数:"+info.getPages());
System.out.println("当前页:"+info.getPageNum());
System.out.println("每页显示条数:"+info.getPageSize());
sqlSession.close();
is.close();
}
}
对应的StudentMapper.xml
在这里插入代码片
```<?xml version="1.0" encoding="UTF-8"?>
<!--Mybatis的DTD的约束-->
<!DOCTYPE mapper PUBLIC "-//mybatis.org/DTD Mapper 3.0" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<!--mapper 核心标签-->
<!--namespace 名称空间-->
<mapper namespace="mapper.StudentMapper">
<!-- sql 语句的动态抽取 需要用得到的地方 就可以对其进行引用-->
<sql id="select">
SELECT * FROM student
</sql>
<!--
id属性 唯一标识 映射配置文件 映射路径 resultType 指定结果映射对象的类型
parameterType 指定参数映射对象类型
-->
<select id="selectAll" resultType="student">
<include refid="select"/>
</select>
<select id="selectById" resultType="student" parameterType="int">
<include refid="select"/> WHERE id=#{id}
</select>
<insert id="insert" parameterType="student">
INSERT INTO student VALUES (#{id},#{name},#{age})
</insert>
<update id="updata" parameterType="student">
UPDATE student SET name=#{name},age=#{age} WHERE id=#{id}
</update>
<delete id="delete" parameterType="java.lang.Integer">
DELETE FROM student WHERE id=#{id}
</delete>
<select id="selectCondition" resultType="student" parameterType="student">
<include refid="select"/>
-- where 标签 用来替换slq语句中的 where关键字的
-- 设置动态语句 进行使用多条件查询 动态sql
<where>
<if test="id != null">
id = #{id}
</if>
<if test="name != null">
AND name = #{name}
</if>
<if test="age != null">
AND age = #{age}
</if>
</where>
</select>
<!-- 这个list集合 存储需要查询的条件s-->
<select id="selectByIds" resultType="student" parameterType="list">
<include refid="select"/>
<where>
-- 循环遍历标签 适用于多个参数或者的关系
-- collection 参数类型容器
-- open 开始的sql语句
-- close 结束的SQL语句
-- item 参数变量名
-- separator 分隔符
<foreach collection="list" open="id IN(" close=")" item="id" separator=",">
#{id}
</foreach>
</where>
</select>
</mapper>
对应的service类 实现基本的增删改查
StudentServImpl
在这里插入代码片
package service.impl;
import bean.Student;
import mapper.StudentMapper;
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 service.StudentService;
import javax.annotation.Resource;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
// 业务层实现类
public class StudentServiceImpl implements StudentService {
@Test
@Override
public List<Student> selectAll() {
// 建立 存入的对象
List<Student> list =null;
SqlSession sqlSession = null;
InputStream is = null;
try {
// 调用对应的 配置文件
is = Resources.getResourceAsStream("MybatisConfig.xml");
// 获取对应的工厂对象 传递字节流对象
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(is);
sqlSession = sqlSessionFactory.openSession(true);
// 获取StudentMapper接口的实现类对象
// 相等于 StudentMapper mapper = new StudentMapperImpl();
// 获得这个接口的一个实现类 指定StudentMapper.class对象 从而得到一个实现类对象 mapper
StudentMapper mapper = sqlSession.getMapper(StudentMapper.class);
// 通过mapper 调用对应的selectAll方法
list = mapper.selectAll();
// 关闭流接口的操作
} catch (IOException e) {
e.printStackTrace();
}finally {
if(sqlSession != null){
sqlSession.close();
}
if(is != null){
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return list;
}
@Override
public Student selectById(Integer id) {
Student stu =null;
SqlSession sqlSession = null;
InputStream is = null;
try {
is = Resources.getResourceAsStream("MybatisConfig.xml");
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(is);
sqlSession = sqlSessionFactory.openSession(true);
// 获取StudentMapper接口的实现类对象
// 相等于 StudentMapper mapper = new StudentMapperImpl();
StudentMapper mapper = sqlSession.getMapper(StudentMapper.class);
stu = mapper.selectById(id);
} catch (IOException e) {
e.printStackTrace();
}finally {
if(sqlSession != null){
sqlSession.close();
}
if(is != null){
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return stu;
}
@Override
public Integer insert(Student stu) {
Integer rs =null;
SqlSession sqlSession = null;
InputStream is = null;
try {
is = Resources.getResourceAsStream("MybatisConfig.xml");
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(is);
sqlSession = sqlSessionFactory.openSession(true);
// 获取StudentMapper接口的实现类对象
// 相等于 StudentMapper mapper = new StudentMapperImpl();
StudentMapper mapper = sqlSession.getMapper(StudentMapper.class);
rs = mapper.insert(stu);
} catch (IOException e) {
e.printStackTrace();
}finally {
if(sqlSession != null){
sqlSession.close();
}
if(is != null){
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return rs;
}
@Override
public Integer updata(Student stu) {
Integer rs =null;
SqlSession sqlSession = null;
InputStream is = null;
try {
is = Resources.getResourceAsStream("MybatisConfig.xml");
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(is);
sqlSession = sqlSessionFactory.openSession(true);
// 获取StudentMapper接口的实现类对象
// 相等于 StudentMapper mapper = new StudentMapperImpl();
StudentMapper mapper = sqlSession.getMapper(StudentMapper.class);
rs = mapper.updata(stu);
} catch (IOException e) {
e.printStackTrace();
}finally {
if(sqlSession != null){
sqlSession.close();
}
if(is != null){
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return rs;
}
@Override
public Integer delete(Integer id) {
Integer rs =null;
SqlSession sqlSession = null;
InputStream is = null;
try {
is = Resources.getResourceAsStream("MybatisConfig.xml");
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(is);
sqlSession = sqlSessionFactory.openSession(true);
// 获取StudentMapper接口的实现类对象
// 相等于 StudentMapper mapper = new StudentMapperImpl();
StudentMapper mapper = sqlSession.getMapper(StudentMapper.class);
rs = mapper.delete(id);
} catch (IOException e) {
e.printStackTrace();
}finally {
if(sqlSession != null){
sqlSession.close();
}
if(is != null){
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return rs;
}
}
控制层 Studentcontller 进行整合 方法的调用 实现对数据库的增删改查
在这里插入代码片
package controller;
import bean.Student;
import org.junit.Test;
import service.StudentService;
import service.impl.StudentServiceImpl;
import java.util.List;
// 控制层测试类
public class StudenrContller {
// 创建业务层对象
private StudentService service = new StudentServiceImpl();
// 对应的Dao层 进行方法的调用 通过调用service 引入传入的mybatis的配置文件
// 调用对应的sql语句 查询数据库 将结果集合 进行返回
// 方法的抽取 进行封装
@Test
public void selectAll(){
List<Student> students = service.selectAll();
for (Student stu : students) {
System.out.println(stu);
}
}
@Test
public void selectById(){
Student stu = service.selectById(2);
System.out.println(stu);
}
@Test
public void insert(){
Student stu = new Student(2,"宋二",42);
Integer rs = service.insert(stu);
System.out.println(rs);
}
@Test
public void delete(){
Integer rs = service.delete(2);
System.out.println(rs);
}
@Test
public void updata(){
Student stu = new Student(7,"杜大",22);
int rs = service.updata(stu);
System.out.println(rs);
}
}
查询功能的展示
分页插件的展示
分页历来都是属于难点(个人看法) 。