1、新建一个Maven项目
2、删除src目录
3、导入maven依赖
<dependencies>
<dependency>
<groupId>org.mybatisgroupId>
<artifactId>mybatisartifactId>
<version>3.5.9version>
dependency>
<dependency>
<groupId>mysqlgroupId>
<artifactId>mysql-connector-javaartifactId>
<version>8.0.28version>
dependency>
<dependency>
<groupId>junitgroupId>
<artifactId>junitartifactId>
<version>4.13.2version>
<scope>testscope>
dependency>
dependencies>
编写mybatis核心配置文件
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/employees?useSSL=true&useUnicode=true&characterEncoding=UTF-8"/>
<property name="username" value="root"/>
<property name="password" value="liuqicheng"/>
dataSource>
environment>
environments>
<mappers>
<mapper resource="org/mybatis/example/BlogMapper.xml"/>
mappers>
configuration>
编写mybatis工具类
public class MybatisUtils {
private static SqlSessionFactory sqlSessionFactory;
// 使用mybatis第一步:获取SQLSessionFactory对象
static {
String resource = "mybatis-config.xml";
try {
InputStream inputStream = Resources.getResourceAsStream(resource);
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
} catch (IOException e) {
e.printStackTrace();
}
}
// 既然有了 SqlSessionFactory,顾名思义,我们可以从中获得 SqlSession 的实例。
// SqlSession 提供了在数据库执行 SQL 命令所需的所有方法。你可以通过 SqlSession 实例来直接执行已映射的 SQL 语句。
public static SqlSession getSqlSession(){
return sqlSessionFactory.openSession();
}
}
实体类
public class User {
private int employee_id;
private String first_name;
private String last_name;
private String email;
public User(int employee_id, String first_name, String last_name, String email) {
this.employee_id = employee_id;
this.first_name = first_name;
this.last_name = last_name;
this.email = email;
}
public User() {
}
public int getEmployee_id() {
return employee_id;
}
public void setEmployee_id(int employee_id) {
this.employee_id = employee_id;
}
public String getFirst_name() {
return first_name;
}
public void setFirst_name(String first_name) {
this.first_name = first_name;
}
public String getLast_name() {
return last_name;
}
public void setLast_name(String last_name) {
this.last_name = last_name;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
@Override
public String toString() {
return "User{" +
"employee_id=" + employee_id +
", first_name='" + first_name + '\'' +
", last_name='" + last_name + '\'' +
", email='" + email + '\'' +
'}';
}
}
Dao接口
public interface UserDao {
List<User> getUserList();
}
接口实现类由原来的impl转变成一个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">
<mapper namespace="com.xlb.dao.UserDao">
<select id="getUserList" resultType="com.xlb.pojo.User">
select * from atguigudb.employees
</select>
</mapper>
public class UserDaoTest {
@Test
public void test(){
// 获得sqlSession对象
SqlSession sqlSession = MybatisUtils.getSqlSession();
// 方式一:getMapper()执行SQL
UserDao mapper = sqlSession.getMapper(UserDao.class);
List<User> userList = mapper.getUserList();
for (User user : userList) {
System.out.println(user);
}
sqlSession.close();
}
}
namespace中的包名要和Dao/mapper接口的包名一致
查询:
编写接口
// 查询全部用户
List<User> getUserList();
// 查询指定用户
User getUserById(int id);
编写对应mapper中的sql语句
<select id="getUserList" resultType="com.xlb.pojo.User">
select *
from mybatis.user
select>
<select id="getUserById" parameterType="int" resultType="com.xlb.pojo.User">
select *
from mybatis.user
where id = #{id};
select>
测试
@Test
public void test() {
// 获得sqlSession对象
SqlSession sqlSession = MybatisUtils.getSqlSession();
// 方式一:getMapper()执行SQL
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
List<User> userList = mapper.getUserList();
for (User user : userList) {
System.out.println(user);
}
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();
}
// 插入一个用户
int addUser(User user);
<insert id="addUser" parameterType="com.xlb.pojo.User">
insert into mybatis.user(id, name, pwd)
VALUES (#{id}, #{name}, #{pwd})
insert>
@Test
public void addUser() {
SqlSession sqlSession = MybatisUtils.getSqlSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
int user = mapper.addUser(new User(4, "xlb4", "4783933"));
if (user > 0) {
System.out.println("success!");
}
// 提交事务
sqlSession.commit();
sqlSession.close();
}
// 修改用户
int updateUser(User user);
<update id="updateUser" parameterType="com.xlb.pojo.User">
update mybatis.user
set pwd = #{pwd}
where id = #{id};
update>
@Test
public void updateUser() {
SqlSession sqlSession = MybatisUtils.getSqlSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
int user = mapper.updateUser(new User(4, "xlb4", "22345"));
if (user > 0) {
System.out.println("success");
}
sqlSession.commit();
sqlSession.close();
}
// 删除用户
int deleteUser(User user);
<delete id="deleteUser" parameterType="com.xlb.pojo.User">
delete
from mybatis.user
where id = #{id};
delete>
@Test
public void deleteUser() {
SqlSession sqlSession = MybatisUtils.getSqlSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
int user = mapper.deleteUser(new User(4, "", ""));
if (user > 0) {
System.out.println("success");
}
sqlSession.commit();
sqlSession.close();
}
假设实体类中或数据库中的表,字段或参数过多,我们应当考虑使用Map
int addUser2(Map<String,Object> map);
<insert id="addUser2" parameterType="map">
insert into mybatis.user(id, name, pwd)
VALUES (#{userid}, #{username}, #{password})
insert>
@Test
public void addUser2(){
SqlSession sqlSession = MybatisUtils.getSqlSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
Map<String, Object> map = new HashMap<>();
map.put("userid",5);
map.put("username","xlb5");
map.put("password","32424");
mapper.addUser2(map);
sqlSession.commit();
sqlSession.close();
}
List<User> getUserLike(String s);
<select id="getUserLike" resultType="com.xlb.pojo.User">
select *
from mybatis.user
where name like #{value}
select>
@Test
public void getUserLike() {
SqlSession sqlSession = MybatisUtils.getSqlSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
List<User> users = mapper.getUserLike("%xlb%");
for (User user : users) {
System.out.println(user);
}
sqlSession.close();
}
MyBatis 可以配置成适应多种环境
不过要记住:尽管可以配置多个环境,但每个 SqlSessionFactory 实例只能选择一种环境。
Mybatis默认的事务管理器就是JDBC
我们可以通过properties属性来实现引用配置文件
这些属性可以在外部进行配置,并可以进行动态替换。你既可以在典型的 Java 属性文件中配置这些属性,也可以在 properties 元素的子元素中设置。【db.properties】
db.properties
drive = com.mysql.cj.jdbc.Driver
url=jdbc:mysql://localhost:3306/mybatis?useSSL=false&useUnicode=true&characterEncoding=UTF-8&nullCatalogMeansCurrent=true&useLegacyDatetimeCode=false&serverTimezone=UTC
username=root
password=liuqicheng
<properties resource="db.properties">
<property name="username" value="root"/>
<property name="password" value="liuqicheng"/>
properties>
类型别名可为 Java 类型设置一个缩写名字。 它仅用于 XML 配置,意在降低冗余的全限定类名书写。
<typeAliases>
<typeAlias type="com.xlb.pojo.User" alias="User"/>
typeAliases>
也可以指定一个包名,MyBatis 会在包名下面搜索需要的 Java Bean
扫描实体类的包,他的默认就是这个类的类名,首字母小写
<typeAliases>
<package name="com.xlb.pojo"/>
typeAliases>
实体类比较少的情况下用第一种方式
实体类比较多的情况下用第二种
前者可以diy,后者不可以,如果非要修改,则需要在实体类前使用注解@Alias(“user”)
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-VVdGllZ7-1648003593332)(Mybatis.assets/image-20220321194642901.png)]
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-RFdtFpdc-1648003593334)(Mybatis.assets/image-20220321194708311-16478632299791.png)]
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-F7apBcJA-1648003593334)(Mybatis.assets/image-20220321194722765-16478632439392.png)]
既然 MyBatis 的行为已经由上述元素配置完了,我们现在就要来定义 SQL 映射语句了。 但首先,我们需要告诉 MyBatis 到哪里去找到这些语句。 在自动查找资源方面,Java 并没有提供一个很好的解决方案,所以最好的办法是直接告诉 MyBatis 到哪里去找映射文件。 你可以使用相对于类路径的资源引用,或完全限定资源定位符(包括 file:///
形式的 URL),或类名和包名等。例如:
<mappers>
<mapper resource="org/mybatis/builder/AuthorMapper.xml"/>
<mapper resource="org/mybatis/builder/BlogMapper.xml"/>
<mapper resource="org/mybatis/builder/PostMapper.xml"/>
mappers>
<mappers>
<mapper class="org.mybatis.builder.AuthorMapper"/>
<mapper class="org.mybatis.builder.BlogMapper"/>
<mapper class="org.mybatis.builder.PostMapper"/>
mappers>
注意点:
<mappers>
<package name="org.mybatis.builder"/>
mappers>
注意点:
不同作用域和生命周期类别是至关重要的,因为错误的使用会导致非常严重的并发问题。
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-J8PqJQhw-1648003593335)(Mybatis.assets/image-20220321203634713-16478661969773.png)]
private int id;
private String name;
private String password;
测试
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-LWEaxi33-1648003593336)(Mybatis.assets/image-20220321203718590-16478662403874.png)]
解决方法:
<select id="getUserById" parameterType="int" resultType="com.xlb.pojo.User">
select id,name,pwd password
from mybatis.user
where id = #{id};
select>
<resultMap id="UserMap" type="int">
<result property="password" column="pwd"/>
resultMap>
<select id="getUserById" parameterType="int" resultMap="UserMap">
select *
from mybatis.user
where id = #{id};
select>
如果一个数据库操作出现异常,日志是最好的排错助手
曾经:sout,debug
现在:日志工厂
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-V5qDDxjc-1648003593338)(Mybatis.assets/image-20220321214548122-16478703807392.png)]
SLF4J
LOG4J
LOG4J2
JDK_LOGGING
COMMONS_LOGGING
STDOUT_LOGGING
NO_LOGGING
具体用那个日志在设置中配置
<settings>
<setting name="logImpl" value="STDOUT_LOGGING"/>
settings>
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-VbfxUjKy-1648003593338)(Mybatis.assets/image-20220321215154397-16478707166833.png)]
什么是LOG4J?
先导包
<dependency>
<groupId>org.apache.logging.log4jgroupId>
<artifactId>log4jartifactId>
<version>2.17.2version>
<type>pomtype>
dependency>
配置log4j
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/kuang.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
配置实现
<setting name="logImpl" value="LOG4J"/>
使用:
import org.apache.log4j.Logger;
static Logger logger = Logger.getLogger(UserDaoTest.class);
3.测试
@Test
public void testLog4j(){
logger.info("info:进入了testLog4j");
logger.debug("debug:进入了testLog4j");
logger.error("error:进入了testLog4j");
}
使用Mybatis实现分页,核心SQL
List<User> getUserLimit(Map<String,Object> 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, Object> map = new HashMap<>();
map.put("startIndex",0);
map.put("pageSize",2);
List<User> userList = mapper.getUserLimit(map);
for (User user : userList) {
System.out.println(user);
}
sqlSession.close();
}
不再使用SQL实现分页
List<User> getUserRowBounds(Map<String, Object> map);
<select id="getUserRowBounds" resultMap="UserMap">
select *
from mybatis.user;
select>
@Test
public void getUserRowBounds(){
SqlSession sqlSession = MybatisUtils.getSqlSession();
RowBounds rowBounds = new RowBounds(1, 2);
// 通过java代码层面
List<Object> list = sqlSession.selectList("com.xlb.dao.UserMapper.getUserRowBounds",null,rowBounds);
for (Object o : list) {
System.out.println(o);
}
sqlSession.close();
}
1.注解在接口上实现
public interface UserMapper {
@Select("select * from user")
List<User> getUsers();
}
2.需要在核心配置文件中绑定借口
<mappers>
<mapper class="com.xlb.dao.UserMapper"/>
mappers>
3.测试
@Test
public void test() {
SqlSession sqlSession = MybatisUtils.getSqlSession();
// 底层主要运用反射
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
List userList = mapper.getUsers();
for (User user : userList) {
System.out.println(user);
}
sqlSession.close();
}
本质是反射机制实现
底层是动态代理
在工具类创建的时候实现自动提交事务
//@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);
@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(6, "xlb6", "21383"));
sqlSession.close();
}
@Test
public void updateUser(){
SqlSession sqlSession = MybatisUtils.getSqlSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
mapper.updateUser(new User(5,"xlb4","54324"));
sqlSession.close();
}
@param()注解
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.
使用步骤:
@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
experimental @var
@UtilityClass
@Data:无参构造、get、set、tostring、hashcode、equals
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-J59OIYVg-1648003593339)(Mybatis.assets/image-20220322151540258-16479333422781.png)]
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');
测试环境搭建
<select id="getStudent" resultMap="StudentTeacher">
select *
from mybatis.student;
select>
<resultMap id="StudentTeacher" type="Student">
<id property="id" column="id"/>
<id 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>
实体类
@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;
}
<select id="getTeacher" resultMap="TeacherStudent">
select s.id sid, s.name sname, t.id tid, t.name tname
from mybatis.teacher t,
mybatis.student s
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"/>
<collection property="students" ofType="Student">
<result property="id" column="sid"/>
<result property="name" column="name"/>
<result property="tid" column="tid"/>
collection>
resultMap>
<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>
小结:
关联-association【多对一】
集合-collection【一对多】
javaType & ofType
注意:
就是指根据不同的条件生成不同的sql语句
JSTL 或任何基于类 XML 语言的文本处理器,你对动态 SQL 元素可能会感觉似曾相识。在 MyBatis 之前的版本中,需要花时间了解大量的元素。借助功能强大的基于 OGNL 的表达式,MyBatis 3 替换了之前的大部分元素,大大精简了元素种类,现在要学习的元素种类比原来的一半还要少。
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
创建一个基础工程
@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="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>
<select id="queryBlogIf" parameterType="map" resultType="blog">
select *
from mybatis.blog
<where>
<if test="title != null">
and 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>
有时候,可以将一些功能抽取出来,方便复用
<sql id="if-title-author">
<if test="title != null">
and title = #{title}
if>
<if test="author != null">
and author = #{author}
if>
sql>
<select id="queryBlogIf" parameterType="map" resultType="blog">
select *
from mybatis.blog
<where>
<include refid="if-title-author">include>
where>
select>
注意:
<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>
@Test
public void queryBlogForeach() {
SqlSession sqlSession = MybatisUtils.getSqlSession();
BlogMapper mapper = sqlSession.getMapper(BlogMapper.class);
HashMap map = new HashMap();
ArrayList<Integer> ids = new ArrayList<>();
for (int i = 1; i < 3; i++) {
ids.add(i);
}
map.put("ids", ids);
List<Blog> blogList = mapper.queryBlogForeach(map);
for (Blog blog : blogList) {
System.out.println(blog);
}
sqlSession.close();
}
动态SQL就是在拼接SQL语句
什么是缓存[Cache]?
为什么使用缓存
什么样的数据使用缓存?
测试步骤:
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-2xoltZXj-1648003593341)(Mybatis.assets/image-20220322222413605-16479590549982.png)]
缓存失效的情况:
步骤:
<setting name="cacheEnabled" value="true"/>
<cache
eviction="FIFO"
flushInterval="60000"
size="512"
readOnly="true"/>
小结: