1、简介
1.1什么是Mybatis
MyBatis 是一款优秀的持久层框架
它支持定制化 SQL、存储过程以及高级映射
MyBatis 避免了几乎所有的 JDBC 代码和手动设置参数以及获取结果集
MyBatis 可以使用简单的 XML 或注解来配置和映射原生信息,将接口和 Java 的 POJOs(Plain Ordinary Java Object,普通的 Java对象)映射成数据库中的记录。
MyBatis 本是apache的一个开源项目iBatis, 2010年这个项目由apache software foundation 迁移到了[google code](https://baike.baidu.com/item/google code/2346604),并且改名为MyBatis 。
2013年11月迁移到Github。
如何获取Mybatis
maven
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>x.x.x</version>
</dependency>
Github:https://github.com/mybatis/mybatis-3
1.2持久化
数据持久化
持久化就是将程序的数据在持久状态和瞬时状态转化的过程
内存:断电即失
数据库(Jdbc),io文件持久化
为什么要做数据持久化?
内存贵
有些对象不能丢弃
1.3持久层
Dao层、Service层、Controller层…
完成持久化工作的代码块
层界限十分明显
1.4为什么需要Mybatis?
方面存储数据
传统的jdbc太复杂。框架做了简化、自动化
优点:
(1)简单易学:本身就很小且简单。没有任何第三方依赖,最简单安装只 要两个jar文件+配置几个sql映射文件易于学习,易于使用,通过文档和源 代码,可以比较完全的掌握它的设计思路和实现。
(2)灵活:mybatis不会对应用程序或者数据库的现有设计强加任何影 响。 sql写在xml里,便于统一管理和优化。通过sql语句可以满足操作数据 库的所有需求。
(3)解除sql与程序代码的耦合:通过提供DAO层,将业务逻辑和数据访 问逻辑分离,使系统的设计更清晰,更易维护,更易单元测试。sql和代码 的分离,提高了可维护性。
(4)提供映射标签,支持对象与数据库的orm字段关系映射
(5)提供对象关系映射标签,支持对象关系组建维护
(6)提供xml标签,支持编写动态sql
2、第一个Mybatis程序
2.1 搭建数据库环境
创建数据库、创建表、插入简单的信息即可
CREATE TABLE `user` (
`id` int(20) NOT NULL,
`name` varchar(30) DEFAULT NULL,
`pwd` varchar(30) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
2.2 创建一个模块
1.pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<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.0</modelVersion>
<!--父工程-->
<groupId>com.zyf</groupId>
<artifactId>Mybatis-Study</artifactId>
<packaging>pom</packaging>
<version>1.0-SNAPSHOT</version>
<modules>
<module>mybatis-01</module>
<module>mybatis-01Internet</module>
<module>mybatis-011</module>
<module>mybatis-0111</module>
</modules>
<!--导入依赖-->
<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>
<!--在build中配置resources,来防止我们资源导出失败的问题-->
<build>
<resources>
<resource>
<directory>src/main/resources</directory>
<includes>
<include>**/*.properties</include>
<include>**/*.xml</include>
</includes>
</resource>
<resource>
<directory>src/main/java</directory>
<includes>
<include>**/*.properties</include>
<include>**/*.xml</include>
</includes>
<filtering>true</filtering>
</resource>
</resources>
</build>
</project>
2.编写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>
<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?userSSL=true&
userUnicode=true&characterEncoding=UTF-8"/>
<property name="username" value="root"/>
<property name="password" value="123456"/>
</dataSource>
</environment>
</environments>
<mappers>
<mapper resource="com/zyf/dao/UserMapper.xml"/>
</mappers>
</configuration>
3.编写mybatis的工具类
package com.zyf.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{
//使用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(){
// SqlSession sqlSession = SqlSessionFactory.openSession();
// return sqlSession;
return sqlSessionFactory.openSession();
}
}
2.3编写代码
4.实体类
//实体类
public class User {
private int id;
//private int age;
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 + '\'' +
'}';
}
}
5.Dao接口
package com.zyf.dao;
import com.zyf.pojo.User
import java.util.List;
public interface UserDao {
List<User> getUserList();
}
6.接口实现类由原来的UserDaoImpl转变为一个Mapper配置文件
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<!--namespace = 绑定一个对应的Dao/Mapper接口-->
<mapper namespace="com.zyf.dao.UserDao">
<!--select查询语句-->
<select id="getUserList" resultType="com.zyf.pojo.User">
select * from mybatis.user
</select>
</mapper>
7.测试
import com.zyf.pojo.User;
import com.zyf.utils.MyBatilsUtils;
import org.apache.ibatis.session.SqlSession;
import org.junit.Test;
import java.util.List;
public class UserDaoTest {
@Test
public void test() {
// 获得sqlsession对象
SqlSession sqlSession = MyBatilsUtils.getSqlSession();
//方式一:getMapper
// UserDao userDao = sqlSession.getMapper(UserDao.class);//通过mapper获取类
// List<User> userList = userDao.getUserList();
//方法二:根据方法的返回值返回,限定死了,不建议
List<User> userList = sqlSession.selectList("com.zyf.dao.UserDao.getUserList");
for (User user : userList) {
System.out.println(user);
}
//关闭SqlSession
sqlSession.close();
}
}
bug调试
1.配置文件没存在,mybatis.xml加上Mapper
2.绑定接口错误,初始化异常,UserMapper.xml可能不存在
maven由于约定大于配置,可能遇到写的配置文件无法被导出或者生效的问题,解决方案:
<!--在build中配置resources,来防止我们资源导出失败的问题-->
<build>
<resources>
<resource>
<directory>src/main/resources</directory>
<includes>
<include>**/*.properties</include>
<include>**/*.xml</include>
</includes>
</resource>
<!--手动配置资源过滤,让src/main/java的properties和xml能够被导出-->
<resource>
<directory>src/main/java</directory>
<includes>
<include>**/*.properties</include>
<include>**/*.xml</include>
</includes>
<filtering>true</filtering>
</resource>
</resources>
</build>
3、CRUD
1、namespace
namesapce中的包名要和Dao/mapper保持一致
2、select
选择,查询语句
—id:就是对应的namespace中的方法名
—resultType:sql查询执行语句
—parameterType:参数类型
-
编写接口
//根据id查询用户 User getUserById(int id);
-
编写对应的mapper中的sql语句
<select id="getUserById" parameterType="int" resultType="com.zyf.pojo.User"> select * from mybatis.user where id = #{id} </select>
-
测试
@Test//查询全部 public void getUserById(){ SqlSession sqlSession = MybatilsUtils.getSqlSession(); //获取mapper拿到对象调方法 UserMapper mapper = sqlSession.getMapper(UserMapper.class); User user = mapper.getUserById(1); System.out.println(user); sqlSession.close(); }
3、Insert
<!--对象中的属性可以直接取出来-->
<insert id="addUser" parameterType="com.zyf.pojo.User" >
insert into mybatis.user (id, name, pwd) values (#{id},#{name},#{pwd})
</insert>
4、update
<update id="updateUser" parameterType="com.zyf.pojo.User">
update mybatis.user set name = #{name}, pwd = #{pwd} where id = #{id} ;
</update>
5、Delete
<delete id="deleteUser" parameterType="int">
delete from mybatis.user where id=#{id}
</delete>
注意:
增删改需要提交事务
IDEA如果没有连接数据库,Mapper.xml里的sql查询就不要写数据库名.表名,直接写表名
6、分析错误
—mapper.xml标签不要对应错误,查询是select,删除是delete,增加是Insert,更新是update
—resource绑定mapper,需要使用\路径而不是 . 过去
—程序配置文件mybatis.xml必须符合规范
—NullPointerException, 空指针错误没有注册到资源
—输出的xml文件存在中文乱码问题!
—maven资源没有导出(在pom里的build中配置resources,来防止我们资源导出失败的问题)
7、万能Map
如果遇到我们的实体类或者数据库中的表字段或者参数过多,我们应当使用map
//万能map
int addUser2(Map<String, Object> user);
<!--通过对象中的属性可以直接取出来,传递map中的key--> <insert id="addUser" parameterType="map" > insert into mybatis.user (id, name, pwd) values (#{userid},#{userName},#{password}) </insert>
//测试万能map @Test public void addUser2(){ SqlSession sqlSession = MybatilsUtils.getSqlSession(); UserMapper mapper = sqlSession.getMapper(UserMapper.class); Map<String, Object> map = new HashMap<String, Object>(); map.put("userid",4); map.put("userName","发审委的"); map.put("password","31241341"); mapper.addUser2(map); //提交事物 sqlSession.commit(); sqlSession.close(); }
Map传递参数,直接在sql中取出key即可!(parameterType=“map”)
对象传递参数,直接在sql中取对象的属性即可!(parameterType=“Object”)
只有一个基本类型的参数情况下可以直接在sql中取到!
多个参数用Map,或者注解!
8、思考
模糊查询怎么写?
-
Java Test代码执行的时候,传递通配符 %张% (通配符还可以在mapper xml里的sql里面写)
List<User> userList = mapper.getUserLike("张");
-
在sql拼接中使用通配符
select * from mybatis.user where name like "%"#{value}"%"
4、配置解析
1、核心配置文件
mybatis-config.xml
MyBatis 的配置文件包含了会深深影响 MyBatis 行为的设置和属性信息。 配置文档的顶层结构如下:
-
configuration(配置)
-
environments(环境配置)
- environment(环境变量)
- transactionManager(事务管理器)
- dataSource(数据源)
- environment(环境变量)
2、环境配置(environments)
mybatis可以配置成适应多种环境
牢记:虽然可以配置多套环境,但每个SqlSessionFactory实例只能选择一种环境。id和default一一对应
要学会使用配置多套环境!
mybatis默认的事务管理器是JDBC,连接池:POOLED
3、属性(properties)
可以通过properties属性来实现引用配置文件
这些属性可以在外部进行配置,并可以进行动态替换。你既可以在典型的 Java 属性文件中配置这些属性,也可以在 properties 元素的子元素中设置。(db.properties)
编写一个配置文件(可以写在xml中,但是xml所有的标签都可以规定其顺序)
driver=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/mybatis?userSSL=true&userUnicode=true&characterEncoding=UTF-8
username=root
password=123456
在核心配置文件中引入外部配置文件
<!-- 引入外部配置文件-->
<properties resource="db.properties">
<property name="username" value="root"/>
<property name="pwd" value="123456"/>
</properties>
—可以直接引入外部文件
—可以在外部配置文件中增加一些属性配置
—如果两个文件有同一字段,优先使用外部配置文件的
4、类型别名(typeAliases)
类型别名可为 Java 类型设置一个缩写名字,它仅用于 XML 配置。
意在降低冗余的全限定类名书写
<!-- 可以给实体类起别名-->
<typeAliases>
<typeAlias type="com.zyf.pojo.User" alias="User"/>
</typeAliases>
也可以指定一个包名,MyBatis 会在包名下面搜索需要的 Java Bean,扫描实体类的包,它的默认别名就为这个类的类名,首字母小写。
每一个在包 domain.blog
中的 Java Bean,在没有注解的情况下,会使用 Bean 的首字母小写的非限定类名来作为它的别名。 比如 domain.blog.Author
的别名为 author
;若有注解,则别名为其注解值。
<!-- 可以给实体类起别名--> <typeAliases> <package name="com.zyf.pojo"/> </typeAliases>
在实体类比较少的时候,使用第一种方式。
如果实体类十分多,建议使用第二种包方式。
区别:第一种可以diy别名,第二种就不行,但是第二种可以用注解,需要在pojo中的实体类增加注解,别名为其注解值。
//实体类@Alias("hello")public class User {
5、设置
这是 MyBatis 中极为重要的调整设置,它们会改变 MyBatis 的运行时行为。
6、其他配置
-
mybtis-generator-core
mybatis-plus
通用mapper
7、映射器(mappers)
MapperRegistry:注册绑定我们的Mapper文件
方式一:推荐使用
<!-- 每一个Mapper.xml都要在mybatis核心配置文件中注册-->
<mappers>
<mapper resource="com/zyf/dao/UserMapper.xml"/>
</mappers>
方式二:使用class文件绑定注册
<!-- 每一个Mapper.xml都要在mybatis核心配置文件中注册-->
<mappers>
<!-- <mapper resource="com/zyf/dao/UserMapper.xml"/>-->
<mapper class="com.zyf.dao.UserMapper"/>
</mappers>
注意点:
接口和他的Mapper配置文件必须同名
接口和他的mapper配置文件必须在同一个包下
方式三:使用扫描包进行注入绑定
<!-- 每一个Mapper.xml都要在mybatis核心配置文件中注册-->
<mappers>
<!-- <mapper resource="com/zyf/dao/UserMapper.xml"/>-->
<!-- <mapper class="com.zyf.dao.UserMapper"/>-->
<package name="com.zyf.dao"/>
</mappers>
注意点:
接口和他的Mapper配置文件必须同名
接口和他的mapper配置文件必须在同一个包下
8、生命周期和作用域
生命周期和作用域是至关重要的,因为错误的使用会导致非常严重的并发问题
SqlSessionFactoryBuilder
—这个类可以被实例化、使用和丢弃,一旦创建了 SqlSessionFactory,就不再需要它了。
—SqlSessionFactoryBuilder 实例的最佳作用域是方法作用域(也就是局部方法变量)
SqlSessionFactory
—可以想象为数据库连接池
—SqlSessionFactory 一旦被创建就应该在应用的运行期间一直存在,没有任何理由丢弃它或重新创建另一个实例。
—因此 SqlSessionFactory 的最佳作用域是应用作用域。
— 有很多方法可以做到,最简单的就是使用单例模式或者静态单例模式
SqlSession
—连接到连接池的一个请求
—用完之后赶紧关闭,否则资源被占用!
—SqlSession 的实例不是线程安全的,因此是不能被共享的,所以它的最佳的作用域是请求或方法作用域。
—每个线程都应该有它自己的 SqlSession 实例。
每一个mapper都代表一个具体的业务
5、解决属性名和字段名不一致的问题
用之前的项目模板新建项目,测试实体类字段不一致的情况
public class User {
private int id;
private String name;
//private String pwd;
private String password;
//select * from mybatis.user where id = #{id}
//类型处理器
//select id,name,pwd as password from mybatis.user where id = #{id}
1、起别名
<!-- mybatis-config.xml 可以给实体类起别名-->
<typeAliases>
<!-- <typeAlias type="com.zyf.pojo.User" alias="User"/>-->
<package name="com.zyf.pojo"/>
</typeAliases>
<!--Usermapper.xml-->
<!-- <select id="getUserById" resultType="com.zyf.pojo.User">-->
<!-- select id,name,pwd as password from mybatis.user where id = #{id}-->
<!-- </select>-->
2、resultMap标签
结果集映射
id name pwd
id name password
<!-- 结果集映射-->
<resultMap id="UserMap" type="User">
<!-- column是数据库的字段,property是实体类中的属性-->
<result column="id" property="id"/>
<result column="name" property="name"/>
<result column="pwd" property="password"/>
</resultMap>
<!--select查询语句-->
<select id="getUserById" resultMap="UserMap">
select * from mybatis.user where id = #{id}
</select>
—resultMap
元素是 MyBatis 中最重要最强大的元素
—ResultMap 的设计思想是,对简单的语句做到零配置,对于复杂一点的语句,只需要描述语句之间的关系就行了
—上面的例子没有一个需要显式配置 ResultMap
,这就是 ResultMap
的优秀之处:你完全可以不用显式地配置它们。
6、日志
6.1、日志工厂
如果一个数据库操作出现了异常,我们需要排错。日志就是最好的助手
曾经:sout、debug
现在:日志工厂!
- SLF4J
- LOG4J !!!
- LOG4J2
- JDK_LOGGING
- COMMONS_LOGGING
- STDOUT_LOGGING !!!
- NO_LOGGING
在框架里具体使用哪个日志实现需要在设置中设定!
STDOUT_LOGGING标准日志输出
6.2、LOG4J
—Log4j是Apache的一个开源项目,通过使用Log4j,我们可以控制日志信息输送的目的地是控制台、文件、GUI组件,甚至是套接口服务器、NT的事件记录器、UNIX Syslog守护进程等;
—可以控制每一条日志的输出格式
—通过定义每一条日志信息的级别,我们能够更加细致地控制日志的生成过程。
—可以通过一个配置文件来灵活地进行配置,而不需要修改应用的代码。
1.maven导包配置好log4j的依赖
<!-- https://mvnrepository.com/artifact/log4j/log4j -->
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.17</version>
</dependency>
2.log4j.properties
#将等级为debug的日志信息输出到console和file这两个目的地,console和file的定义在下面的代码中log4j.rootCategory=DEBUG,console,file#控制台输出相关设置log4j.appender.console=org.apache.log4j.ConsoleAppenderlog4j.appender.console.Target=System.outlog4j.appender.console.Threshold=DEBUGlog4j.appender.console.layout=org.apache.log4j.PatternLayoutlog4j.appender.console.layout.ConversionPattern=[%c]-%m%n#文件输出的相关设置log4j.appender.file = org.apache.log4j.RollingFileAppenderlog4j.appender.file.File = ./log/zyf.loglog4j.appender.file.MaxFileSize = 10MBlog4j.appender.file.Threshold=DEBUGlog4j.appender.file.layout=org.apache.log4j.PatternLayoutlog4j.appender.file.layout.ConversionPattern=[%p][%d{yy-MM-dd}][%c]%m%n#日志输出级别log4j.logger.org.mybatis=DEBUGlog4j.logger.java.sql=DEBUGlog4j.logger.java.sql.Statement=DEBUGlog4j.logger.java.sql.ResultSet=DEBUGlog4j.logger.java.sql.PreparedStatement=DEBUG
3.配置log4j为日志实现
<settings> <setting name="logImpl" value="LOG4J"/></settings>
4、测试运行
5、简单使用
-
要导包
import org.apache.log4j.Logger;
-
日志对象,参数为当前类的class
static Logger logger = Logger.getLogger(UserDaoTest.class);
-
日志级别
@Test public void testLog4j(){ logger.info("info:进入了testlog4j"); logger.debug("debug:进入了testlog4j"); logger.error("error:进入了testlog4j"); }}
7、分页
为什么要分页
—减少数据的处理量
7.1使用Limit分页法
语法:SELECT * from user limit startIndex,pageSize;SELECT * from user limit 5;#[0,5]
使用mybatis实现分页,核心sql
1.接口
//分页
List<User> getUserByLimit(Map<String,Integer> map);
2.Mapper.xml
<!-- 分页-->
<select id="getUserByLimit" parameterType="map" resultMap="UserMap">
select * from mybatis.user limit #{startIndex},#{pageSize};
</select>
3.测试
7.2RowBounds分页
不再使用sql实现分页
1.接口
//分页
List<User> getUserByRowBounds();
2.mapper.xml
<!-- getUserByRowBounds分页2-->
<select id="getUserByRowBounds" resultMap="UserMap">
select * from mybatis.user
</select>
3.测试
@Test
public void getUserByRowBounds(){
SqlSession sqlSession = MybatisUtils.getSqlSession();
//通过RowBounds实现
RowBounds rowBounds = new RowBounds(1, 2);
//通过java代码实现分页
List<User> userList = sqlSession.selectList("com.zyf.dao.UserMapper.getUserByRowBounds",null,rowBounds);
for (User user : userList) {
System.out.println(user);
}
sqlSession.close();
}
7.3分页插件
了解即可,工作可能会用
8、使用注解开发
8.1、面向接口编程
8.2、注解在接口上实现
-
注解在接口上实现
public interface UserMapper { @Select("select * from user") List<User> getUsers(); }
-
需要咋核心配置文件中绑定接口
<!-- 绑定接口--> <mappers> <mapper class="com.zyf.dao.UserMapper"/> </mappers>
-
测试
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(); }}
-
本质:反射机制的实现
-
底层:动态代理!
8.3、mybatis详细的执行流程
8.4、CRUD
我们可以在工具类创建的时候实现自动提交事物
//既然有了SqlSessionFactory,顾名思义,我们就可以从中获得SqlSession的实例了 //SqlSession完全包含了买那些数据库执行sql命令所学的所有方法 public static SqlSession getSqlSession(){ return sqlSessionFactory.openSession(true); }
编写接口,增加注解
package com.zyf.dao;import com.zyf.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 getUsreById(@Param("id") int id); @Insert("insert into user(id,name,pwd) values (#{id},#{name},#{pwd})") int addUser(User user); @Update("update user set name=#{name},pwd=#{pwd} where id =#{id}") int updateUser(User user); @Delete("delete from user where id = #{uid}") int deleteUser(@Param("uid") int id);}
测试类
{注意:必须要将接口注册绑定到我们的核心配置文件}
关于@Param()注解
—基本类型的参数或者String类型需要加上
—引用类型不需要加
—如果只有一个基本类型的话,可以忽略,但是建议都加上
—在sql中引用的就是我们这里到的@Param中设置的属性名
#{} 和¥{} 的区别
预编译 没有预编译
**#{}**与JDBC一样创建prearedStatement参数占位符并安全设置参数(就像使用 ? 一样),安全迅速,转义字符
${} 采用的是字符串拼接参数的形式,不太安全,当传入参数为字段名,表名,排序方式,固定常量则可以使用。不转义字符串,有风险,同时存在sql注入,一般设置固定变量,例如字段名。
用 方 式 传 入 数 据 直 接 显 示 在 生 成 的 s q l 中 , 且 {}方式传入数据直接显示在生成的sql中,且 方式传入数据直接显示在生成的sql中,且{}无法防止sql注入,${}一般用来传入数据库的对象,比如数据库表名
注意:mybatis排序的时候使用order by动态参数需要注意,使用${}而不使用#{}
resultMap 它则是结果映射定义,作用是将体现每行记录的映射,其中type属性是接收参数的类型,在resultMap标签中还有常用id标签 一般用于存储接收的id字段,而result标签则指的是其他字段,这两个标签还有**property **和 **column **两个常用属性,property 就是接收type设置对象的值,而column 只的是数据库中对应的字段名,如果对应不上,则接收不到相对应的值
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
使用步骤:
1.IDEA装lombok插件
2.在项目中导入lombok的jar包
<dependencies>
<!-- https://mvnrepository.com/artifact/org.projectlombok/lombok -->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.20</version>
<scope>provided</scope>
</dependency>
</dependencies>
Lombok会改变你如何编写源码,降低了阅读源代码的舒适性
10、多对一处理
10、多对一
多个学生对应一个老师
对于学生而言,多个学生关联一个老师:多对一
对于老师而言:一对多
SQL
use mybatis
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
- 新建实体类Teacher,Student
- 建立Mapper接口
- 建立Mapper.xml文件
- 在核心配置文件中绑定注册我们的Mapper接口或者文件!
- 测试查询能否成功
按照查询嵌套处理
<select id="getStudent" resultMap="StudentTeacher">
select * from student;
</select>
<resultMap id="StudentTeacher" type="com.hou.pojo.Student">
<result property="id" column="id"></result>
<result property="name" column="name"></result>
<!--对象使用assiociation-->
<!--集合用collection-->
<association property="teacher" column="tid"
javaType="com.hou.pojo.Teacher"
select="getTeacher"></association>
</resultMap>
<select id="getTeacher" resultType="com.hou.pojo.Teacher">
select * from teacher where id = #{id};
</select>
MySQL多对一查询
子查询
连表查询
11、一对多
实体类修改
@Data
public class Student {
private int id;
private String name;
private int tid;
}
@Data
public class Teacher {
private int id;
private String name;
//学生需要关联一个老师
private List<Student> students;
}
12、动态SQL
动态SQL就是根据不同的条件生成不同的SQL语句。
动态SQL类似于JSTL 或任何基于类 XML 语言的文本处理器,你对动态 SQL 元素可能会感觉似曾相识。在 MyBatis 之前的版本中,需要花时间了解大量的元素。借助功能强大的基于 OGNL 的表达式,MyBatis 3 替换了之前的大部分元素,大大精简了元素种类,现在要学习的元素种类比原来的一半还要少。
- if
- choose (when, otherwise)
- trim (where, set)
- foreach
搭建环境
use mybait;
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
创建一个基础工程
-
pom
-
编写配置文件
-
编写实体类
@lombok.Data public class Blog { private String id; private String title; private String author; private Data createTime; private int views; }
-
编写实体类对应Mapper接口和Mapper.xml文件
IF
<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>
choose(when,otherwise)
trim(where,set)
where 元素只会在子元素返回任何内容的情况下才插入 “WHERE” 子句。而且,若子句的开头为 “AND” 或 “OR”,where 元素也会将它们去除。
加上where智能拼接,可识别and
<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>
set
set 元素会动态地在行首插入 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>
trim才是总的
如果 where 元素与你期望的不太一样,你也可以通过自定义 trim 元素来定制 where 元素的功能。比如,和 where 元素等价的自定义 trim 元素为:
<trim prefix="WHERE" prefixOverrides="AND |OR ">
--前缀 后缀
...
</trim>
动态SQL就是在SQL层面去执行一个逻辑代码
SQL片段
将一些功能部分抽取出来方便复用
-
使用sql标签抽取公共部分
<sql id="if-title-author"> <if test="title != null"> and 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 nad (id=1 or id=2 or id=3)
<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语句,在对应的去拼接。
13、缓存
Cache缓存
Memcache
在服务器和数据库之间存在,Memcahe提供读,MySQL服务器负责写数据的压力
主从复制,读写一致
Mybatis系统默认定义了二级缓存:一级和二级
默认情况下只有一级缓存开启(AqlSession级别的缓存,也成为本地缓存)
二级缓存需要手动开启和配置,是基于namespace级别的缓存
为了提高扩展性,Mybatis定义了缓存接口Cache,我们可以通过实习Cache接口来自定义二级缓存
一级缓存
缓存失效的情况:
- 查询不同的东西
- 增删改操作,会改变数据,所以必定刷新缓存
- 查询不同的Mapper.xml
- 手动清理缓存
小结:一级缓存默认开启,只在依次sqlSession中有效,也就是拿到连接额关闭的区间段里。
一级缓存相当于一个map
二级缓存
cacheEnabled 全局性地开启或关闭所有映射器配置文件中已配置的任何缓存。 true | false true
二级缓存也叫全局缓存
基于namespace级别的缓存,一个名称空间对应一个二级缓存
工作机制
—一个会话查询一条数据,这个数据就会被放在当前对话一级缓存中
—如果当前会话关闭了,这个会话对应的一级缓存就没有了;但是我们想要的是会话关闭了一级缓存中的数据会被放到二级缓存中。
—新的会话查询信息,就可以从二级缓存中获取内容
—不同的mapper查询出的数据会对应的放在自己对应的缓存(mapper.xml)中
步骤:
1.开启全局缓存
<settings>
<!--标准的日志工厂-->
<setting name="logImpl" value="STDOUT_LOGGING"/>
<!-- <!– 是否开启自动驼峰命名规则–>-->
<!-- <setting name="mapUnderscoreToCamelCase" value="true"/>-->
<!-- 显示开启缓存-->
<setting name="cacheEnabled" value="true"/>
</settings>
2.在要使用二级缓存的mapper中开启
<!-- 在当前mapper。xml中使用二级缓存-->
<cache/>
也可以自定义参数
<!-- 在当前mapper。xml中使用二级缓存-->
<cache eviction="FIFO"
flushInterval="60000"
size="512"
readOnly="true"/>
3.测试
Caused by: java.io.NotSerializableException: com.zyf.pojo.User
没有序列化
解决办法:
public class User implements Serializable