目录
Mybatis基础+增删改查(代码示例)
首先什么是MyBatis?
MyBatis中文文档(学习参考资料):
MyBatis 基础框架搭建源码:
MyBatis 基础框架详解:
项目基本结构:
项目依赖:
数据库配置文件(dp.properties):
日志配置文件(log4j.properties):
Mybatis核心配置文件:
(POJO)实体类Blog:
(POJO)实体类Student:
(POJO)实体类Teacher:
(POJO)实体类User:
Mybatis核心配置文件解析工具:
UUID生成器(全局唯一ID生成器):
UserMapper.java 接口(增删改查CRUD):
UserMapper.xml对应接口的SQL信息:
StudentMapper.java 接口:
StudentMapper.xml对应接口的SQL信息:
TeacherMapper.java 接口:
TeacherMapper.xml对应接口的SQL信息:
BlogMapper.java 接口:
BlogMapper.xml对应接口的SQL信息:
StudentAnnotationMapper.java 接口:
UserMapperTest 测试代码:(此处采用 Junit 进行查询,没有用到Spring注解的单测)
UserMapperTest.java
StudentMapperTest 测试代码:(此处采用 Junit 进行查询,没有用到Spring注解的单测)
StudentMapperTest.java
StudentAnnotationMapperTest 测试代码:(此处采用 Junit 进行查询,没有用到Spring注解的单测)
StudentAnnotationMapperTest.java
TeacherMapperTest 测试代码:(此处采用 Junit 进行查询,没有用到Spring注解的单测)
TeacherMapperTest.java
BlogMapperTest测试代码:(此处采用 Junit 进行查询,没有用到Spring注解的单测)
BlogMapperTest.java
MyBatis 是一流的持久性框架,支持自定义 SQL、存储过程和高级映射。MyBatis 消除了几乎所有的 JDBC 代码和手动设置参数和检索结果。MyBatis 可以使用简单的 XML 或 Annotations 进行配置和映射原语、映射接口和 Java POJO(普通旧 Java 对象)到数据库记录。
mybatis – MyBatis 3 | Introduction
https://gitee.com/aaron1996/mybatis
RocketDemo
org.cainiao
1.0-SNAPSHOT
4.0.0
demo-mybatisJDBC
org.springframework.boot
spring-boot-starter
org.springframework.boot
spring-boot-starter-test
test
org.projectlombok
lombok
1.18.22
provided
org.mybatis
mybatis
3.5.2
junit
junit
4.12
mysql
mysql-connector-java
5.1.46
log4j
log4j
1.2.17
org.jetbrains
annotations
RELEASE
compile
src/main/resources
**/*.properties
**/*.xml
true
src/main/java
**/*.properties
**/*.xml
true
注意:父pom.xml文件中还有:
driver=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/test?useSSL=true&useUnicode=true&characterEncoding=UTF-8
username=root
password=root123456
# log配置文件如下可以在任意项目中使用,属于可以写死的代码
# 将等级为DEBUG的日志信息输出到console和file这两个目的地
log4j.rootLogger=DEBUG,console,file
# 控制台输出的相关设置
log4j.appender.console=org.apache.log4j.ConsoleAppender
log4j.appender.console.Target=System.out
log4j.appender.console.Threshold=DEBUG
log4j.appender.console.layout=org.apache.log4j.PatternLayout
log4j.appender.console.layout.ConversionPattern=[%c]-%m%n
# 文件输出的相关设置
log4j.appender.file=org.apache.log4j.RollingFileAppender
log4j.appender.file.File=./log/log.log
log4j.appender.file.MaxFileSize=10mb
log4j.appender.file.Threshold=DEBUG
log4j.appender.file.layout=org.apache.log4j.PatternLayout
log4j.appender.file.layout.ConversionPattern=[%p][%d{yy-mm-dd}][%c]%m%n
# 日志输出级别
log4j.logger.org.mybatis=DEBUG
log4j.logger.java.sql=DEBUG
log4j.logger.java.sql.Statement=DEBUG
log4j.logger.java.sql.ResultSet=DEBUG
log4j.logger.java.sql.PreparedStatement=DEBUG
package com.cainiao.pojo;
import java.util.Date;
public class Blog {
private String id;
private String title;
private String author;
private Date createTime;
private String views;
public Blog() {
}
public Blog(String id, String title, String author, Date createTime, String views) {
this.id = id;
this.title = title;
this.author = author;
this.createTime = createTime;
this.views = views;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getAuthor() {
return author;
}
public void setAuthor(String author) {
this.author = author;
}
public Date getCreateTime() {
return createTime;
}
public void setCreateTime(Date createTime) {
this.createTime = createTime;
}
public String getViews() {
return views;
}
public void setViews(String views) {
this.views = views;
}
@Override
public String toString() {
return "Blog{" +
"id='" + id + '\'' +
", title='" + title + '\'' +
", author='" + author + '\'' +
", createTime=" + createTime +
", views='" + views + '\'' +
'}';
}
}
package com.cainiao.pojo;
public class Student {
private Long sid;
private String sname;
private Byte sage;
private String smaster;
private Teacher teacher;
public Student() {
}
public Student(Long sid, String sname, Byte sage, String smaster, Teacher teacher) {
this.sid = sid;
this.sname = sname;
this.sage = sage;
this.smaster = smaster;
this.teacher = teacher;
}
public Long getSid() {
return sid;
}
public void setSid(Long sid) {
this.sid = sid;
}
public String getSname() {
return sname;
}
public void setSname(String sname) {
this.sname = sname;
}
public Byte getSage() {
return sage;
}
public void setSage(Byte sage) {
this.sage = sage;
}
public String getSmaster() {
return smaster;
}
public void setSmaster(String smaster) {
this.smaster = smaster;
}
public Teacher getTeacher() {
return teacher;
}
public void setTeacher(Teacher teacher) {
this.teacher = teacher;
}
@Override
public String toString() {
return "Student{" +
"sid=" + sid +
", sname='" + sname + '\'' +
", sage=" + sage +
", smaster='" + smaster + '\'' +
", teacher=" + teacher +
'}';
}
}
package com.cainiao.pojo;
import lombok.AllArgsConstructor;
import lombok.Data;
import java.util.List;
public class Teacher {
private String master;
private Integer tage;
private String tmajor;
private List studentList;
public Teacher() {
}
public Teacher(String master, Integer tage, String tmajor, List studentList) {
this.master = master;
this.tage = tage;
this.tmajor = tmajor;
this.studentList = studentList;
}
public String getMaster() {
return master;
}
public void setMaster(String master) {
this.master = master;
}
public Integer getTage() {
return tage;
}
public void setTage(Integer tage) {
this.tage = tage;
}
public String getTmajor() {
return tmajor;
}
public void setTmajor(String tmajor) {
this.tmajor = tmajor;
}
public List getStudentList() {
return studentList;
}
public void setStudentList(List studentList) {
this.studentList = studentList;
}
@Override
public String toString() {
return "Teacher{" +
"master='" + master + '\'' +
", tage=" + tage +
", tmajor='" + tmajor + '\'' +
", studentList=" + studentList +
'}';
}
}
package com.cainiao.pojo;
public class User {
private Integer id;
private String userName;
private String userAge;
private String userAddress;
public User() {
}
public User(Integer id, String userName, String userAge, String userAddress) {
this.id = id;
this.userName = userName;
this.userAge = userAge;
this.userAddress = userAddress;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getUserAge() {
return userAge;
}
public void setUserAge(String userAge) {
this.userAge = userAge;
}
public String getUserAddress() {
return userAddress;
}
public void setUserAddress(String userAddress) {
this.userAddress = userAddress;
}
@Override
public String toString() {
return "User{" +
"id=" + id +
", userName='" + userName + '\'' +
", userAge='" + userAge + '\'' +
", userAddress='" + userAddress + '\'' +
'}';
}
}
package com.cainiao.utils;
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 MybatisUtils {
private static SqlSessionFactory sqlSessionFactory;
static {
try {
String resource = "mybatis-config.xml";
InputStream inputStream = Resources.getResourceAsStream(resource);
sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
} catch (IOException e) {
e.printStackTrace();
}
}
public static SqlSession getSqlSession(){
// 这里设置autoCommit=true,可自动提交,不同在提交中,手动sqlSession.commit;
return sqlSessionFactory.openSession(true);
}
}
package com.cainiao.utils;
import org.junit.Test;
import java.util.UUID;
public class IdUtils {
public static String getId(){
return UUID.randomUUID().toString().replaceAll("-", "");
}
@Test
public void test(){
System.out.println(getId());
}
}
注意:凡是基本类型前面都需要加上@Param()方法,开发规范;引用类型可不用@Param()方法;
内容:基于 User 实现了
(1)查询所有用户;
(2)根据用户Id进行查询;
(3)根据用户 name 进行模糊查询(此处用 concat() 进行字符串拼接,防止SQL注入);
(4)添加用户;
(5)企业级:如果实体类属性过多,可以考虑使用map进行数据库插入操作@param map
(6)根据用户id 删除用户;
(7)根据用户id 修改用户信息;
package com.cainiao.mapper;
import com.cainiao.pojo.User;
import org.apache.ibatis.annotations.Param;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public interface UserMapper {
/**
* 查询所有用户 (查)
* @return
*/
List getUserList();
/**
* 根据用户Id进行查询 (查)
* @param id
* @return
*/
User selectUserById(@Param("id") int id);
/**
* 根据用户 name 进行模糊查询 (查)
* @param name
* @return
*/
List selectUserByLike(@Param("name") String name);
/**
* 添加用户 (增)
* @param user
*/
void addUser(User user);
/**
* 企业级:如果实体类属性过多, (增)
* 可以考虑使用map进行
* 数据库插入操作
* @param map
*/
void addUserByMap(Map map);
/**
* 根据用户id 删除用户 (删)
* @param id
*/
void deleteUser(@Param("id") int id);
/**
* 根据用户id 修改用户信息 (改)
* @param user
*/
void updateUser(User user);
}
insert into user values(#{id},#{userName},#{userAge},#{userAddress})
insert into user(id, userName, userAddress) values(#{defineId},#{defineUserName},#{defineUserAddress})
delete from user where id=#{id};
update user set userName=#{userName},userAge=#{userAge},userAddress=#{userAddress} where id=#{id};
注意:凡是基本类型前面都需要加上@Param()方法,开发规范;引用类型可不用@Param()方法;
内容:基于 Student实现了
(1)基于简单
(2)分页查询;(实质上为 SQL语句 ---- limit)
package com.cainiao.mapper;
import com.cainiao.pojo.Student;
import org.apache.ibatis.annotations.Param;
import java.util.List;
import java.util.Map;
public interface StudentMapper {
/**
* 此处采用 resultMap 来进行查询
* @return
*/
List selectAllStudent();
/**
* 分页
* @param map
* @return
*/
List selectStudentByPage(Map map);
}
注意:凡是基本类型前面都需要加上@Param()方法,开发规范;引用类型可不用@Param()方法;
内容:基于 Teacher 实现了
(1)“多对一” 联表查询;
(2)“一对多” 联表查询;
package com.cainiao.mapper;
import com.cainiao.pojo.Student;
import com.cainiao.pojo.Teacher;
import java.util.List;
public interface TeacherMapper {
/**
* 通过 联表 查询学生和老师所有信息 (多对一)
* @return
*/
List getStuTeaInfo();
/**
* 通过 联表 查询老师和学生所有信息 (一对多)
* @return
*/
List getTeaStuInfo();
}
注意:凡是基本类型前面都需要加上@Param()方法,开发规范;引用类型可不用@Param()方法;
内容:基于 Blog 实现了
(1)插入 Blog 数据;
(2)采用 动态SQL
(3)使用 动态SQL
(4) 采用 动态SQL
(5)使用
package com.cainiao.mapper;
import com.cainiao.pojo.Blog;
import java.util.List;
import java.util.Map;
public interface BlogMapper {
/**
* 插入 Blog 数据
* @param blog
*/
void addBlog(Blog blog);
/**
* 采用 动态SQL 进行查询
* @return
*/
List selectBlogIF(Map map);
/**
* 使用 动态SQL 进行对属性有选择地执行 SQL语句
* @param map
* @return
*/
List selectBlogCHOOSE(Map map);
/**
* 采用 动态SQL 进行更新 blog表
* @param blog
*/
void updateBlog(Blog blog);
/**
* 使用 foreach 进行 动态SQL 查询
* @param map
* @return
*/
List selectBlogFOREACH(Map map);
}
insert into blog (id, title, author, create_time, views)
values(#{id}, #{title}, #{author}, #{createTime}, #{views})
update blog
title=#{title},
author=#{author},
views=#{views}
id=#{id}
注意:此处没有采用常规的 XXX.xml 文件进行数据库数据访问,
采用 注解 的方式进行数据库查询@Select;
简单查询 可以使用注解进行查询;复杂数据库查询操作 还是需要采用xml文件进行编写查询;
package com.cainiao.annotationMapper;
import com.cainiao.pojo.Student;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;
public interface StudentAnnotationMapper {
/**
* 使用注解进行 =简单= 的查询操作
* 注意:使用注解需要保证 实体类属性 一一对应 数据库字段
* @param sid
* @return
*/
@Select("select * from student where sid=#{sid}")
Student selectStudentByIdAno(@Param("sid") long sid);
}
package com.cainiao.mapper;
import com.cainiao.pojo.User;
import com.cainiao.utils.MybatisUtils;
import org.apache.ibatis.session.SqlSession;
import org.junit.jupiter.api.Test;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import static org.junit.jupiter.api.Assertions.*;
public class UserMapperTest {
@Test
void getUserListTest() {
SqlSession sqlSession = MybatisUtils.getSqlSession();
UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
List userList = userMapper.getUserList();
for (User user : userList) {
System.out.println(user.getId() + "\t" + user.getUserName() + "\t" +
user.getUserAge() + "\t" + user.getUserAddress());
}
sqlSession.close();
}
@Test
void selectUserByIdTest() {
SqlSession sqlSession = MybatisUtils.getSqlSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
User user = mapper.selectUserById(1);
System.out.println(user.getId() + "\t" + user.getUserName() + "\t" +
user.getUserAge() + "\t" + user.getUserAddress());
sqlSession.close();
}
@Test
void addUserTest() {
SqlSession sqlSession = MybatisUtils.getSqlSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
User user = new User();
user.setUserName("Aaron1");
user.setUserAge("20");
user.setUserAddress("Chongqing");
mapper.addUser(user);
// 注意:增删改都需要事务提交
sqlSession.commit();
sqlSession.close();
}
@Test
void deleteUser() {
SqlSession sqlSession = MybatisUtils.getSqlSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
mapper.deleteUser(8);
System.out.println("成功删除用户");
sqlSession.commit();
sqlSession.close();
}
@Test
void updateUser() {
SqlSession sqlSession = MybatisUtils.getSqlSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
User user = new User();
user.setId(9);
user.setUserName("Aaron2");
user.setUserAge("50");
user.setUserAddress("Shiniapan");
mapper.updateUser(user);
// 增删改:都必须进行事务提交
sqlSession.commit();
sqlSession.close();
}
@Test
void addUserByMap() {
SqlSession sqlSession = MybatisUtils.getSqlSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
Map map = new HashMap<>();
map.put("defineUserName", "User1");
map.put("defineUserAddress", "Wenquancheng");
mapper.addUserByMap(map);
sqlSession.commit();
sqlSession.close();
}
@Test
void selectUserByLike() {
SqlSession sqlSession = MybatisUtils.getSqlSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
List userList = mapper.selectUserByLike("Aaron");
for (User user : userList) {
System.out.println(user.getId() + "\t" + user.getUserName() + "\t" +
user.getUserAge() + "\t" + user.getUserAddress());
}
sqlSession.close();
}
}
package com.cainiao.mapper;
import com.cainiao.pojo.Student;
import com.cainiao.utils.MybatisUtils;
import org.apache.ibatis.session.SqlSession;
import org.apache.log4j.Logger;
import org.junit.jupiter.api.Test;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import static org.junit.jupiter.api.Assertions.*;
class StudentMapperTest {
@Test
void selectAllStudentTest() {
SqlSession sqlSession = MybatisUtils.getSqlSession();
StudentMapper mapper = sqlSession.getMapper(StudentMapper.class);
List students = mapper.selectAllStudent();
for (Student student : students) {
System.out.println(student.getSid() + "\t"
+ student.getSname() + "\t" + student.getSage()
+ "\t" + student.getSmaster() + "\t" + student.getTeacher());
}
sqlSession.close();
}
@Test
void testLogger(){
Logger logger = Logger.getLogger(StudentMapperTest.class);
logger.info("成功进入info级别");
logger.debug("成功进入debug级别");
logger.error("成功进入error级别");
}
/**
* 测试分页
*/
@Test
void selectStudentByPage() {
SqlSession sqlSession = MybatisUtils.getSqlSession();
StudentMapper mapper = sqlSession.getMapper(StudentMapper.class);
Map map = new HashMap<>();
map.put("startPage", 0);
map.put("pageSize", 2);
List students = mapper.selectStudentByPage(map);
for (Student student : students) {
System.out.println(student.getSid() + "\t"
+ student.getSname() + "\t" + student.getSage()
+ "\t" + student.getSmaster());
}
sqlSession.close();
}
}
package com.cainiao.mapper;
import com.cainiao.annotationMapper.StudentAnnotationMapper;
import com.cainiao.pojo.Student;
import com.cainiao.utils.MybatisUtils;
import org.apache.ibatis.session.SqlSession;
import org.junit.jupiter.api.Test;
class StudentAnnotationMapperTest {
@Test
void selectStudentByIdTest() {
SqlSession sqlSession = MybatisUtils.getSqlSession();
StudentAnnotationMapper mapper = sqlSession.getMapper(StudentAnnotationMapper.class);
if(mapper.selectStudentByIdAno(1) == null){
System.out.println("结果为空");
}else{
Student student = mapper.selectStudentByIdAno(1);
System.out.println(student.getSid() + "\t"
+ student.getSname() + "\t" + student.getSage()
+ "\t" + student.getSmaster());
sqlSession.close();
}
}
}
package com.cainiao.mapper;
import com.cainiao.pojo.Student;
import com.cainiao.pojo.Teacher;
import com.cainiao.utils.MybatisUtils;
import org.apache.ibatis.session.SqlSession;
import org.junit.jupiter.api.Test;
import java.util.List;
import static org.junit.jupiter.api.Assertions.*;
class TeacherMapperTest {
@Test
void getStuTeaInfoTest() {
SqlSession sqlSession = MybatisUtils.getSqlSession();
TeacherMapper mapper = sqlSession.getMapper(TeacherMapper.class);
List stuTeaInfo =
mapper.getStuTeaInfo();
for (Student student : stuTeaInfo) {
System.out.println(String.valueOf(student));
}
}
@Test
void getTeaStuInfoTest() {
SqlSession sqlSession = MybatisUtils.getSqlSession();
TeacherMapper mapper = sqlSession.getMapper(TeacherMapper.class);
List teaStuInfo = mapper.getTeaStuInfo();
for (Teacher teacher : teaStuInfo) {
System.out.println(teacher);
}
sqlSession.close();
}
}
package com.cainiao.mapper;
import com.cainiao.pojo.Blog;
import com.cainiao.utils.IdUtils;
import com.cainiao.utils.MybatisUtils;
import org.apache.ibatis.session.SqlSession;
import org.junit.jupiter.api.Test;
import java.util.*;
import static org.junit.jupiter.api.Assertions.*;
class BlogMapperTest {
@Test
void addBlogTest() {
SqlSession sqlSession = MybatisUtils.getSqlSession();
BlogMapper mapper = sqlSession.getMapper(BlogMapper.class);
mapper.addBlog(new Blog(IdUtils.getId(), "aaaaaaaaaaaaa", "Mary", new Date(), "100"));
mapper.addBlog(new Blog(IdUtils.getId(), "bbbbbbbbbbbbb", "Tom", new Date(), "200"));
mapper.addBlog(new Blog(IdUtils.getId(), "ccccccccccccc", "Tony", new Date(), "58"));
mapper.addBlog(new Blog(IdUtils.getId(), "ddddddddddddd", "Aaron", new Date(), "355"));
sqlSession.close();
}
@Test
void selectBlogIFTest() {
SqlSession sqlSession = MybatisUtils.getSqlSession();
BlogMapper mapper = sqlSession.getMapper(BlogMapper.class);
// 有参数:按照参数进行查询
// 无参数:查询所有数据
Map map = new HashMap<>();
// map.put("title", "bbbbbbbbbbbbb");
List blogs = mapper.selectBlogIF(map);
for (Blog blog : blogs) {
System.out.println(blog);
}
}
@Test
void selectBlogCHOOSE() {
SqlSession sqlSession = MybatisUtils.getSqlSession();
BlogMapper mapper = sqlSession.getMapper(BlogMapper.class);
Map map = new HashMap<>();
// map.put("title", "bbbbbbbbbbbbb");
map.put("author", "Mary");
map.put("views", "58");
List blogs = mapper.selectBlogCHOOSE(map);
for (Blog blog : blogs) {
System.out.println(blog);
}
sqlSession.close();
}
@Test
void updateBlog() {
SqlSession sqlSession = MybatisUtils.getSqlSession();
BlogMapper mapper = sqlSession.getMapper(BlogMapper.class);
Blog blog = new Blog();
blog.setTitle("ddddddddddddd1");
blog.setAuthor("Aaron1");
blog.setId("45a5fa1f5e4f41599b72ae1950257e6c");
mapper.updateBlog(blog);
sqlSession.close();
}
@Test
void selectBlogFOREACH() {
SqlSession sqlSession = MybatisUtils.getSqlSession();
BlogMapper mapper = sqlSession.getMapper(BlogMapper.class);
Map map = new HashMap<>();
ArrayList authors = new ArrayList();
authors.add("Tony");
map.put("authors", authors);
List blogs = mapper.selectBlogFOREACH(map);
for (Blog blog : blogs) {
System.out.println(blog);
}
sqlSession.close();
}
}