-
注解在接口上实现;
UserMapper.java
package com.github.dao; import com.github.pojo.User; import org.apache.ibatis.annotations.Select; import java.util.List; public interface UserMapper { @Select("select * from user") List<User> getUsers(); }
-
需要在核心配置文件中绑定接口!
mybatis-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> <properties resource="db.properties"> <property name="username" value="root"/> <property name="password" value="root"/> </properties> <settings> <setting name="logImpl" value="STDOUT_LOGGING"/> </settings> <typeAliases> <package name="com.github.pojo"/> </typeAliases> <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> <!--绑定接口--> <mappers> <mapper class="com.github.dao.UserMapper"/> </mappers> </configuration>
-
测试
package com.github.test;
import com.github.dao.UserMapper;
import com.github.pojo.User;
import com.github.utils.MybatisUtils;
import org.apache.ibatis.session.SqlSession;
import org.junit.Test;
import java.util.List;
public class UserMapperTest {
@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();
}
}
-
本质:反射机制实现
-
底层:动态代理!
Mybatis详细的执行流程!
8.3、CRUD
- 我们可以在工具类创建的时候实现自动提交事务!
public static SqlSession getSqlSession(){
return sqlSessionFactory.openSession(true);
}
- 编写接口,增加注解。
package com.github.dao;
import com.github.pojo.User;
import org.apache.ibatis.annotations.*;
import java.util.List;
import java.util.Map;
public interface UserMapper {
@Select("select * from user")
List<User> getUsers();
// 方法存在多个参数,所有的参数前面必须加上 @Param("id")注解
@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 = #{uid}")
int deleteUser(@Param("uid") int id);
}
- 测试类,【注意:必须要将接口注册绑定到核心配置文件中!】
package com.github.test;
import com.github.dao.UserMapper;
import com.github.pojo.User;
import com.github.utils.MybatisUtils;
import org.apache.ibatis.session.SqlSession;
import org.junit.Test;
import java.util.List;
public class UserMapperTest {
@Test
public void test(){
SqlSession sqlSession = MybatisUtils.getSqlSession();
// 底层主要应用反射
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
mapper.addUser(new User(5,"hello","123456"));
sqlSession.close();
}
}
/*
List<User> users = mapper.getUsers();
for(User user : users){
System.out.println(user);
}
User userByID = mapper.getUserByID(1);
System.out.println(userByID);
mapper.addUser(new User(5,"hello","123456"));
mapper.updateUser(new User(5,"to","213213"));
mapper.deleteUser(5);
*/
关于@Param() 注解
- 基本类型的参数或者String类型,需要加上。
- 引用类型不需要加。
- 如果只有一个基本类型的话,可以忽略,但是建议大家都加上!
- 我们在SQL中引用的就是我们这里的 @Param() 中设定的属性名!
#{}与${} 区别
-
参考链接:https://blog.csdn.net/kaixuansui/article/details/88637311
-
{} 解析为一个 JDBC 预编译语句(prepared statement)的参数标记符,一个 #{ } 被解析为一个参数占位符;而${}仅仅为一个纯碎的 string 替换,在动态 SQL 解析阶段将会进行变量替换。
-
{} 解析之后会将String类型的数据自动加上引号,其他数据类型不会;而${} 解析之后是什么就是什么,他不会当做字符串处理。
-
{} 很大程度上可以防止SQL注入(SQL注入是发生在编译的过程中,因为恶意注入了某些特殊字符,最后被编译成了恶意的执行操作);而${} 主要用于SQL拼接的时候,有很大的SQL注入隐患。
-
在某些特殊场合下只能用${},不能用#{}。
- 例如:在使用排序时ORDER BY $ {id},如果使用#{id},则会被解析成ORDER BY “id”,这显然是一种错误的写法。
9、Lombok
Project Lombok is a java library that automatically plugs into your editor and build tools, spicing up your java.
Never write another getter or equals method again, with one annotation your class has a fully featured builder, Automate your logging variables, and much more.
- java library
- plugs
- build tools
- with one annotation your class
使用步骤:
- 在IDEA中安装Lombok插件!
-
在项目中导入lombok的jar包
<dependencies> <!-- https://mvnrepository.com/artifact/org.projectlombok/lombok --> <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> <version>1.18.12</version> <scope>provided</scope> </dependency> </dependencies>
-
在实体类上加注解即可!
@Data @AllArgsConstructor @NoArgsConstructor
@Getter and @Setter
@FieldNameConstants
@ToString
@EqualsAndHashCode
@AllArgsConstructor, @RequiredArgsConstructor and @NoArgsConstructor
@Log, @Log4j, @Log4j2, @Slf4j, @XSlf4j, @CommonsLog, @JBossLog, @Flogger
@Data
@Builder
@Singular
@Delegate
@Value
@Accessors
@Wither
@SneakyThrows
- 说明:
@Data:无参构造,get、set、tostring、hashcode,equals
@AllArgsConstructor
@NoArgsConstructor
@EqualsAndHashCode
@ToString
@Getter
10、多对一处理
多对一:
- 多个学生,对应一个老师
- 对于学生这边而言, 关联 .. 多个学生,关联一个老师 【多对一】
- 对于老师而言, 集合 , 一个老师,有很多学生 【一对多】
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' );
10.1测试环境搭建
- 导入lombok
- 新建实体类 Teacher,Student
package com.github.pojo;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@AllArgsConstructor
@NoArgsConstructor
public class Student {
private int id;
private String name;
// 学生需要关联一个老师
private Teacher teacher;
}
package com.github.pojo;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@AllArgsConstructor
@NoArgsConstructor
public class Teacher {
private int id;
private String name;
}
- 建立Mapper接口
package com.github.dao;
import com.github.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);
}
- 建立Mapper.XML文件
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.github.dao.TeacherMapper">
</mapper>
- 在核心配置文件中绑定注册我们的Mapper接口或者文件!【方式很多,随心选】
mybatis-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>
<properties resource="db.properties">
<property name="username" value="root"/>
<property name="password" value="root"/>
</properties>
<settings>
<setting name="logImpl" value="STDOUT_LOGGING"/>
</settings>
<typeAliases>
<package name="com.github.pojo"/>
</typeAliases>
<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>
<mappers>
<mapper class="com.github.dao.StudentMapper"/>
<mapper class="com.github.dao.TeacherMapper"/>
</mappers>
</configuration>
- 测试查询是否能够成功!
import com.github.dao.TeacherMapper;
import com.github.pojo.Teacher;
import com.github.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();
}
}
10.2按照查询嵌套处理
- StudentMapper接口
package com.github.dao;
import com.github.pojo.Student;
import java.util.List;
public interface StudentMapper {
// 查询所有的学生的信息,以及对应老师的信息
public List<Student> getStudent();
}
- StudentMapper.xml文件
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<!--configuration核心配置文件-->
<mapper namespace="com.github.dao.StudentMapper">
<select id="getStudent" resultType="Student">
select * from student
</select>
</mapper>
- 测试类
import com.github.dao.StudentMapper;
import com.github.dao.TeacherMapper;
import com.github.pojo.Student;
import com.github.pojo.Teacher;
import com.github.utils.MybatisUtils;
import org.apache.ibatis.session.SqlSession;
import org.junit.Test;
import java.util.List;
public class MyTest {
@Test
public void testStudent(){
SqlSession sqlSession = MybatisUtils.getSqlSession();
StudentMapper mapper = sqlSession.getMapper(StudentMapper.class);
List<Student> studentList = mapper.getStudent();
for(Student student : studentList){
System.out.println(student);
}
sqlSession.close();
}
}
- 修改xml文件
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<!--configuration核心配置文件-->
<mapper namespace="com.github.dao.StudentMapper">
<!--
思路:
1. 查询所有的学生信息
2. 根据查询出来的学生的tid,寻找对应的老师! 子查询
-->
<select id="getStudent" resultMap="StudentTeacher">
select * from student;
</select>
<resultMap id="StudentTeacher" type="Student">
<result property="id" column="id"/>
<result property="name" column="name"/>
<!-- 复杂的属性,需要单独处理
对象: association 集合: collection
-->
<association property="teacher" column="tid" javaType="Teacher" select="getTeacher"/>
</resultMap>
<select id="getTeacher" resultType="Teacher">
select * from teacher where id = #{id};
</select>
</mapper>
10.3按照结果嵌套处理
<!--按照结果嵌套处理-->
<select id="getStudent2" resultMap="StudentTeacher2">
select s.id sid,s.name sname,t.name tname
from student s,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"/>
</association>
</resultMap>
回顾Mysql 多对一查询方式:
- 子查询
- 联表查询
11、一对多处理
-
比如:一个老师拥有多个学生!
-
对于老师而言,就是一对多的关系!
11.1环境搭建
- 环境搭建,和刚才一样。
实体类
package com.github.pojo;
import lombok.Data;
@Data
public class Student {
private int id;
private String name;
private int tid;
}
package com.github.pojo;
import lombok.Data;
import java.util.List;
@Data
public class Teacher {
private int id;
private String name;
// 一个老师拥有多个学生
private List<Student> students;
}
- 测试一下,编写TeacherMapper接口
package com.github.dao;
import com.github.pojo.Teacher;
import java.util.List;
public interface TeacherMapper {
// 获取老师
List<Teacher> getTeacher();
}
- 编写xml文档
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<!--configuration核心配置文件-->
<mapper namespace="com.github.dao.TeacherMapper">
<select id="getTeacher" resultType="Teacher">
select * from mybatis.teacher;
</select>
</mapper>
- 编写测试文档
import com.github.dao.TeacherMapper;
import com.github.pojo.Teacher;
import com.github.utils.MybatisUtils;
import org.apache.ibatis.session.SqlSession;
import org.junit.Test;
import java.util.List;
public class MyTest {
@Test
public void FTest(){
SqlSession sqlSession = MybatisUtils.getSqlSession();
TeacherMapper mapper = sqlSession.getMapper(TeacherMapper.class);
List<Teacher> teacherList = mapper.getTeacher();
for (Teacher teacher : teacherList){
System.out.println(teacher);
}
sqlSession.close();
}
}
11.2按照结果嵌套处理
- 修改接口文档
package com.github.dao;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;
import com.github.pojo.Teacher;
import java.util.List;
public interface TeacherMapper {
// 获取老师
// List<Teacher> getTeacher();
// 获取指定老师下的所有的学生及老师信息
Teacher getTeacher(@Param("tid") int id);
}
- 修改xml文档
<!--按结果嵌套查询-->
<select id="getTeacher" resultMap="TeacherStudent">
select s.id sid, s.name sname, t.name tname,t.id tid
from student s,teacher t
where s.tid = t.id and t.id = #{tid};
</select>
<resultMap id="TeacherStudent" type="Teacher">
<result property="id" column="tid"/>
<result property="name" column="tname"/>
<!--复杂的属性,需要单独处理
对象: association 集合: collection
javaType="" 指定属性的类型!
集合中的泛型信息,我们使用ofType获取
-->
<collection property="students" ofType="Student">
<result property="id" column="sid"/>
<result property="name" column="sname"/>
<result property="tid" column="tid"/>
</collection>
</resultMap>
- 测试文档
import com.github.dao.TeacherMapper;
import com.github.pojo.Teacher;
import com.github.utils.MybatisUtils;
import org.apache.ibatis.session.SqlSession;
import org.junit.Test;
import java.util.List;
public class MyTest {
@Test
public void FTest(){
SqlSession sqlSession = MybatisUtils.getSqlSession();
TeacherMapper mapper = sqlSession.getMapper(TeacherMapper.class);
Teacher teacher = mapper.getTeacher(1);
System.out.println(teacher);
sqlSession.close();
}
}
11.3按照查询嵌套处理
Teacher getTeacher2(@Param("tid") int id);
<select id="getTeacher2" resultMap="TeacherStudent2">
select * from mybatis.teacher where id = #{tid}
</select>
<resultMap id="TeacherStudent2" type="Teacher">
<collection property="students" javaType="ArrayList" ofType="Student" select="getStudentByTeacherId" column="id"/>
</resultMap>
<select id="getStudentByTeacherId" resultType="Student">
select * from mybatis.student where tid = #{tid}
</select>
@Test
public void TTest(){
SqlSession sqlSession = MybatisUtils.getSqlSession();
TeacherMapper mapper = sqlSession.getMapper(TeacherMapper.class);
Teacher teacher = mapper.getTeacher2(1);
System.out.println(teacher);
sqlSession.close();
}
小结
- 关联 - association 【多对一】
- 集合 - collection 【一对多】
- javaType & ofType
- JavaType 用来指定实体类中属性的类型
- ofType 用来指定映射到List或者集合中的 pojo类型,泛型中的约束类型!
注意点:
- 保证SQL的可读性,尽量保证通俗易懂!
- 注意一对多和多对一中,属性名和字段的问题!
- 如果问题不好排查错误,可以使用日志 , 建议使用 Log4j!
慢SQL 1s 1000s
面试高频:
- Mysql引擎
- InnoDB底层原理
- 索引
- 索引优化!
12、动态 SQL
什么是动态SQL:动态SQL就是指根据不同的条件生成不同的SQL语句
- 利用动态 SQL 这一特性可以彻底摆脱这种痛苦。
动态 SQL 元素和 JSTL 或基于类似 XML 的文本处理器相似。
在 MyBatis 之前的版本中,有很多元素需要花时间了解。
MyBatis 3 大大精简了元素种类,现在只需学习原来一半的元素便可。
MyBatis 采用功能强大的基于 OGNL 的表达式来淘汰其它大部分元素。
if
choose (when, otherwise)
trim (where, set)
foreach
搭建环境
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;
创建一个基础工程:
- 导包。
- IDutil工具类
package com.github.utils;
import java.util.UUID;
public class IUtils {
public static String genId(){
return UUID.randomUUID().toString().replaceAll("-","");
}
}
- 编写实体类
package com.github.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;
}
- 编写Mapper接口及xml文件
package com.github.dao;
import com.github.pojo.Blog;
import java.util.List;
import java.util.Map;
public interface BlogMapper {
// 新增一个博客
int addBlog(Blog blog);
}
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.github.dao.BlogMapper">
<insert id="addBlog" parameterType="blog">
insert into blog (id, title, author, create_time, views)
values (#{id},#{title},#{author},#{createTime},#{views});
</insert>
</mapper>
- mybatis核心配置文件
<?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>
<properties resource="db.properties">
<property name="username" value="root"/>
<property name="password" value="root"/>
</properties>
<settings>
<setting name="logImpl" value="STDOUT_LOGGING"/>
</settings>
<typeAliases>
<package name="com.github.pojo"/>
</typeAliases>
<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>
<mappers>
<mapper class="com.github.dao.BlogMapper"/>
</mappers>
</configuration>
- 测试类
import com.github.dao.BlogMapper;
import com.github.pojo.Blog;
import com.github.utils.IUtils;
import com.github.utils.MybatisUtils;
import org.apache.ibatis.session.SqlSession;
import org.junit.Test;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
public class MyTest {
@Test
public void addInitBlog(){
SqlSession session = MybatisUtils.getSqlSession();
BlogMapper mapper = session.getMapper(BlogMapper.class);
Blog blog = new Blog();
blog.setId(IUtils.genId());
blog.setTitle("Mybatis如此简单");
blog.setAuthor("功夫河粉");
blog.setCreateTime(new Date());
blog.setViews(998);
mapper.addBlog(blog);
blog.setId(IUtils.genId());
blog.setTitle("Java如此困难");
blog.setCreateTime(new Date());
blog.setViews(998);
mapper.addBlog(blog);
blog.setId(IUtils.genId());
blog.setTitle("Spring如此困难");
blog.setCreateTime(new Date());
blog.setViews(998);
mapper.addBlog(blog);
blog.setId(IUtils.genId());
blog.setTitle("微服务如此困难");
blog.setCreateTime(new Date());
blog.setViews(998);
mapper.addBlog(blog);
session.close();
}
}
- 接口文件
// 查询博客
List<Blog> queryBlogIF(Map map);
- xml文件
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<!--configuration核心配置文件-->
<mapper namespace="com.github.dao.BlogMapper">
<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>
</mapper>
- 测试类
@Test
public void IFTest(){
SqlSession session = MybatisUtils.getSqlSession();
BlogMapper mapper = session.getMapper(BlogMapper.class);
HashMap map = new HashMap();
map.put("title","java如此困难");
List<Blog> blogs = mapper.queryBlogIF(map);
for(Blog blog : blogs){
System.out.println(blog);
}
session.close();
}
choose (when, otherwise)
传入了 “title” 就按 “title” 查找,传入了 “author” 就按 “author” 查找的情形。若两者都没有传入,就返回标记为 featured 的 BLOG(这可能是管理员认 为,与其返回大量的无意义随机 Blog,还不如返回一些由管理员精选的 Blog)。
List<Blog> queryBlogChoose(Map map);
<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>
@Test
public void chooseTest(){
SqlSession session = MybatisUtils.getSqlSession();
BlogMapper mapper = session.getMapper(BlogMapper.class);
HashMap map = new HashMap();
// map.put("title","java如此困难");
map.put("views",998);
List<Blog> blogs = mapper.queryBlogChoose(map);
for(Blog blog : blogs){
System.out.println(blog);
}
session.close();
}
trim (where,set)
// 选择查询
List<Blog> queryBlogIf2(Map map);
// 修改博客
int updateBlog(Map map);
<select id="queryBlogChoose" 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>
<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>
@Test
public void chooseTest(){
SqlSession session = MybatisUtils.getSqlSession();
BlogMapper mapper = session.getMapper(BlogMapper.class);
HashMap map = new HashMap();
map.put("title","java如此困难");
//map.put("views",998);
List<Blog> blogs = mapper.queryBlogIf(map);
for(Blog blog : blogs){
System.out.println(blog);
}
session.close();
}
@Test
public void updateBlog(){
SqlSession session = MybatisUtils.getSqlSession();
BlogMapper mapper = session.getMapper(BlogMapper.class);
HashMap map = new HashMap();
map.put("title","MybatisPlus如此困难");
map.put("id","3690");
mapper.updateBlog(map);
session.close();
}
- 所谓的动态SQL,本质还是SQL语句 , 只是我们可以在SQL层面,去执行一个逻辑代码。
SQL片段
- 有的时候,我们可能会将一些功能的部分抽取出来,方便复用!
-
使用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>
注意事项:
- 最好基于单表来定义SQL片段!
- 不要存在where标签;
Foreach
select * from user where 1=1 and
<foreach item="id" collection="ids"
open="(" separator="or" close=")">
#{id}
</foreach>
(id=1 or id=2 or id=3)
<!--
select * from mybatis.blog where 1=1 and (id=1 or id = 2 or id=3)
现在传递一个万能的map , 这map中可以存在一个集合!
-->
<select id="queryBlogForeach" parameterType="map" resultType="blog">
select * from mybatis.blog
<where>
<foreach collection="ids" item="id" open="and (" close=")" separator="or">
id = #{id}
</foreach>
</where>
</select>
- 动态SQL就是在拼接SQL语句,我们只要保证SQL的正确性,按照SQL的格式,去排列组合就可以了
建议:
- 现在Mysql中写出完整的SQL,再对应的去修改成为我们的动态SQL实现通用即可!