MyBatis 是支持普通 SQL查询,存储过程和高级映射的优秀持久层框架。MyBatis 消除了几乎所有的JDBC代码和参数的手工设置以及结果集的检索。MyBatis 使用简单的 XML或注解用于配置和原始映射,将接口和 Java 的POJOs(Plain Ordinary Java Objects,普通的 Java对象)映射成数据库中的记录。
如何获得Mybatis?
<dependency>
<groupId>org.mybatisgroupId>
<artifactId>mybatisartifactId>
<version>3.5.2version>
dependency>
搭建环境→导入Mybatis→编写代码→测试!
创建数据库和表
CREATE DATABASE `mybatis`;
USE `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,'aaa','123456'),
(2,'bbb','123456'),
(3,'ccc','123456')
<dependencies>
<dependency>
<groupId>mysqlgroupId>
<artifactId>mysql-connector-javaartifactId>
<version>5.1.49version>
dependency>
<dependency>
<groupId>org.mybatisgroupId>
<artifactId>mybatisartifactId>
<version>3.5.2version>
dependency>
<dependency>
<groupId>junitgroupId>
<artifactId>junitartifactId>
<version>4.13version>
dependency>
dependencies>
resources中创建mybatis-config.xml
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">transactionManager>
<dataSource type="POOLED">
<property name="driver" value="com.mysql.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://192.168.1.110:3306/mybatis?useSSL=false&useUnicode=true&characterEncoding=UTF-8"/>
<property name="username" value="root"/>
<property name="password" value="P17CKSzBp0q2@866"/>
dataSource>
environment>
environments>
configuration>
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 resourceAsStream = Resources.getResourceAsStream(resource);
sqlSessionFactory = new SqlSessionFactoryBuilder().build(resourceAsStream);
} catch (IOException e) {
e.printStackTrace();
}
}
// 有了SqlSessionFactory,就可以从中获得SqlSession的实例了。
// SqlSession 完全包含了面向数据库执行SQL命令所需的全部方法
public static SqlSession getSqlSession(){
SqlSession sqlSession = sqlSessionFactory.openSession();
return sqlSession;
}
}
public interface UserDao {
List<User> getUserList();
}
DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.meng.dao.UserDao">
<select id="getUserList" resultType="com.meng.pojo.User">
select * from mybatis.user
select>
mapper>
<build>
<resources>
<resource>
<directory>src/main/resourcesdirectory>
<includes>
<include>**/*.propertiesinclude>
<include>**/*.xmlinclude>
includes>
<filtering>falsefiltering>
resource>
<resource>
<directory>src/main/javadirectory>
<includes>
<include>**/*.propertiesinclude>
<include>**/*.xmlinclude>
includes>
<filtering>falsefiltering>
resource>
resources>
build>
我出现的问题:1. useSSL=fasle,2.
和select相同,只有sql语句要修改
id
方法名
parameterType
sql输入
resultType
sql输出
假设,我们的实体类或者数据库中的表,字段或者参数过多,我们应当考虑使用Map!
// 万能的Map
int addUser2(Map<String,Object> map);
<!-- 传递Map的Key -->
<insert id="addUser2" parameterType="map">
insert into mybatis.user (id, pwd) values (#{
userid},#{
passWord});
</insert>
@Test
public void addUser2(){
SqlSession sqlSession = MybatisUtils.getSqlSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
Map<String, Object> map = new HashMap<String, Object>();
map.put("userid",5);
map.put("passWord","222333");
mapper.addUser2(map);
sqlSession.commit();
sqlSession.close();
}
Map传递参数,直接在sql中取出key即可!【parameterType=“map”】
对象传递参数,直接在sql中取对象的属性即可!【parameterType=“Object”】
只有一个基本类型参数的情况下,可以直接在sql中取到
多个参数用Map,或者注解!
% %
List userList = mapper.getUserLike("%李%");
会产生Sql注入的问题select * from mybatis.user where name like #{value}
List userList = mapper.getUserLike("李");
更安全select * from mybatis.user where name like "%"#{value}"%"
configuration(配置)
properties(属性)
settings(设置)
typeAliases(类型别名)
typeHandlers(类型处理器)
objectFactory(对象工厂)
plugins(插件)
environments(环境配置)
environment(环境变量)
transactionManager(事务管理器)
dataSource(数据源)
databaseIdProvider(数据库厂商标识)
mappers(映射器)
不过要记住:尽管可以配置多个环境,但每个 SqlSessionFactory 实例只能选择一种环境。
学会配置多套运行环境!
Mybatis默认的事务管理器就是JDBC,连接池:POOLED
我们可以通过properties属性来实现引用配置文件
这些属性可以在外部进行配置,并可以进行动态替换。你既可以在典型的 Java 属性文件中配置这些属性,也可以在 properties 元素的子元素中设置。【properties】
driver=com.mysql.jdbc.Driver
url=jdbc:mysql://192.168.1.110:3306/mybatis?useSSL=false&useUnicode=true&characterEncoding=utf8
username=root
password=P17CKSzBp0q2@866
<properties resource="db.properties">
<property name="username" value="root"/>
<property name="password" value="P17CKSzBp0q2@866"/>
properties>
可以直接引入外部文件
可以在其中增加一些属性配置
如果两个文件有同一个字段,优先使用外部配置文件
<typeAliases>
<typeAlias type="com.meng.pojo.User" alias="User"/>
typeAliases>
也可以指定一个包名,MyBatis 会在包名下面搜索需要的 Java Bean,比如:
扫描实体类的包,它的默认别名就为这个类的类名,首字母小写!
<typeAliases>
<package name="domain.blog"/>
typeAliases>
在实体类较少的时候,使用第一种方式,可以DIY设置别名
如果实体类较多,建议使用第二种,不可以自定义别名
若有注解,则别名为注解值。
@Alias("author")
public class Author {
...
}
typeHandlers(类型处理器)
objectFactory(对象工厂)
plugins(插件)
MapperRegistry:注册绑定我们的Mapper文件
<mappers>
<mapper resource="com/meng/dao/UserMapper.xml"/>
mappers>
<mappers>
<mapper class="com.meng.dao.UserMapper"/>
5 mappers>
注意点:
<mappers>
<package name="com.meng.dao"/>
mappers>
生命周期和作用域是至关重要的,因为错误的使用会导致非常严重的并发问题
SqlSessionFactoryBuilder:
SqlSessionFactory
SqlSession
这里的每一个Mapper,就代表一个具体的业务
当查询名与数据表的列名不同时,查出值为null
解决办法
<select id="getUserById" parameterType="int" resultType="User">
select id,name,pwd as password from mybatis.user where id = #{id}
select>
<resultMap id="UserMap" type="User">
<result column="pwd" property="password"/>
resultMap>
<select id="getUserById" resultMap="UserMap">
select * from mybatis.user where id = #{id}
select>
resultMap 元素是 MyBatis 中最重要最强大的元素。
ResultMap 的设计思想是,对简单的语句做到零配置,对于复杂一点的语句,只需要描述语句之间的关系就行了。
如果一个数据库操作,出现了异常,我们就需要排错。日志就是最好的助手。
mybatis-config.xml
<settings>
<setting name="logImpl" value="STDOUT_LOGGING"/>
settings>
<dependency>
<groupId>log4jgroupId>
<artifactId>log4jartifactId>
<version>1.2.17version>
dependency>
#将等级为DEBUG的日志信息输出到console和file这两个目的地,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/meng.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
<settings>
<setting name="logImpl" value="LOG4J"/>
settings>
分页可以减少数据的处理量
// 分页
List<User> getUserByLimit(Map<String,Integer> map);
<select id="getUserByLimit" parameterType="map" resultType="user">
select * from mybatis.user limit #{startIndex},#{pageSize}
select>
@Test
public void getUserByLimit(){
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.getUserByLimit(map);
for (User user: userLimit){
System.out.println(user);
}
sqlSession.close();
}
List<User> getUserByRowBounds();
<select id="getUserByRowBounds" resultMap="UserMap">
select * from mybatis.user
select>
@Test
public void getUserByRowBounds(){
SqlSession sqlSession = MybatisUtils.getSqlSession();
//RowBounds实现
RowBounds rowBounds = new RowBounds(0, 2);
//通过java代码层面实现分页
List<User> userList = sqlSession.selectList("com.meng.dao.UserMapper.getUserByRowBounds",null,rowBounds);
for (User user : userList) {
System.out.println(user);
}
sqlSession.close();
}
有这个东西奥,真的。
@Select("select * from user")
List<User> getUsers();
<mappers>
<mapper class="com.meng.dao.UserMapper"/>
mappers>
Mybatis详细的执行流程!
public static SqlSession getSqlSession(){
return sqlSessionFactory.openSession(true);
}
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);
}
User user = mapper.getUserById(1);
System.out.println(user);
User user = new User(6, "mxc", "12345");
mapper.addUser(user);
User user = new User(6, "牛逼", "123432");
mapper.updateUser(user);
mapper.deleteUser(6);
@Param("")
中设定的属性名!#{}
和${}
相比,#{}
有更高的安全性(防止SQL注入)使用步骤:
<dependency>
<groupId>org.projectlombokgroupId>
<artifactId>lombokartifactId>
<version>1.18.22version>
<scope>providedscope>
dependency>
@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
多个学生对应一个老师
按查询嵌套处理
<select id="getStudent" resultMap="StudentTeacher">
select * from mybatis.student
select>
<resultMap id="StudentTeacher" type="Student">
<result property="id" column="id"/>
<result property="name" column="name"/>
<association property="teacher" column="tid" javaType="Teacher" select="getTeacher"/>
resultMap>
<select id="getTeacher" resultType="Teacher">
select * from mybatis.teacher where id = #{id}
select>
按查询结果嵌套
<select id="getStudent2" resultMap="StudentTeacher2">
select s.id sid,s.name sname,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"/>
association>
resultMap>
回顾Mysql多对一查询方式:
一个老师对应多个学生
按结果嵌套处理
<select id="getTeacher" resultMap="TeacherToStudents">
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="TeacherToStudents" type="Teacher">
<result property="id" column="tid"/>
<result property="name" column="tname"/>
<collection property="students" ofType="Student">
<result property="id" column="sid"/>
<result property="name" column="sname"/>
<result property="tid" column="tid"/>
collection>
resultMap>
按查询结果嵌套
<select id="getTeacher2" resultMap="TeacherToStudents2">
select * from teacher t where t.id = #{tid}
select>
<resultMap id="TeacherToStudents2" type="Teacher">
<result property="id" column="id"/>
<result property="name" column="name"/>
<collection property="students" column="id" ofType="Student" select="getStudent"/>
resultMap>
<select id="getStudent" resultType="Student">
select * from student where tid = #{id}
select>
小结
面试高频
动态SQL是根据不同的条件生成不同的SQL语句
在SQL层面,去执行一个逻辑代码
CREATE TABLE `mybatis`.`blog` (
`id` int(10) NOT NULL AUTO_INCREMENT COMMENT '博客id',
`title` varchar(30) NOT NULL COMMENT '博客标题',
`author` varchar(30) NOT NULL COMMENT '博客作者',
`create_time` datetime(0) NOT NULL COMMENT '创建时间',
`views` int(30) NOT NULL COMMENT '浏览量',
PRIMARY KEY (`id`)
)
创建一个工程
@Data
public class Blog {
private int 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>
<select id="findActiveBlogLike"
resultType="Blog">
SELECT * FROM BLOG WHERE state = ‘ACTIVE’
<choose>
<when test="title != null">
AND title like #{title}
when>
<when test="author != null and author.name != null">
AND author_name like #{author.name}
when>
<otherwise>
AND featured = 1
otherwise>
choose>
select>
测试步骤:
@Test
public void test(){
SqlSession sqlSession = MybatisUtils.getSqlSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
User user1 = mapper.getUserById(1);
System.out.println(user1.toString());
System.out.println("====================");
User user2 = mapper.getUserById(1);
System.out.println(user1.toString());
System.out.println(user1==user2);
sqlSession.close();
}
缓存失效的情况
sqlSession.clearCache();
一级缓存默认开启,只在一次sqlSession中有效,也就是拿到链接关闭连接这个区间段!
一级缓存开启(SqlSession级别的缓存,也称为本地缓存)
步骤:
在UserMapper.xml中添加
<cache/>
<setting name="cacheEnabled" value="true"/>
<cache
eviction="FIFO"
flushInterval="60000"
size="512"
readOnly="true"/>
这个更高级的配置创建了一个 FIFO 缓存,每隔 60 秒刷新,最多可以存储结果对象或列表的 512 个引用,而且返回的对象被认为是只读的,因此对它们进行修改可能会在不同线程中的调用者产生冲突。
可用的清除策略有:
LRU
– 最近最少使用:移除最长时间不被使用的对象。
FIFO
– 先进先出:按对象进入缓存的顺序来移除它们。
SOFT
– 软引用:基于垃圾回收器状态和软引用规则移除对象。
WEAK
– 弱引用:更积极地基于垃圾收集器状态和弱引用规则移除对象。
implements Serializable
只要开启了二级缓存,在同一个Mapper下就有效
所有的数据都会放在一级缓存中
只有当前会话提交,或者关闭的时候,才会提交到二级缓存中
注意:
<select id="getUserById" resultType="User" useCache="true">
select * from mybatis.user where id = #{id}
select>
Ehcache是一种广泛使用的开源Java分布式缓存。主要面向通用缓存
<dependency>
<groupId>org.mybatis.cachesgroupId>
<artifactId>mybatis-ehcacheartifactId>
<version>1.2.1version>
dependency>
在Mapper中指定使用ehcache缓存实现
<cache-ref namespace="com.someone.application.data.SomeMapper"/>
=============================end
SqlSession空指针异常,是xml与接口映射有问题