简介
Maven仓库
<!-- https://mvnrepository.com/artifact/org.mybatis/mybatis -->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.5.6</version>
</dependency>
文档
持久层
功能
- 数据持久化(将数据存储到数据库里)
Mybatis的优点
- 简单易学:本身就很小且简单。没有任何第三方依赖,最简单安装只要两个jar文件+配置几个sql映射文件易于学习,易于使用,通过文档和源代码,可以比较完全的掌握它的设计思路和实现。
- 灵活:mybatis不会对应用程序或者数据库的现有设计强加任何影响。 sql写在xml里,便于统一管理和优化。通过sql语句可以满足操作数据库的所有需求。
- 解除sql与程序代码的耦合:通过提供DAO层,将业务逻辑和数据访问逻辑分离,使系统的设计更清晰,更易维护,更易单元测试。sql和代码的分离,提高了可维护性。
- 提供映射标签,支持对象与数据库的orm字段关系映射
- 提供对象关系映射标签,支持对象关系组建维护
- 提供xml标签,支持编写动态sql。
第一个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.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>
<mappers>
<mapper resource="org/mybatis/example/BlogMapper.xml"/>
</mappers>
</configuration>
实体类
package com.rjx.pojo;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@NoArgsConstructor
public class User {
private int id;
private String name;
public String pwd;
}
数据表
CREATE TABLE `mybatis`.`user` (
`id` INT NOT NULL AUTO_INCREMENT,
`name` VARCHAR(45) NULL,
`pwd` VARCHAR(45) NULL,
PRIMARY KEY (`id`));
Dao
package com.rjx.dao;
import com.rjx.pojo.User;
import java.util.List;
public interface UserDao {
List<User> getUserList();
}
配置
<?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.rjx.dao.UserDao">
<select id="getUserList" resultType="com.rjx.pojo.User">
select * from user
</select>
</mapper>
pom修改
<build>
<resources>
<resource>
<directory>src/main/java</directory>
<includes>
<include>**/*.properties</include>
<include>**/*.xml</include>
</includes>
<filtering>true</filtering>
</resource>
<resource>
<directory>src/main/resources</directory>
<includes>
<include>**/*.properties</include>
<include>**/*.xml</include>
</includes>
<filtering>true</filtering>
</resource>
</resources>
</build>
mybatis-config修改
<mappers>
<mapper resource="com/rjx/dao/UserMapper.xml"/>
</mappers>
测试
package com.rjx.dao;
import com.rjx.pojo.User;
import com.rjx.utils.MybatisUtil;
import org.apache.ibatis.session.SqlSession;
import org.junit.Test;
import java.util.List;
public class UserMapperTest {
@Test
public void test(){
SqlSession sqlSession = MybatisUtil.getSqlSession();
UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
List<User> userList = userMapper.getUserList();
// 另一种方法
// List<User> userList = sqlSession.selectList("com.rjx.dao.UserDao.getUserList");
for (User user : userList){
System.out.println(user);
}
sqlSession.close();
}
}
基本CRUD
select
见第一个Mybatis语句
- id:namespace中的方法名
- resultType:SQL语句返回值类型
- parameterType:参数类型
insert
DAO
package com.rjx.dao;
import com.rjx.pojo.User;
import java.util.List;
public interface UserMapper {
List<User> getUserList();
User getUserById(int id);
int addUser(User user);
int updateUser(User user);
int deleteUser(int id);
}
关联配置
<insert id="addUser" parameterType="com.rjx.pojo.User">
insert into user (id, name, pwd) values (null,#{name},#{pwd});
</insert>
测试
@Test
public void addUser(){
SqlSession sqlSession = MybatisUtil.getSqlSession();
UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
int res = userMapper.addUser(new User(4,"name4","123456"));
if(res > 0)
System.out.println("insert successfully");
sqlSession.commit();
sqlSession.close();
}
udate
DAO
package com.rjx.dao;
import com.rjx.pojo.User;
import java.util.List;
public interface UserMapper {
List<User> getUserList();
User getUserById(int id);
int addUser(User user);
int updateUser(User user);
int deleteUser(int id);
}
关联配置
<update id="updateUser" parameterType="com.rjx.pojo.User">
update user set name=#{name}, pwd=#{pwd} where id = #{id};
</update>
测试
@Test
public void updateUser(){
SqlSession sqlSession = MybatisUtil.getSqlSession();
UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
int res = userMapper.updateUser(new User(6,"NAME6","123456"));
if(res > 0)
System.out.println("update successfully");
sqlSession.commit();
sqlSession.close();
}
delete
DAO
package com.rjx.dao;
import com.rjx.pojo.User;
import java.util.List;
public interface UserMapper {
List<User> getUserList();
User getUserById(int id);
int addUser(User user);
int updateUser(User user);
int deleteUser(int id);
}
关联配置
<delete id="deleteUser" parameterType="int">
delete from user where id = #{id};
</delete>
测试
@Test
public void deleteUser(){
SqlSession sqlSession = MybatisUtil.getSqlSession();
UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
int res = userMapper.deleteUser(1);
if(res > 0)
System.out.println("delete successfully");
sqlSession.commit();
sqlSession.close();
}
模糊查询
DAO
package com.rjx.dao;
import com.rjx.pojo.User;
import java.util.List;
import java.util.Map;
public interface UserMapper {
List<User> getUserList();
User getUserById(int id);
List<User> getUserLike(String expression);
int addUser(User user);
int updateUser(User user);
int deleteUser(int id);
int addUser_Map(Map<String,Object> map);
}
关联配置
<select id="getUserLike" resultType="com.rjx.pojo.User" parameterType="String">
select * from user where name like #{expression};
</select>
测试
@Test
public void getUserLike(){
SqlSession sqlSession = MybatisUtil.getSqlSession();
UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
List<User> userList = userMapper.getUserLike("%王%");
for (User user : userList){
System.out.println(user);
}
sqlSession.close();
}
配置解析
核心配置文件
mybatis-config.xml
properties
1. 通过使用properties类引用文件
2. 可以半导入半使用
3. 外部文件优先级高
外部文件
driver=com.mysql.cj.jdbc.Driver
url=jdbc:mysql://localhost:3306/mybatis?useSSL=true&useUnicode=true&characterEncoding=UTF-8&serverTimezone=GMT%2B8
password=123456
导入
<properties resource="db.properties">
<property name="username" value="root"/>
</properties>
setting
typeAliases
功能
- 减少类名的冗余
类别名
<typeAliases>
<typeAlias type="com.rjx.pojo.User" alias="User"></typeAlias>
</typeAliases>
包别名
<typeAliases>
<package name="com.rjx.pojo"/>
</typeAliases>
注解形式
@Alias("alias")
public class className{
}
效果
<select id="getUserById" resultType="User" parameterType="int">
select * from user where id = #{id};
</select>
environments
- mybatis 可以适配多个环境
- 每次只能使用一个环境
environment
transactionManager
dataSource
- pool:数据库连接池,使用完后可以回收连接
- JNDI:不怎么用
mappers
-
方式1(资源绑定)
<mappers> <mapper resource="com/rjx/dao/UserMapper.xml"/> </mappers>
-
类绑定(Mapper需与接口在同一文件夹且接口与Mapper同名)
<mappers> <mapper class="com.rjx.dao.UserMapper"></mapper> </mappers>
-
包绑定
<mappers> <package name="com.rjx.dao"/> </mappers>
生命周期和作用域
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-zoE56pfX-1645076645573)(figures/Mybatis/image-20210815101255710.png)]
SqlSessionFactoryBuilder
- 创建SQLSessionFactory
- 局部变量
SQLSessionFactory
- 相当于数据库连接池
- 一旦创建就应该一直存在 不应该创建多个
- 最简单的就是使用单例模式或是静态单例模式
SQLSession
- 每个线程都应有一个SqlSession实例,是连接到连接池的一个请求
- 线程不安全,其最佳作用域是方法作用域,用完须关闭
ResultMap
语法
<resultMap id="UserMap" type="user">
<result column="id" properties="id"/>
<result column="name" properties="name"/>
<result column="pwd" properties="password"/>
</resultMap>
<!--使用Map进行结果集映射-->
<select id="getUserById" resultMap="UserMap">
select *from user where id = #{id}
</select>
日志工厂
STDOUT_LOGGING
log4j
导入依赖
<!-- https://mvnrepository.com/artifact/log4j/log4j -->
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.17</version>
</dependency>
配置
# Global logging configuration
# 设置日志输出级别以及输出目的地,可以设置多个输出目的地,开发环境下,日志级别要设置成DEBUG或者ERROR
# 前面写日志级别,逗号后面写输出目的地:我自己下面设置的目的地相对应,以逗号分开
# log4j.rootLogger = [level],appenderName1,appenderName2,…
log4j.rootLogger=DEBUG,CONSOLE,LOGFILE
#### 控制台输出 ####
log4j.appender.CONSOLE=org.apache.log4j.ConsoleAppender
# 输出到控制台
log4j.appender.CONSOLE.Target = System.out
# 指定控制台输出日志级别
log4j.appender.CONSOLE.Threshold = DEBUG
# 默认值是 true, 表示是否立即输出
log4j.appender.CONSOLE.ImmediateFlush = true
# 设置编码方式
log4j.appender.CONSOLE.Encoding = UTF-8
# 日志输出布局
log4j.appender.CONSOLE.layout=org.apache.log4j.PatternLayout
# 如果日志输出布局为PatternLayout 自定义级别,需要使用ConversionPattern指定输出格式
log4j.appender.CONSOLE.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} %5p (%c:%L) - %m%n
#### 输出错误信息到文件 ####
log4j.appender.LOGFILE=org.apache.log4j.FileAppender
# 指定输出文件路径
#log4j.appender.LOGFILE.File =F://Intellij idea/logs/error.log
log4j.appender.LOGFILE.File =./logs/error.log
#日志输出到文件,默认为true
log4j.appender.LOGFILE.Append = true
# 指定输出日志级别
log4j.appender.LOGFILE.Threshold = ERROR
# 是否立即输出,默认值是 true,
log4j.appender.LOGFILE.ImmediateFlush = true
# 设置编码方式
log4j.appender.LOGFILE.Encoding = UTF-8
# 日志输出布局
log4j.appender.LOGFILE.layout = org.apache.log4j.PatternLayout
# 如果日志输出布局为PatternLayout 自定义级别,需要使用ConversionPattern指定输出格式
log4j.appender.LOGFILE.layout.ConversionPattern = %-d{yyyy-MM-dd HH:mm:ss} [ %t:%r ] - [ %p ] %m%n
配置mybatis实现
<settings>
<setting name="logImpl" value="log4j"/>
</settings>
创建
Logger logger = Logger.getLogger(UserMapperTest.class);
使用
@Test
public void testLog4j(){
logger.info("info in log4j");
logger.debug("debug in log4j");
logger.error("error in log4j");
}
注解开发
源文件
@Select("select * from user")
List<User> getUserList();
配置文件
<mappers>
<package name="com.rjx.dao"/>
</mappers>
使用注解CRUD
@Select("select * from user;")
List<User> getUserList();
@Select("select * from user where id = #{id};")
User getUserById(@Param("id") int id);
List<User> getUserLike(String expression);
@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 = #{id};")
int deleteUser(@Param("id") int id);
int addUser_Map(Map<String, Object> map);
")
List getUserList();
## 配置文件
```xml
<mappers>
<package name="com.rjx.dao"/>
</mappers>
使用注解CRUD
@Select("select * from user;")
List<User> getUserList();
@Select("select * from user where id = #{id};")
User getUserById(@Param("id") int id);
List<User> getUserLike(String expression);
@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 = #{id};")
int deleteUser(@Param("id") int id);
int addUser_Map(Map<String, Object> map);