Maven仓库:
<!-- https://mvnrepository.com/artifact/org.mybatis/mybatis -->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.5.13</version>
</dependency>
GitHub
中文文档
思路:搭建环境——》导入Mybatis——》编写代码——》测试
注意事项:
1. 配置文件是否注册
2. 绑定接口是否有误
3. 方法名是否对应
4. 返回类型
5. Maven导出资源问题
搭建数据库
CREATE DATABASE `mybatis`;
USER `mybatis`;
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,'Java学不会','123456'),
(2,'张三','123456'),
(3,'李四','123456')
新建项目
<!--导入依赖-->
<dependencies>
<!--mysql驱动-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.47</version>
</dependency>
<!--Mybatis-->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.5.2</version>
</dependency>
<!--Junit-->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
</dependency>
</dependencies>
编写Mybatis的核心配置文件(mybatis-config.xml)
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"https://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="url" value="jdbc:mysql://localhost:3306/mybatis?useSSL=true&useUnicode=true&characterEncoding=UTF-8"/>
<property name="username" value="root"/>
<property name="password" value="123456"/>
</dataSource>
</environment>
</environments>
<mappers>
<mapper resource="org/mybatis/example/BlogMapper.xml"/>
</mappers>
</configuration>
编写Mybatis工具类
package com.javastudy.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;
//SqlSessionFactory ---》 SqlSession
public class MybatisUtils {
private static SqlSessionFactory sqlSessionFactory;
static {
try {
//获取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.javastudy.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;
}
@Override
public String toString( ) {
return "User{id="+id+",name="+name+",pwd="+pwd+"}";
}
public void setId( int id ) {
this.id = id;
}
public void setName( String name ) {
this.name = name;
}
public void setPwd( String pwd ) {
this.pwd = pwd;
}
public int getId( ) {
return id;
}
public String getName( ) {
return name;
}
public String getPwd( ) {
return pwd;
}
}
Dao接口
public interface UserDao {
List<User> getUserList();
}
接口实现类(将原来的UserDaoImpl转换为一个Mapper配置文件)
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"https://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.javastudy.dao.UserDao">
<!--select查询语句-->
<select id="getUserList" resultType="com.javastudy.pojo.User">
select * from mybatis.user
</select>
</mapper>
注意: org.apache.ibatis.binding.BindingException: Type interface com.javastudy.dao.UserDao is not known to the MapperRegistry.
核心配置文件中注册mappers
防止资源导出失败
<!--在build中配置properties中防止资源导出失败-->
<build>
<resources>
<resource>
<directory>src/main/java</directory>
<includes>
<include>**/*.properties
**/ *.xml</include>
</includes>
<filtering>false</filtering>
</resource>
<resource>
<directory>src/main/resources</directory>
<includes>
<include>**/*.properties
**/ *.xml</include>
</includes>
<filtering>false</filtering>
</resource>
</resources>
</build>
junit测试
package com.javastudy.dao;
import com.javastudy.pojo.User;
import com.javastudy.utils.MybatisUtils;
import org.apache.ibatis.session.SqlSession;
import org.junit.Test;
import java.util.List;
public class UserDaoTest {
@Test
public void test(){
//第一步:获得sqlSession对象
SqlSession sqlSession = MybatisUtils.getSqlSession();
//方式-:getMapper执行Sql
UserDao userDao = sqlSession.getMapper(UserDao.class);
List<User> userList = userDao.getUserList();
for (User user : userList) {
System.out.println(user.toString());
}
//关闭sqlSession
sqlSession.close();
}
}
增删改需要提交事务
//根据ID查询用户
User getUserById(int id);
<select id="getUserById" parameterType="int" resultType="com.javastudy.pojo.User">
select * from mybatis.user where id= #{id}
</select>
编写接口
//增加用户
int addUser(User user);
编写对应的Mapper中的SQL语句
<!--对象中的属性,可以直接取出来-->
<insert id="addUser" parameterType="com.javastudy.pojo.User" >
insert into mybatis.user(id, name, pwd) values (#{id},#{name},#{pwd})
</insert>
编写接口
//修改用户
int updaTeUser(User user);
编写对应的Mapper中的SQL语句
<update id="updaTeUser" parameterType="com.javastudy.pojo.User">
update mybatis.user
set name =#{name},pwd=#{pwd}
where id=#{id};
</update>
编写接口
//删除用户
int deleteUser(int id);
编写对应的Mapper中的SQL语句
<delete id="deleteUser" parameterType="int">
delete
from user
where id=#{id};
</delete>
package com.javastudy.dao;
import com.javastudy.pojo.User;
import com.javastudy.utils.MybatisUtils;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionException;
import org.junit.Test;
import java.util.List;
public class UserDaoTest {
@Test
public void test( ) {
//第一步:获得sqlSession对象
SqlSession sqlSession = MybatisUtils.getSqlSession();
//方式-:getMapper执行Sql
UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
List<User> userList = userMapper.getUserList();
for (User user : userList) {
System.out.println(user.toString());
}
//关闭sqlSession
sqlSession.close();
}
@Test
public void getUserById( ) {
SqlSession sqlSession = MybatisUtils.getSqlSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
User user = mapper.getUserById(1);
System.out.println(user);
sqlSession.close();
}
@Test
//增删改需要提交事务
public void addUser( ) {
SqlSession sqlSession = MybatisUtils.getSqlSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
mapper.addUser(new User(4,"代转魂","200123123"));
//提交事务
sqlSession.commit();
sqlSession.close();
}
@Test
public void updaTeUser(){
SqlSession sqlSession = MybatisUtils.getSqlSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
int i = mapper.updaTeUser(new User(4, "大专魂", "123456"));
if(i>0){
sqlSession.commit();
}
sqlSession.close();
}
@Test
public void deleteUser(){
SqlSession sqlSession = MybatisUtils.getSqlSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
int i = mapper.deleteUser(4);
if(i>0){
sqlSession.commit();
}
sqlSession.close();
}
}
Java代码执行的时候,传递通配符%%
List<User> userList = mapper.getUserLike("李%");
在SQL拼接中使用通配符
<select id="getUserLike" resultType="com.javastudy.pojo.User">
select * from mybatis.user where name like "%"#{value}"%"
</select>
MyBatis 的配置文件包含了会深深影响 MyBatis 行为的设置和属性信息
mybatis-config.xml
configuration(配置)
properties(属性)
settings(设置)
typeAliases(类型别名)
typeHandlers(类型处理器)
objectFactory(对象工厂)
plugins(插件)
environments(环境配置)
environment(环境变量)
transactionManager(事务管理器)
dataSource(数据源)
databaseIdProvider(数据库厂商标识)
mappers(映射器)
可以通过properties属性来实现引用配置文件
这些属性可以在外部进行配置,并可以进行动态替换。你既可以在典型的 Java 属性文件中配置这些属性,也可以在 properties 元素的子元素中设置(db.properties)
编写一个配置文件(db.properties)
driver=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/mybatis?useSSL=true&useUnicode=true&characterEncoding=UTF-8
username=root
password=123456
在核心配置文件引入
<!--引入外部配置文件-->
<properties resource="db.properties">
<property name="username" value="root"/>
<property name="password" value=""/>
</properties>
可以直接引入外部文件
可以在其中增加一些属性配置
如果两个文件有有同一个字段,优先使用外部配置文件
<environments default="development">
<environment id="development">
<transactionManager type="JDBC"/>
<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>
类型别名可为 Java 类型设置一个缩写名字
意在降低冗余的全限定类名书写
<!--可以给实体类起别名-->
<typeAliases>
<typeAlias type="com.javastudy.pojo.User" alias="User"></typeAlias>
</typeAliases>
也可以指定一个包名,MyBatis 会在包名下面搜索需要的 Java Bean
扫描实体类的包,它的默认别名就为这个类的类名
<!--可以给实体类起别名-->
<typeAliases>
<package name="com.javastudy.pojo"/>
</typeAliases>
在实体类比较少的时候,使用第一种方式
如果实体类十分多,建议使用第二种
第一种可以DIY;第二种则不行,如果要改,需要在实体类上增加注解
@Alias("User")
public class User {
方式一:推荐使用
<mappers>
<mapper resource="com/javastudy/dao/UserMapper.xml/"></mapper>
</mappers>
方式二:使用class文件绑定注册
<mappers>
<mapper class="com.javastudy.dao.UserMapper"></mapper>
</mappers>
方式三:使用包扫描进行注入绑定
<mappers>
<package name="com.javastudy.dao"></package>
</mappers>
实体类
public class User {
private int id;
private String name;
private String password;
<select id="getUserById" parameterType="int" resultType="com.javastudy.pojo.User">
select id,name,pwd from mybatis.user where id= #{id}
</select>
起别名
<select id="getUserById" parameterType="int" resultType="com.javastudy.pojo.User">
select id,name,pwd as password from mybatis.user where id= #{id}
</select>
resultMap: 结果集映射
<!--结果集映射-->
<resultMap id="UserMap" type="User">
<!--column数据库中的字段,property实体类中的属性-->
<result column="id" property="id"></result>
<result column="name" property="name"></result>
<result column="pwd" property="password"></result>
</resultMap>
<select id="getUserById" parameterType="int" resultMap="UserMap">
select * from mybatis.user where id= #{id}
</select>
掌握
)减少数据的处理量
//分页查询
List<User> getUserLimit( Map<String,Integer> map );
<!--分页-->
<select id="getUserLimit" parameterType="map" resultMap="UserMap">
select * from mybatis.user limit #{startIndex},#{pageSize}
</select>
@Test
public void getUserLimit(){
SqlSession sqlSession = MybatisUtils.getSqlSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
HashMap<String, Integer> map = new HashMap<>();
map.put("startIndex",0);
map.put("pageSize",2);
List<User> userLimit = mapper.getUserLimit(map);
for (User user : userLimit) {
System.out.println(user);
}
sqlSession.close();
}
//分页查询
List<User> getUserRowBounds( );
<!--分页-->
<select id="getUserRowBounds" resultMap="UserMap">
select * from mybatis.user
</select>
@Test
public void getUserRowBounds(){
SqlSession sqlSession = MybatisUtils.getSqlSession();
//通过RowBounds实现
RowBounds rowBounds = new RowBounds(1, 2);
//通过java代码层实现分页
List<User> userList = sqlSession.selectList("com.javastudy.dao.UserMapper.getUserRowBounds",null,rowBounds);
for (User user : userList) {
System.out.println(user);
}
sqlSession.close();
}
注解在接口上实现
@Select("select * from user")
List<User> getUsers( );
需要在核心配置文件中绑定接口
<!--绑定接口-->
<mappers>
<mapper class="com.javastudy.dao.UserMapper"></mapper>
</mappers>
测试
@Test
public void test(){
SqlSession sqlSession = MybatisUtils.getSqlSession();
//底层主要应用反射
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
List<User> users = mapper.getUsers();
for (User user : users) {
System.out.println(user);
}
sqlSession.close();
}
本质:反射机制实现
底层:动态代理
我们可以在工具类创建的时候实现自动提交事务
public static SqlSession getSqlSession(){
return sqlSessionFactory.openSession(true);
}
编写接口,增加注解
package com.javastudy.dao;
import com.javastudy.pojo.User;
import org.apache.ibatis.annotations.*;
import java.util.List;
public interface UserMapper {
@Select("select * from user")
List<User> getUsers( );
//方法存在多个参数,所有的参数前面必须加上@Param注解
@Select("select * from user where id=#{id}")
User getUserById( @Param("id") int id );
@Insert("insert into user(id,name,pwd) values (#{id},#{name},#{password})")
int addUser(User user);
@Update("update user set name=#{name},pwd=#{password} where id=#{id}")
int updateUser(User user);
@Delete("delete from user where id=#{id}")
int deleteUser(@Param("id") int id);
}
注意:必须要把接口注册绑定的核心配置文件中
<!--绑定接口-->
<mappers>
<mapper class="com.javastudy.dao.UserMapper"></mapper>
</mappers>
Lombok项目是一个java库,它可以自动插入到编辑器和构建工具中,增强java的性能。不需要再写getter、setter或equals方法,只要有一个注解,你的类就有一个功能齐全的构建器、自动记录变量等等
在idea中安装Lombok插件
在项目中导入Lombok的jar包
<!-- https://mvnrepository.com/artifact/org.projectlombok/lombok -->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.26</version>
</dependency>
Lombok常用注解
@Getter and @Setter
@FieldNameConstants
@ToString
@EqualsAndHashCode
@AllArgsConstructor, @RequiredArgsConstructor and @NoArgsConstructor
@Log, @Log4j, @Log4j2, @Slf4j, @XSlf4j, @CommonsLog, @JBossLog, @Flogger, @CustomLog
@Data
@Builder
@SuperBuilder
@Singular
@Delegate
@Value
@Accessors
@Wither
@With
@SneakyThrows
@val
@var
@Data: 无参构造、get、set、toString、hashcode,equals
@AllArgsConstructor: 有参构造
@NoArgsConstructor: 无参构造
SQL
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');
INSERT INTO `student` (`id`, `name`, `tid`) VALUES ('2', '小红', '1');
INSERT INTO `student` (`id`, `name`, `tid`) VALUES ('3', '小张', '1');
INSERT INTO `student` (`id`, `name`, `tid`) VALUES ('4', '小李', '1');
INSERT INTO `student` (`id`, `name`, `tid`) VALUES ('5', '小王', '1');
导入Lombok
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.26</version>
</dependency>
新建实体类
package com.javastudy.pojo;
import lombok.Data;
@Data
public class Teacher {
private int id;
private String name;
}
package com.javastudy.pojo;
import lombok.Data;
@Data
public class Student {
private int id;
private String name;
//学生需要关联一个老师
private Teacher teacher;
}
建立Mapper接口
package com.javastudy.dao;
import com.javastudy.pojo.Teacher;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;
public interface TeacherMapper {
@Select("select * from teacher where id=#{tid}")
Teacher getTeacher( @Param ("tid") int id);
}
package com.javastudy.dao;
public interface StudentMapper {
}
建立Mapper.XML文件
<?xml version="1.0" encoding="utf-8" ?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"https://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.javastudy.dao.TeacherMapper">
</mapper>
<?xml version="1.0" encoding="utf-8" ?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"https://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.javastudy.dao.StudentMapper">
</mapper>
在核心配置文件中绑定注册Mapper接口或者文件
<!--每一个mapper.xml都需要在Mybatis核心配置文件中注册-->
<mappers>
<mapper class="com.javastudy.dao.TeacherMapper"/>
<mapper class="com.javastudy.dao.StudentMapper"/>
</mappers>
测试查询能否成功
package com.javastudy.dao;
import com.javastudy.pojo.Teacher;
import com.javastudy.utils.MybatisUtils;
import org.apache.ibatis.session.SqlSession;
public class MyTest {
public static void main( String[] args ) {
SqlSession sqlSession = MybatisUtils.getSqlSession();
TeacherMapper mapper = sqlSession.getMapper(TeacherMapper.class);
Teacher teacher = mapper.getTeacher(1);
System.out.println(teacher);
sqlSession.close();
}
}
<!--
思路:
1.查询所有的学生信息
2.根据查询出来的学生的tid,寻找对应的老师
-->
<select id="getStudent" resultMap="StudentTeacher">
select * from mybatis.student
</select>
<resultMap id="StudentTeacher" type="Student">
<result property="id" column="id"></result>
<result property="name" column="name"></result>
<!--复杂的属性需要单独处理
对象:association
集合:collection
-->
<association property="teacher" column="tid" javaType="Teacher" select="getTeacher"/>
</resultMap>
<select id="getTeacher" resultType="Teacher">
select * from mybatis.teacher where id=#{tid}
</select>
<!--按照结果嵌套处理-->
<select id="getStudent2" resultMap="StudentTeacher2">
select s.id sid,s.name sname,t.id tid, t.name tname
from mybatis.student s,mybatis.teacher t
where s.tid=t.id
</select>
<resultMap id="StudentTeacher2" type="Student">
<result property="id" column="sid"/>
<result property="name" column="sname"/>
<association property="teacher" javaType="Teacher">
<result property="name" column="tname"/>
<result property="id" column="tid"/>
</association>
</resultMap>
package com.javastudy.pojo;
import lombok.Data;
@Data
public class Student {
private int id;
private String name;
private int tid;
}
package com.javastudy.pojo;
import lombok.Data;
import java.util.List;
@Data
public class Teacher {
private int id;
private String name;
//一个老师拥有多个学生
private List<Student> students;
}
<!--按照结果嵌套查询-->
<select id="getTeacher" resultMap="TeacherStudent" >
select s.id sid,s.name sname,t.name name,t.id tid
from mybatis.student s,mybatis.teacher t
where s.tid=t.id
and t.id=#{tid}
</select>
<resultMap id="TeacherStudent" type="Teacher">
<result property="id" column="tid"></result>
<result property="name" column="tname"></result>
<!--javaType指定的属性类型
集合中的泛型信息,使用ofType获取
-->
<collection property="students" ofType="Student">
<result property="id" column="sid"></result>
<result property="name" column="sname"></result>
<result property="tid" column="tid"></result>
</collection>
</resultMap>
<!--按照查询嵌套处理-->
<select id="getTeacher2" resultMap="TeacherStudent2">
select * from mybatis.teacher where id=#{tid}
</select>
<resultMap id="TeacherStudent2" type="Teacher">
<collection property="students" javaType="List" ofType="Student" select="getStudentByTeacherId" column="id">
</collection>
</resultMap>
<select id="getStudentByTeacherId" resultType="Student">
select * from mybatis.student where tid=#{tid}
</select>
动态SQL就是根据不同的条件生成不同的SQL语句
SQL
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;
import com.javastudy.dao.BlogMapper;
import com.javastudy.pojo.Blog;
import com.javastudy.utils.IDUtils;
import com.javastudy.utils.MybatisUtils;
import org.apache.ibatis.session.SqlSession;
import org.junit.Test;
import java.util.Date;
public class MyTest {
@Test
public void addBlogTest() {
SqlSession sqlSession = MybatisUtils.getSqlSession();
BlogMapper mapper = sqlSession.getMapper(BlogMapper.class);
Blog blog = new Blog();
blog.setId(IDUtils.getId());
blog.setTitle("Mybatis");
blog.setAuthor("Java学不会");
blog.setCreateTime(new Date());
blog.setViews(9999);
mapper.addBlog(blog);
blog.setId(IDUtils.getId());
blog.setTitle("Java");
mapper.addBlog(blog);
blog.setId(IDUtils.getId());
blog.setTitle("Spring");
mapper.addBlog(blog);
blog.setId(IDUtils.getId());
blog.setTitle("微服务");
mapper.addBlog(blog);
sqlSession.close();
}
}
创建一个基础工程
package com.javastudy.pojo;
import lombok.Data;
import java.util.Date;
@Data
public class Blog {
private String id;
private String title;
private String author;
private Date createTime;
private int views;
}
条件可以有多个并列的关系
<select id="queryBlogIF" parameterType="map" resultType="blog">
select * from mybatis.blog where 1=1
<if test="title!=null">
and title=#{title}
</if>
<if test="author!=null">
and author =#{author}
</if>
</select>
where会自动判断有没有符合的条件如果有则添加where;同时会判断是不是第一个条件,如果是第一个条件且有
and
或者or
会自动去除
<select id="queryBlogIF" parameterType="map" resultType="blog">
select * from mybatis.blog
<where>
<if test="title!=null">
title=#{title}
</if>
<if test="author!=null">
and author =#{author}
</if>
</where>
</select>
choose
: 从上到下选择满足的第一个
when
: 匹配条件
otherwise
: 如果条件都不满足,走这个语句
<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=#{views}
</otherwise>
</choose>
</where>
</select>
set会判断后面还是否会有修改语句,如果没有删除最后一个
,
<update id="updateBlog" parameterType="map">
update mybatis.blog
<set>
<if test="title!=null">
title=#{title},
</if>
<if test="author !=null">
author=#{author}
</if>
</set>
where id=#{id}
</update>
有时候,可能会将一些功能的部分抽取出来,方便复用
使用SQL标签抽取公共的部分
<sql id="if-title-author">
<if test="title!=null">
title=#{title}
</if>
<if test="author!=null">
and author =#{author}
</if>
</sql>
在需要使用的地方使用include标签引用
<select id="queryBlogIF" parameterType="map" resultType="blog">
select * from mybatis.blog
<where>
<include refid="if-title-author"></include>
</where>
</select>
collection:
从map传递的key,map可以存一个集合
item:
collection中的每个元素别名
open:
开头
close:
结尾
separator:
分隔符(每一个item用什么分隔
)
<select id="queryBlogForeach" parameterType="map" resultType="blog">
select * from mybatis.blog
<where>
<foreach collection="ids" item="id" open="(" close=")" separator="or">
id =#{id}
</foreach>
</where>
</select>
- 什么是缓存(Cache)
- 存放在内存中的数据
- 将用户查询到的数据放在缓存(内存)中,用户去查询数据就不用从磁盘(关系型数据库数据文件)查询,从缓存中查询,从而提高查询效率,解决了高并发系统的性能问题。
- 为什么使用缓存?
- 减少数据库的交互次数,减少系统开销,提高系统效率。
- 什么样的数据能使用缓存?
- 经常查询并且不经常改变的数据。
<!--显示的开启全局缓存-->
<setting name="cacheEnabled" value="true "/>
<!--在当前Mapper.XML中使用二级缓存-->
<cache
eviction="FIFO"
flushInterval="60000"
size="512"
readOnly="true"/>