maven仓库:
<dependency>
<groupId>org.mybatisgroupId>
<artifactId>mybatisartifactId>
<version>x.x.xversion>
dependency>
Github:https://github.com/mybatis/mybatis-3/releases
中文文档:https://mybatis.net.cn/getting-started.html
CREATE TABLE `user` (
`id` INT ( 20 ) NOT NULL PRIMARY KEY,
`name` VARCHAR ( 30 ) DEFAULT NULL,
`pwd` VARCHAR ( 30 ) DEFAULT NULL
) ENGINE = INNODB DEFAULT charset = utf8
insert into `user` (`id`,`name`,`pwd`) values
(1,'chenyu','123456'),
(2,'cy','123456'),
(3,'admin','123456')
删除src文件夹,编写父项目的pom.xml文件
<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.0modelVersion>
<groupId>org.examplegroupId>
<artifactId>myBatisartifactId>
<version>1.0-SNAPSHOTversion>
<dependencies>
<dependency>
<groupId>mysqlgroupId>
<artifactId>mysql-connector-javaartifactId>
<version>8.0.21version>
dependency>
<dependency>
<groupId>org.mybatisgroupId>
<artifactId>mybatisartifactId>
<version>3.5.7version>
dependency>
<dependency>
<groupId>junitgroupId>
<artifactId>junitartifactId>
<version>4.13.1version>
<scope>testscope>
dependency>
dependencies>
project>
DOCTYPE configuration
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
<environments default="development">
<environment id="development">
<transactionManager type="JDBC"/>
<dataSource type="POOLED">
<property name="driver" value="com.mysql.jdbc.Driver"/>
<property name="driver" value="com.mysql.cj.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost:3306/mybatis?useSSL=true&useUnicode=true&characterEncoding=UTF-8&serverTimezone=GMT%2B8"/>
<property name="username" value="root"/>
<property name="password" value="123456"/>
dataSource>
environment>
environments>
configuration>
package com.chen.utils;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.jdbc.SQL;
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;
//sqlSessionFactory --> sqlSession
public class MybatisUtils {
private static SqlSessionFactory sqlSessionFactory;
static {
try {
// 使用Mybatis第一步:获取sqlSessionFactory
String resource = "mybatis-config.xml";
InputStream inputStream = Resources.getResourceAsStream(resource);
sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
} catch (IOException e) {
e.printStackTrace();
}
}
// 既然有了SqlSessionFactory,顾名思义,我们就可以从中获得SqlSession的实例
// SqlSession 完全包含了面向数据库执行SQL命令所需的所有方法。
public static SqlSession getSqlSession() {
return sqlSessionFactory.openSession();
}
}
package com.chen.pojo;
public class User {
private int id;
private String name;
private String pwd;
public User() {
}
public User(int id, String name, String pwd) {
this.id = id;
this.name = name;
this.pwd = pwd;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPwd() {
return pwd;
}
public void setPwd(String pwd) {
this.pwd = pwd;
}
@Override
public String toString() {
return "User{" +
"id=" + id +
", name='" + name + '\'' +
", pwd='" + pwd + '\'' +
'}';
}
}
package com.chen.mapper;
import com.chen.pojo.User;
import java.util.List;
public interface userMapper {
List<User> getUserList();
}
DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.chen.mapper.UserMapper">
<select id="getUserList" resultType="com.chen.pojo.User">
select * from mybatis.user
select>
mapper>
在src/test/java里面创建测试类
package com.chen.dao;
import com.chen.mapper.UserMapper;
import com.chen.pojo.User;
import com.chen.utils.MybatisUtils;
import org.apache.ibatis.session.SqlSession;
import org.junit.Test;
import java.util.List;
public class UserMapperTest {
@Test
public void test() {
// 1.获得SqlSession对象
SqlSession sqlSession = MybatisUtils.getSqlSession();
try {
// 方式一:getMapper
// 2.获得Mapper
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
// 3.执行SQL
List<User> userList = mapper.getUserList();
// 方式二:
// List userList = sqlSession.selectList("com.chen.mapper.UserMapper.getUserList");
for (User user : userList) {
System.out.println(user.toString());
}
} catch (Exception e) {
e.printStackTrace();
} finally {
// 4.关闭SqlSession
sqlSession.close();
}
}
}
注意点:绑定异常
org.apache.ibatis.binding.BindingException:
Type interface com.chen.mapper.UserMapper is not known to the MapperRegistry.
MapperRegistry 不知道类型接口 com.chen.mapper.UserMapper。
解决方法:mybatis-config.xml中注册Mapper
<mappers>
<mapper resource="com/chen/mapper/UserMapper.xml"/>
mappers>
注册了但是扫描不到mapper的文件需要在配置文件中添加扫描配置
解决方法:pom.xml增加配置
<build>
<resources>
<resource>
<directory>src/main/resourcesdirectory>
<includes>
<include>**/*.propertiesinclude>
<include>**/*.xmlinclude>
includes>
<filtering>truefiltering>
resource>
<resource>
<directory>src/main/javadirectory>
<includes>
<include>**/*.propertiesinclude>
<include>**/*.xmlinclude>
includes>
<filtering>truefiltering>
resource>
resources>
<plugins>
<plugin>
<groupId>org.apache.maven.pluginsgroupId>
<artifactId>maven-resources-pluginartifactId>
<configuration>
<encoding>UTF-8encoding>
configuration>
plugin>
plugins>
build>
namespace中的包名要和Dao/mapper接口包名一致
选择,查询语句;
<insert id="addUser" parameterType="com.chen.pojo.User">
insert into mybatis.user (id,name,pwd) value (#{id},#{name},#{pwd});
insert>
<update id="updateUser" parameterType="com.chen.pojo.User">
update mybatis.user
set name = #{name},pwd = #{pwd}
where id = #{id};
update>
<delete id="deleteUser" parameterType="java.lang.Integer">
delete from mybatis.user where id = #{id}
delete>
注意:增删改需要提交事务,否则所做操作无效
package com.chen.dao;
import com.chen.mapper.UserMapper;
import com.chen.pojo.User;
import com.chen.utils.MybatisUtils;
import org.apache.ibatis.session.SqlSession;
import org.junit.Test;
import java.util.List;
import java.util.Scanner;
public class UserMapperTest {
@Test
public void test() {
// 1.获得SqlSession对象
SqlSession sqlSession = MybatisUtils.getSqlSession();
try {
// 方式一:getMapper
// 2.获得Mapper
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
// 3.执行SQL
List<User> userList = mapper.getUserList();
// 方式二:
// List userList = sqlSession.selectList("com.chen.mapper.UserMapper.getUserList");
for (User user : userList) {
System.out.println(user.toString());
}
} catch (Exception e) {
e.printStackTrace();
} finally {
// 4.关闭SqlSession
sqlSession.close();
}
}
@Test
public void testGetUserById() {
SqlSession sqlSession = MybatisUtils.getSqlSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
User user = mapper.getUserById(1);
System.out.println(user.toString());
sqlSession.close();
}
@Test
public void testAddUser() {
SqlSession sqlSession = MybatisUtils.getSqlSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
int row = mapper.addUser(new User(5, "zhang", "123456"));
if (row > 0) {
System.out.println("增加成功!");
}
sqlSession.commit();
sqlSession.close();
this.test();
}
@Test
public void testUpdateUser() {
SqlSession sqlSession = MybatisUtils.getSqlSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
int row = mapper.updateUser(new User(2, "chen", "123456"));
if (row > 0) {
System.out.println("修改成功!");
}
sqlSession.commit();
this.test();
}
@Test
public void testDeleteUser() {
SqlSession sqlSession = MybatisUtils.getSqlSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
int row = mapper.deleteUser(1);
if (row > 0) {
System.out.println("删除成功!");
}
sqlSession.commit();
this.test();
}
}
好处:不受字段限制就能进行数据操作
/**
* 根据条件Map获取用户
* @param map 条件
* @return 用户
*/
List<User> getUserByMap(Map<String,Object> map);
<select id="getUserByMap" parameterType="map" resultType="com.chen.pojo.User">
select * from mybatis.user
<where>
<if test="userId!=null">
id = #{userId}
if>
<if test="userName != null">
and name like "%"#{userName}"%"
if>
<if test="userPassword != null">
and pwd = #{userPassword}
if>
where>
select>
@Test
public void testGetUserByMap() {
SqlSession sqlSession = MybatisUtils.getSqlSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
Map<String, Object> map = new HashMap<String, Object>();
map.put("userPassword", "123456");
map.put("userName", "z");
List<User> userList = mapper.getUserByMap(map);
System.out.println(userList.toString());
sqlSession.close();
}
方式一:写死,好处是用户不能随便进行更多操作
name like "%"#{userName}"%"
方式二:放开,用户可以通过不同的字符集进行不同的操作效果
map.put("userName", "%z%");
name like #{userName}
/**
* 自定义获取User
* @return 用户集合
*/
List<User> getUserWhere(String where);
<select id="getUserWhere" resultType="com.chen.pojo.User">
select *
from mybatis.user
where ${where}
select>
@Test
public void testGetUserWhere() {
SqlSession sqlSession = MybatisUtils.getSqlSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
List<User> userList = mapper.getUserWhere("id = 1");
System.out.println(userList.toString());
sqlSession.close();
}
当数据库字段名与实体对象不匹配时,我们用到结果集映射来将数据库字段名与实体对象名关联匹配。
id name pwd
id name password
<resultMap id="UserMap" type="User">
<result column="id" property="id"/>
<result column="name" property="name"/>
<result column="pwd" property="password"/>
resultMap>
<select id="getUserById" parameterType="int" resultMap="UserMap">
select *
from mybatis.user
where id = #{id}
select>
也可以简单写成只映射数据库中对应字段不一样的做映射
<resultMap id="UserMap" type="User">
<result column="pwd" property="password"/>
resultMap>
<select id="getUserById" parameterType="int" resultMap="UserMap">
select *
from mybatis.user
where id = #{id}
select>
Mappser.xml
<select id="getUserByLimit" parameterType="map" resultMap="UserMap">
select *
from mybatis.user
limit #{pageNo},#{pageSize}
select>
Mapper.java
List<User> getUserByLimit(Map<String, Integer> map);
调用
@Test
public void testLimit() {
SqlSession sqlSession = MybatisUtils.getSqlSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
Map<String, Integer> map = new HashMap<String, Integer>();
map.put("pageNo", 0);
map.put("pageSize", 2);
List<User> list = mapper.getUserByLimit(map);
for (User user : list) {
logger.info(user.toString());
}
sqlSession.close();
}
使用注解可以简化对Mapper.xml文件的操作
mapper层
@Select("select * from user")
List<User> getUserList();
调用
@Test
public void test(){
SqlSession sqlSession = MybatisUtils.getSqlSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
List<User> userList = mapper.getUserList();
System.out.println(userList.toString());
sqlSession.close();
}
mapper
// 方法存在多个参数,所有参数前面加上@Param
@Select("select * from user where id = #{id}")
User getUserById(@Param("id") int id);
调用
@Test
public void testGetUserById() {
SqlSession sqlSession = MybatisUtils.getSqlSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
User user = mapper.getUserById(1);
System.out.println(user.toString());
sqlSession.close();
}
mapper
@Insert("insert into user(id,name,pwd) values (#{id},#{name},#{password}) ")
int addUser(User user);
调用
@Test
public void testAdd(){
SqlSession sqlSession = MybatisUtils.getSqlSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
User user = new User(6, "huang", "123456");
mapper.addUser(user);
// 在构造时候传参可以无需提交事务
sqlSession.close();
}
mapper
@Update("update user set name=#{name},pwd=#{password} where id = #{id}")
int updateUser(User user);
调用
@Test
public void testUpdate(){
SqlSession sqlSession = MybatisUtils.getSqlSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
mapper.updateUser(new User(7, "yue", "654321"));
sqlSession.close();
}
mapper
@Delete("delete from user where id = #{id}")
int delUser(@Param("id") int id);
调用
@Test
public void testDelete(){
SqlSession sqlSession = MybatisUtils.getSqlSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
mapper.delUser(7);
sqlSession.close();
}
简化实体对象操作
需要idea增加插件"lombok"
需要导包
<dependency>
<groupId>org.projectlombokgroupId>
<artifactId>lombokartifactId>
<version>1.18.4version>
<scope>providedscope>
dependency>
使用
@Alias("User")
@Data
@AllArgsConstructor
@NoArgsConstructor
public class User {
private int id;
private String name;
private String password;
}
创建老师表
CREATE TABLE `teacher` (
`id` int(10) NOT NULL,
`name` varchar(30) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
INSERT INTO teacher(`id`,`name`) VALUES (1,'陈老师');
创建学生表
CREATE TABLE student(
`id` INT(10) NOT NULL,
`name` VARCHAR(30) DEFAULT NULL,
`tid` INT(10) DEFAULT NULL,
PRIMARY KEY (`id`),
KEY `fktid`(`tid`),
CONSTRAINT `fktid` FOREIGN KEY (`tid`) REFERENCES `teacher` (`id`)
)ENGINE=INNODB DEFAULT CHARSET=utf8;
INSERT INTO `student`(`id`,`name`,`tid`)
VALUES
('1','小张','1'),
('2','小周','1'),
('3','小黄','1'),
('4','小田','1'),
('5','小欧','1'),
('6','小曹','1'),
('7','小李','1');
目的:查询多个学生所对应的老师
方式一:子查询
mapper.java
List<Student> getStudentList();
mapper.xml
<resultMap id="StudentTeacher" type="Student">
<id column="id" property="id"/>
<result column="name" property="name"/>
<association column="tid" property="teacher" javaType="Teacher" select="getTeacher"/>
resultMap>
<select id="getTeacher" resultType="Teacher">
select * from mybatis.teacher where id=#{id}
select>
<select id="getStudentList" resultMap="StudentTeacher">
select * from mybatis.student
select>
将查出学生的结果再通过子查询形式查到对应老师
方式二:按照结果嵌套处理
<select id="getStudentList2" resultMap="StudentTeacher2">
select s.id sid,
s.name sname,
t.id tid,
t.name tname
from mybatis.student as s,
mybatis.teacher as t
where s.tid = t.id
select>
<resultMap id="StudentTeacher2" type="Student">
<id property="id" column="sid"/>
<result property="name" column="sname"/>
<association property="teacher" javaType="Teacher">
<id property="id" column="tid"/>
<result property="name" column="tname"/>
association>
resultMap>
方式一:按结果集嵌套
<resultMap id="TeacherStudent" type="Teacher">
<id property="id" column="tid"/>
<result property="name" column="tname"/>
<collection
property="studentList"
ofType="Student">
<id property="id" column="sid"/>
<result property="name" column="sname"/>
<result property="tid" column="tid"/>
collection>
resultMap>
<select id="getTeacher" resultMap="TeacherStudent">
select s.id sid, s.name sname, t.name tname, t.id tid
from mybatis.teacher as t,
mybatis.student as s
where s.tid = t.id
and t.id = #{id}
select>
方式二:子查询
<select id="getTeacher2" resultMap="TeacherStudent2">
select *
from mybatis.teacher
where id = #{id}
select>
<resultMap id="TeacherStudent2" type="Teacher">
<id property="id" column="id"/>
<result property="name" column="name"/>
<collection
property="studentList"
javaType="ArrayList"
ofType="Student"
select="getStudentByTeacherId"
column="id"
/>
resultMap>
<select id="getStudentByTeacherId" resultType="Student">
select *
from mybatis.student
where tid = ${id}
select>
创建表
CREATE TABLE `blog` (
`id` varchar(50) NOT NULL COMMENT '博客id',
`title` varchar(100) NOT NULL COMMENT '博客标题',
`author` varchar(30) NOT NULL COMMENT '博客作者',
`create_time` datetime NOT NULL COMMENT '创建时间',
`views` int(30) NOT NULL COMMENT '浏览量'
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
创建实体
@Data
@Alias("Blog")
public class Blog {
private String id;
private String title;
private String author;
private Date createTime;
private int views;
}
if:条件执行
where:去掉第一个查询条件的AND 或 OR ,没有条件匹配去除where
mapper.java
List<Blog> getBlogIf(Map map);
mapper.xml
<select id="getBlogIf" parameterType="Blog" resultType="Blog">
select * from mybatis.blog
<where>
<if test="title != null">
title = #{title}
if>
<if test="author != null">
AND author = #{author}
if>
where>
select>
test.java
@Test
public void getBlogIf() {
SqlSession sqlSession = MybatisUtils.getSqlSession();
BlogMapper mapper = sqlSession.getMapper(BlogMapper.class);
Map<String, String> map = new HashMap<String, String>();
map.put("title", "Mybatis如此简单");
List<Blog> blogIf = mapper.getBlogIf(map);
for (Blog blog : blogIf) {
System.out.println(blog);
}
sqlSession.close();
}
choose:唯一满足条件查询
when:条件
otherwise:无匹配条件执行
mappper.java
List<Blog> queryBlogChoose(Map map);
mapper.xml
<select id="queryBlogChoose" parameterType="map" resultType="blog">
select * from mybatis.blog
<where>
<choose>
<when test="title != null">
title = #{title}
when>
<when test="author != null">
and author = #{author}
when>
<otherwise>
and views > 1000
otherwise>
choose>
where>
select>
test.java
@Test
public void queryBlogChoose(){
SqlSession sqlSession = MybatisUtils.getSqlSession();
BlogMapper mapper = sqlSession.getMapper(BlogMapper.class);
Map<String, String> map = new HashMap<String, String>();
// map.put("title", "Java如此简单");
map.put("author", "chen");
List<Blog> blogIf = mapper.queryBlogChoose(map);
for (Blog blog : blogIf) {
System.out.println(blog);
}
sqlSession.close();
}
set:自动去除结尾","
mapper.java
int updateBlog(Blog blog);
mapper.xml
<update id="updateBlog" parameterType="Blog">
update mybatis.blog
<set>
<if test="title != null">
title=#{title},
if>
<if test="author != null">
author=#{author},
if>
set>
where id=#{id}
update>
test.java
@Test
public void updateTest(){
SqlSession sqlSession = MybatisUtils.getSqlSession();
BlogMapper mapper = sqlSession.getMapper(BlogMapper.class);
Blog blog = new Blog();
blog.setId("7b680cce1ccf483e8ebb155eb2b455b8");
blog.setAuthor("yu");
mapper.updateBlog(blog);
sqlSession.commit();
sqlSession.close();
}
prefix:添加前缀 WHERE 或 SET 以及 “(”
suffix:添加后缀 “)”
prefixOverrides:要去除的前缀 “AND | OR”
suffixOverrides:要去除的后缀","
将可复用的SQL片段提取出来
1.使用sql标签提取出复用部分
2.使用include标签包含复用部分
注意:最好基于单表来定义SQL片段,不要包含where 和set标签
<sql id="if-title-author">
<if test="title != null">
title=#{title},
if>
<if test="author != null">
author=#{author},
if>
sql>
<update id="updateBlog" parameterType="Blog">
update mybatis.blog
<set>
<include refid="if-title-author">include>
set>
where id=#{id}
update>
collection:集合
item:单个对象
index:下标
open:开始符号
separator:间隔符号
close:结束符号
案例:批量新增
mapper.java
int addBlogBatch(@Param("list") List<Blog> list);
mapper.xml
<insert id="addBlogBatch" parameterType="list">
insert into mybatis.blog(id, title, author, create_time, views)
values
<foreach collection="list" item="item" index="index" separator=",">
(#{item.id}, #{item.title}, #{item.author}, #{item.createTime}, #{item.views})
foreach>
insert>
test.java
@Test
public void addBatch() {
SqlSession sqlSession = MybatisUtils.getSqlSession();
ArrayList<Blog> list = new ArrayList<Blog>();
for (int i = 1; i <= 5; i++) {
Blog blog = new Blog();
blog.setId(IdUtils.getId());
blog.setTitle("标题" + i);
blog.setAuthor("作者" + i);
blog.setViews(i);
blog.setCreateTime(new Date());
list.add(blog);
}
BlogMapper mapper = sqlSession.getMapper(BlogMapper.class);
mapper.addBlogBatch(list);
sqlSession.commit();
sqlSession.close();
}
/set>
where id=#{id}
### 7.foreach
**collection**:集合
**item**:单个对象
**index**:下标
**open**:开始符号
**separator**:间隔符号
**close**:结束符号
案例:批量新增
mapper.java
```java
int addBlogBatch(@Param("list") List list);
mapper.xml
<insert id="addBlogBatch" parameterType="list">
insert into mybatis.blog(id, title, author, create_time, views)
values
<foreach collection="list" item="item" index="index" separator=",">
(#{item.id}, #{item.title}, #{item.author}, #{item.createTime}, #{item.views})
foreach>
insert>
test.java
@Test
public void addBatch() {
SqlSession sqlSession = MybatisUtils.getSqlSession();
ArrayList<Blog> list = new ArrayList<Blog>();
for (int i = 1; i <= 5; i++) {
Blog blog = new Blog();
blog.setId(IdUtils.getId());
blog.setTitle("标题" + i);
blog.setAuthor("作者" + i);
blog.setViews(i);
blog.setCreateTime(new Date());
list.add(blog);
}
BlogMapper mapper = sqlSession.getMapper(BlogMapper.class);
mapper.addBlogBatch(list);
sqlSession.commit();
sqlSession.close();
}