如果对你有帮助的话
为博主点个赞吧
点赞是对博主最大的鼓励
爱心发射~
狂神老师的B站课程:https://www.bilibili.com/video/BV1NE411Q7Nx?spm_id_from=333.999.0.0
本人整理的配套代码:https://download.csdn.net/download/qq_47540091/85094457
环境:
JDK1.8
Mysql 5.7
maven 3.6.1
IDEA
回顾:
JDBC
Mysql
java基础
Maven
Junit
SSM框架:配置文件的。 最好的方式:看官网文档;
MyBatis 是一款优秀的持久层框架,它支持自定义 SQL、存储过程以及高级映射。MyBatis 免除了几乎所有的 JDBC 代码以及设置参数和获取结果集的工作。MyBatis 可以通过简单的 XML 或注解来配置和映射原始类型、接口和 Java POJO(Plain Old Java Objects,普通老式 Java 对象)为数据库中的记录。
MyBatis 本是apache的一个开源项目iBatis, 2010个项目由apache software foundatic迁移google code,并且改名为MyBatis 。
2013年11月迁移到Github。
如何获得Mybatis?
maven仓库
<dependency>
<groupId>org.mybatisgroupId>
<artifactId>mybatisartifactId>
<version>3.5.6version>
dependency>
Github:地址:Github:地址
中文文档:https://mybatis.org/mybatis-3/zh/index.html
地址:上图地址
数据持久化
为什么需要需要持久化?
Dao层,Service层,Controller层…
最重要的一点:使用的人多!
Spring SpringMVC SpringBoot
思路:搭建环境-> 导入Mybatis-> 编写代码-> 测试!
搭建数据库
创建表
插入数据
新建项目
1、新建一个普通的maven项目
2、删除src目录
注意查看
官网:mybatis – MyBatis 3 | 简介
3、 导入依赖
1、编写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.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost:3306/mybatis?useSSL=true&useUnicode=true&characterEncoding=UTF-8"/>
<property name="username" value="root"/>
<property name="password" value="123456"/>
dataSource>
environment>
environments>
<mappers>
<mapper resource="org/mybatis/example/BlogMapper.xml"/>
mappers>
configuration>
2、编写mybatis工具类
String resource = "org/mybatis/example/mybatis-config.xml";
package com.blue.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;
public class MybatisUtils {
private static SqlSessionFactory sqlSessionFactory;
static {
try {
String resource = "mybatis-config.xml";
InputStream inputStream = Resources.getResourceAsStream(resource);
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
} catch (IOException e) {
e.printStackTrace();
}
}
public static SqlSession getSqlSession(){
return sqlSessionFactory.openSession();
}
}
第一步:MabstisUtils
工具类
第二步:resources配置文件mybatis-config.xml
第三步:实体类-User
第四步:接口UserMapper.xml
接口实现类由原来的JserDaolmpl转变为一个Mapper配置文件.
代码复制过来
DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.blue.dao.UserDao">
<select id="getUserList" resultType="com.blue.pojo.User">
select * from mybatis.user
select>
mapper>
新建文件对应好
注意点:
MapperRegistry是什么?
解决
<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.0modelVersion>
<groupId>org.examplecom.bluegroupId>
<artifactId>Mybatis-StudyartifactId>
<packaging>pompackaging>
<version>1.0-SNAPSHOTversion>
<modules>
<module>mybatis-01module>
modules>
<dependencies>
<dependency>
<groupId>org.mybatisgroupId>
<artifactId>mybatisartifactId>
<version>3.5.2version>
dependency>
<dependency>
<groupId>mysqlgroupId>
<artifactId>mysql-connector-javaartifactId>
<version>8.0.20version>
dependency>
<dependency>
<groupId>junitgroupId>
<artifactId>junitartifactId>
<version>4.12version>
<scope>testscope>
dependency>
dependencies>
<properties>
<maven.compiler.source>8maven.compiler.source>
<maven.compiler.target>8maven.compiler.target>
properties>
<build>
<resources>
<resource>
<directory>src/main/javadirectory>
<includes>
<include>**/*.propertiesinclude>
<include>**/*.xmlinclude>
includes>
<filtering>truefiltering>
resource>
<resource>
<directory>src/main/resourcesdirectory>
<includes>
<include>**/*.propertiesinclude>
<include>**/*.xmlinclude>
includes>
<filtering>truefiltering>
resource>
resources>
build>
project>
你们可以能会遇到的问题:
1.配置文件没有注册
2.绑定接口错误。
3.方法名不对
4.返回类型不对
5.Maven导出资源问题
了解方式二
package com.blue.dao;
import com.blue.pojo.User;
import com.blue.utils.MybatisUtils;
import org.apache.ibatis.session.SqlSession;
import org.junit.Test;
import java.util.List;
public class UserDaoText {
@Test
public void test(){
//第一步获取SqlSession对象
SqlSession sqlSession = MybatisUtils.getSqlSession();
// //方式一:执行sql getMapper
// UserDao userDao = sqlSession.getMapper(UserDao.class);
// List<User> userList = userDao.getUserList();
//方式2
List<User> userList = sqlSession.selectList("com.blue.dao.UserDao.getUserList");
for (User user : userList){
System.out.println(user);
}
sqlSession.close();
}
}
方法对比
命名
改三个
namespace中的包名要和Dao/mapper接口的包名一致!
DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.blue.dao.UserMapper">
<select id="getUserList" resultType="com.blue.pojo.User">
select * from mybatis.user
select>
mapper>
选择,查询语句;
package com.blue.dao;
import com.blue.pojo.User;
import java.util.List;
public interface UserMapper {
//可以避免JDBC代码和手动设置参数
List<User> getUserList();
根据ID查询用户
User getUserById(int id);
}
DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.blue.dao.UserMapper">
<select id="getUserList" resultType="com.blue.pojo.User">
select * from mybatis.user
select>
<select id="getUserById" parameterType="int" resultType="com.blue.pojo.User">
select * from mybatis.user where id =#{id}
select>
mapper>
package com.blue.dao;
import com.blue.pojo.User;
import com.blue.utils.MybatisUtils;
import org.apache.ibatis.session.SqlSession;
import org.junit.Test;
import java.util.List;
public class UserDaoText {
@Test
public void test(){
//第一步获取SqlSession对象
SqlSession sqlSession = MybatisUtils.getSqlSession();
try {
//方式一:执行sql getMapper
UserMapper userDao = sqlSession.getMapper(UserMapper.class);
List<User> userList = userDao.getUserList();
// //方式2
List userList = sqlSession.selectList("com.blue.dao.UserDao.getUserList");
for (User user : userList){
System.out.println(user);
}
}catch (Exception e){
e.printStackTrace();
}finally {
sqlSession.close();
}
}
public void getUserById(){
SqlSession sqlSession = MybatisUtils.getSqlSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
User user = mapper.getUserById(1);
System.out.println(user);
sqlSession.close();
}
}
package com.blue.dao;
import com.blue.pojo.User;
import java.util.List;
public interface UserMapper {
//可以避免JDBC代码和手动设置参数
List<User> getUserList();
根据ID查询用户
User getUserById(int id);
//'insert一个用户
int addUser(User user);
}
DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.blue.dao.UserMapper">
<select id="getUserList" resultType="com.blue.pojo.User">
select * from mybatis.user
select>
<select id="getUserById" parameterType="int" resultType="com.blue.pojo.User">
select * from mybatis.user where id =#{id}
select>
<insert id="addUser" parameterType="com.blue.pojo.User">
insert into mybatis.user (id, name, pwd) VALUES (#{id},#{name},#{pwd});
insert>
mapper>
@Test
public void addUser(){
SqlSession sqlSession = MybatisUtils.getSqlSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
int hh = mapper.addUser(new User(4, "hh", "123456"));
if (hh>0){
System.out.println("插入成功");
}
//提交事务
sqlSession.commit();
sqlSession.close();
}
package com.blue.dao;
import com.blue.pojo.User;
import java.util.List;
public interface UserMapper {
//可以避免JDBC代码和手动设置参数
List<User> getUserList();
根据ID查询用户
User getUserById(int id);
//'insert一个用户
int addUser(User user);
//修改用户
int updateUser(User user);
}
<update id="updateUser" parameterType="com.blue.pojo.User">
update mybatis.user
set name = #{name},pwd=#{pwd}
where id=#{id};
update>
@Test
public void updateUser(){
SqlSession sqlSession = MybatisUtils.getSqlSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
mapper.updateUser(new User(4,"hehe","123213"));
sqlSession.commit();
sqlSession.close();
}
//删除一个用户
int deleteUser(int id);
<delete id="deleteUser" parameterType="int">
delete
from mybatis.user
where id=#{id};
delete>
@Test
public void deleteUser(){
SqlSession sqlSession = MybatisUtils.getSqlSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
mapper.deleteUser(4);
sqlSession.commit();
sqlSession.close();
}
注意点:
增删改需要提交事务!
1、标签不要匹配错
2、resource绑定mapper,需要使用路径!
用/,不用点.
3、程序配置文件必须符合规范!
4、空指针异常:NullPointerException,没有注册到资源
5、输出的xl文件中存在中文乱码问题!
6、maven资源没有导出
假设,我们的实体类,或者数据库中的表,字段或者参数过多,我们应当考虑使用Map!
1、编写接口
2、编写对应的mapper中的sql语句
3、测试
1、
2、编写对应的mapper中的sql语句
3、
Map传递参数,直接在sql中取出key即可!
对象传递参数,直接在Sq中取对象的属性即可!
只有一个基本类型参数的情况下,可以直接在Sq中取到!
多个参数用Map,或者注解!
模糊查询怎么写?
Java代码执行的时候,传递通配符%%
List
在sql拼接中使用通配符!
select * from mybatis.user where name like "%"#{value}"%"
1.Java代码执行的时候,传递通配符%%
不加%, 查询不出来
2.在sq拼接中使用通配符!
mybatis-config.xml
MyBatis 的配置文件包含了会深深影响 MyBatis 行为的设置和属性信息。
configuration(配置)
properties(属性)
settings(设置)
typeAliases(类型别名)
typeHandlers(类型处理器)
objectFactory(对象工厂)
plugins(插件)
environments(环境配置)
environment(环境变量)
transactionManager(事务管理器)
dataSource(数据源)
databaseIdProvider(数据库厂商标识)
mappers(映射器)
新建模块
MyBatis可以配置成适应多种环境
不过要记住:尽管可以配置多个环境,但每个SqlSessionFactory实例只能选择一种环境。
学会使用配置多套运行环境!
Mybatis默认的事务管理器就是JDBC,连接池:POOLED
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"/>
<dataSource type="POOLED">
<property name="driver" value="com.mysql.cj.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost:3306/mybatis?serverTimezone=GMT&useUnicode=true&characterEncoding=utf8&useSSL=false"/>
<property name="username" value="root"/>
<property name="password" value="123456"/>
dataSource>
environment>
environments>
<mappers>
<mapper resource="com/blue/dao/UserMapper.xml"/>
mappers>
configuration>
了解的:
我们可以通过properties属性来实现引用配置文件
这些属性都是可外部配置且可动态替换的,既可以在典型的ava属性文件中配置,亦可通过properties元素的子元素来传递。【db.properties】.
新建数据库配置文件
db.properties
driver=com.mysql.cj.jdbc.Driver
url=jdbc:mysql://localhost:3306/mybatis?serverTimezone=GMT&useUnicode=true&characterEncoding=utf8&useSSL=false
username=root
password=123456
在核心配置文件中映入
<properties resource="db.properties">
<property name="username" value="root"/>
<property name="pwd" value="123456"/>
properties>
注意顺序
映入配置文件的几种方式:
第一种方式
第二种方式外部配置文件
<typeAliases>
<typeAlias type="com.blue.pojo.User" alias="User"/>
typeAliases>
这是 MyBatis 中极为重要的调整设置,它们会改变 MyBatis 的运行时行为。
mybati-Plus
MapperRegistry:注册绑定我们的Mapper文件;
方式一:
<mappers>
<mapper class="com.blue.dao.UserMapper"/>
mappers>
方式二:使用class文件绑定
<mappers>
<mapper resource="com/blue/dao/UserMapper.xml"/>-->
mappers>
方式三:使用扫描包进行注入绑定
注意点:
练习时间:(重点)
生命周期是至关重要的,因为错误的使用会导致非常严重的并发问题。
SqlSessionFactoryBuilder:
SqlSessionFactory:
SqlSession:
这里面的每一个Mapper,就代表一个具体的业务!
数据库中的字段
新建一个项目,拷贝之前的,测试实体类字段不一致的情况
实体类User
修改如下
public class User {
private int id;
private String name;
private String password;
}
输出结果:
// select from mybatis.user where id #{id}
//类型处理器
// select id,name,pwd from mybatis.user where id =#{id}
解决方法:-
<select id="getUserById" parameterType="int" resultType="com.blue.pojo.User">
select id,name,pwd from mybatis.user where id =#{id}
select>
结果集映射
id name pwd
id name password
<resultMap id="UserMap" type="User">
<result column="id" property="id"/>
<result column="name" property="name"/>
<result column="pwd" property="password"/>
resultMap>
<select id="getUserById" parameterType="int" resultMap="UserMap">
select * from mybatis.user where id =#{id}
select>
resultMap
元素是MyBatis中最重要最强大的元素ResultMap
的设计思想是,对于简单的语句根本不需要配置显式的结果映射,而对于复杂一点的语句只需要描述它们的关系就行了。[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-JYj1Kyab-1647332164411)(C:\Users\dlmu\AppData\Roaming\Typora\typora-user-images\image-20220315090559917.png)]
接下来讲
如果一个数据库操作,出现了异常,我们需要排错。日志就是最好的助手!
曾经:sout、debug
现在:日志工厂!
在Mybatis中具体使用那个一日志实现,在设置中设定!
STDOUT LOGGING标准日志输出
在mybatis核心配置文件中,配置我们的日志!
在这个文件中配置日志输出
日志如下
什么是Log4j?
<dependency>
<groupId>log4jgroupId>
<artifactId>log4jartifactId>
<version>1.2.17version>
dependency>
导入log4j步骤
<dependency>
<groupId>log4jgroupId>
<artifactId>log4jartifactId>
<version>1.2.17version>
dependency>
配置文件
Log4j框架配置文件log4j.properties配置使用详解_CycloneKid的博客-CSDN博客_log4j配置文件详解
#将等级为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/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
<settings>
<setting name="logImpl" value="LOG4J"/>
settings>
简单使用
static Logger logger Logger.getLogger(UserDaoTest.class);
logger.info("info:进入了testLog4j");
logger.debug("debug:进入了testLog4j");
logger.error("error:进入了testLog4j");
测试:
package com.blue.dao;
import com.blue.pojo.User;
import com.blue.utils.MybatisUtils;
import org.apache.ibatis.session.SqlSession;
import org.apache.log4j.Logger;
import org.junit.Test;
import java.util.List;
public class UserDaoText {
Logger logger = Logger.getLogger(UserDaoText.class);
@Test
public void textLog4j(){
logger.info("info:进入了testLog4j");
logger.debug("debug:进入了testLog4j");
logger.error("error:进入了testLog4j");
}
}
输出:
运行后输出:log文件
[INFO][22-03-15][com.blue.dao.UserDaoText]info:进入了testLog4j
[DEBUG][22-03-15][com.blue.dao.UserDaoText]debug:进入了testLog4j
[ERROR][22-03-15][com.blue.dao.UserDaoText]error:进入了testLog4j
思考:为什么要分页?
语法:SELECT * from user limit startIndex,pagesize;
SELECT from user limit 3;#[0,n]
0——从第几个显示
2——显示几个
使用Mybatis实现分页,核心SQL
接口
package com.blue.dao;
import com.blue.pojo.User;
import java.util.List;
import java.util.Map;
public interface UserMapper {
// 分页
List<User> getUserByLimit(Map<String,Integer> map);
}
Mapper.xml
DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.blue.dao.UserMapper">
<resultMap id="UserMap" type="User">
<result column="id" property="id"/>
<result column="name" property="name"/>
<result column="pwd" property="password"/>
resultMap>
<select id="getUserByLimit" parameterType="map" resultType="user">
select * from mybatis.user limit #{startIndex},#{pageSize}
select>
mapper>
测试
package com.blue.dao;
import com.blue.pojo.User;
import com.blue.utils.MybatisUtils;
import org.apache.ibatis.session.SqlSession;
import org.apache.log4j.Logger;
import org.junit.Test;
import java.util.HashMap;
import java.util.List;
public class UserDaoText {
Logger logger = Logger.getLogger(UserDaoText.class);
@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> userList = mapper.getUserByLimit(map);
for (User user : userList) {
System.out.println(user);
}
sqlSession.close();
}
}
结果中有
修改
不建议开发中使用
了解就行
不再使用SQL实现分页
从第一个数据开始,两个一页
MyBatis 分页插件 PageHelper
关于接口的理解
从更深层次的理解,应是定义(规范,约束)与实现(名实分离的原则)的分离。
接口的本身反映了系统设计人员对系统的抽象理解。
接口应有两类:
一个体有可能有多个抽象面。抽象体与抽象面是有区别的。
三个面向区别
新建模块
删掉
换成这个
注解在接口上实现
package com.blue.dao;
import com.blue.pojo.User;
import org.apache.ibatis.annotations.Select;
import java.util.List;
import java.util.Map;
public interface UserMapper {
@Select("select * from user")
List<User> getUsers();
}
需要再核心配置文件中绑定接口!
<mappers>
<mapper class="com.blue.dao.UserMapper"/>
mappers>
测试
本质:反射机制实现
底层:动态代理!
Java动态代理设计模式 - 大数据技术派 - 博客园 (cnblogs.com)
Mybatis详细的执行流程!
我们可以在工具类创建的时候实现自动提交事务!
测试类
【注意:我们必须要讲接口注册绑定到我们的核心配置文件中!】
1、接口加注解
package com.blue.dao;
import com.blue.pojo.User;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;
import java.util.List;
import java.util.Map;
public interface UserMapper {
//方法存在多个参数,所有的参数加面必颈M上@Param("id")注解
@Select("select * from user where id = #{id}")
User getUserByID(@Param("id") int id);
}
2、测试
@Test
public void text2(){
SqlSession sqlSession = MybatisUtils.getSqlSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
User userByID = mapper.getUserByID(1);
System.out.println(userByID);
sqlSession.close();
}
结果
接口
package com.blue.dao;
import com.blue.pojo.User;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;
import java.util.List;
import java.util.Map;
public interface UserMapper {
@Insert("insert into user(id,name,pwd) value (#{id},#{name},#{password})")
int addUser(User user);
}
测试
@Test
public void text2(){
SqlSession sqlSession = MybatisUtils.getSqlSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
mapper.addUser(new User(5,"Hello","123123"));
sqlSession.close();
}
结果
接口
测试
接口
测试
#{} ${} 区别
Lombok:是一款Java开发插件,使得Java开发者可以通过其定义的一些注解来消除业务工程中冗长和繁琐的代码,尤其对于简单的Java模型对象(POJO)。在开发环境中使用Lombok插件后,Java开发人员可以节省重复构建,诸如hashCode和equals这样的方法以及各种业务对象模型的accessor和ToString等方法的大量时间。对于这些方法,它能够在编译源代码期间自动帮我们生成这些方法,并没有如反射那样降低程序的性能。
Project 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.
没有的点这里
<dependencies>
<dependency>
<groupId>org.projectlombokgroupId>
<artifactId>lombokartifactId>
<version>1.18.20version>
<scope>providedscope>
dependency>
dependencies>
@Getter and @Setter
@FieldNameConstants
@Tostring
@Equal sAndHashCode
@AllArgsconstructor,@Requi redArgsconstructor and @NoArgsconstructor
@Log,@Log4j,@Log4j2,@slf4j,@xs1f4j,@CommonsLog,@JBossLog,@Flogger
@Data
@Builder
@singular
@Delegate
@Value
@Accessors
@wither
@SneakyThrows
目前掌握这些
常用的:
@Data:无参构造,get、set、tostring、hashcode,equals
@AllArgsConstructor
@NoArgsConstructor
@EqualsAndHashCode
@ToString
@Getter
优点:
缺点:
一会用这两个
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=utf8INSERT 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文件
在核心配置文件中绑定注册我们的Mappera接口或者文件!【】
测试查询是否能够成功!
package com.blue.pojo;
public class Student {
private int id;
private String name;
//学生需要关联一·个老师!
private Teacher teacher;
}
package com.blue.pojo;
import lombok.Data;
@Data
public class Teacher {
private int id;
private String name;
}
DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.blue.dao.TeacherMapper">
mapper>
<mappers>
<mapper class="com.blue.dao.TeacherMapper"/>
<mapper class="com.blue.dao.StudentMapper"/>
mappers>
package com.blue.dao;
import com.blue.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);
}
package com.blue.dao;
import com.blue.pojo.Teacher;
import com.blue.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();
}
}
select s.id,s.name,t.name from student s,teacher t where s.tid = t.id;
package com.blue.dao;
import com.blue.pojo.Student;
import java.util.List;
public interface StudentMapper {
//查询所有的学生信息。以及对应老师的信息!
public List<Student> getStudent();
}
DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.blue.dao.StudentMapper">
<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>
mapper>
复杂的属性,我们需要单独处理对象:association集合:collection
public List<Student> getStudent2();
DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.blue.dao.StudentMapper">
<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>
<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>
mapper>
回顾Mysql多对一查询方式:
比如:一个老师拥有多个学生!
对于老师而言,就是一对多的关系!
和刚才一样
实体类
学生只有一个
package com.blue.pojo;
import lombok.Data;
@Data
public class Student {
private int id;
private String name;
private int tid;
}
package com.blue.pojo;
import lombok.Data;
import java.util.List;
@Data
public class Teacher {
private int id;
private String name;
//一个老师有多个学生
private List<Student> students;
}
package com.blue.dao;
import com.blue.pojo.Teacher;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;
import java.util.List;
public interface TeacherMapper {
List<Teacher> getTeacher();
//获取指定老师下的所有学生及老师的信息
Teacher getTeacher(@Param("tid") int id);
}
DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.blue.dao.TeacherMapper">
<select id="getTeacher" resultMap="TeacherStudent">
select s.id sid,s.name sname,t.name tname,t.id tid
from mybatis.student s,mybatis.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"/>
<collection property="students" ofType="Student">
<result property="id" column="sid"/>
<result property="name" column="sname"/>
<result property="tid" column="tid"/>
collection>
resultMap>
mapper>
package com.blue.dao;
import com.blue.pojo.Student;
import com.blue.pojo.Teacher;
import com.blue.utils.MybatisUtils;
import org.apache.ibatis.session.SqlSession;
import org.junit.Test;
import java.util.List;
public class MyTest {
@Test
public void test(){
SqlSession sqlSession = MybatisUtils.getSqlSession();
TeacherMapper mapper = sqlSession.getMapper(TeacherMapper.class);
Teacher teacher = mapper.getTeacher(1);
System.out.println(teacher);
sqlSession.close();
}
}
查询老老师下面的所有东西:
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 test2(){
SqlSession sqlSession = MybatisUtils.getSqlSession();
TeacherMapper mapper = sqlSession.getMapper(TeacherMapper.class);
Teacher teacher = mapper.getTeacher2(1);
System.out.println(teacher);
sqlSession.close();
}
javaType
& ofType
JavaType
用来指定实体类中属性的类型ofType
用来指定映射到List或者集合中的pojo类型,泛型中的约束类型!慢SQL 1s 1000s
mybatis – MyBatis 3 | 动态 SQL
什么是动态SQL:动态SQL就是指根据不同的条件生成不同的SQL语句
利用动态SQL这一特性可以彻底摆脱这种痛苦。
如果你之前用过 JSTL 或任何基于类 XML 语言的文本处理器,你对动态 SQL 元素可能会感觉似曾相识。在 MyBatis 之前的版本中,需要花时间了解大量的元素。借助功能强大的基于 OGNL 的表达式,MyBatis 3 替换了之前的大部分元素,大大精简了元素种类,现在要学习的元素种类比原来的一半还要少。
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
创建一个基础工程
package com.blue.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;
}
package com.blue.utils;
import java.util.UUID;
@SuppressWarnings("all")
public class IDutils {
public static String getId(){
return UUID.randomUUID().toString().replaceAll("-","");
}
}
package com.blue.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;
}
<settings>
<setting name="logImpl" value="STDOUT_LOGGING"/>
<setting name="mapUnderscoreToCamelCase" value="true"/>
settings>
package com.blue.dao;
import com.blue.pojo.Blog;
public interface BlogMapper {
//插入数据
int addBook(Blog blog);
}
DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.blue.dao.BlogMapper">
<insert id="addBook" parameterType="blog">
insert into mybatis.blog(id, title, author, create_time, views)
VALUES (#{id},#{title},#{author},#{createTime},#{views});
insert>
mapper>
package com.blue.dao;
import com.blue.pojo.Blog;
import com.blue.utils.IDutils;
import com.blue.utils.MybatisUtils;
import org.apache.ibatis.session.SqlSession;
import org.junit.Test;
import java.util.Date;
public class MyTest {
@Test
public void addBlogTest() {
SqlSession sqlSession = MybatisUtils.getSqlSession();
BlogMapper mapper = sqlSession.getMapper(BlogMapper.class);
Blog blog = new Blog();
blog.setId(IDutils.getId());
blog.setTitle("Mybatis");
blog.setAuthor("狂神说");
blog.setCreateTime(new Date());
blog.setViews(9999);
mapper.addBook(blog);
blog.setId(IDutils.getId());
blog.setTitle("Java");
mapper.addBook(blog);
blog.setId(IDutils.getId());
blog.setTitle("Spring");
mapper.addBook(blog);
blog.setId(IDutils.getId());
blog.setTitle("微服务");
mapper.addBook(blog);
sqlSession.close();
}
}
package com.blue.dao;
import com.blue.pojo.Blog;
import java.util.List;
public interface BlogMapper {
//插入数据
int addBook(Blog blog);
List<Blog> queryBlog();
}
<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>
@Test
public void queryBlogIF(){
SqlSession sqlSession = MybatisUtils.getSqlSession();
BlogMapper mapper = sqlSession.getMapper(BlogMapper.class);
HashMap map = new HashMap();
List<Blog> blogs = mapper.queryBlogIF(map);
for (Blog blog : blogs) {
System.out.println(blog);
}
sqlSession.close();
}
@Test
public void queryBlogIF(){
SqlSession sqlSession = MybatisUtils.getSqlSession();
BlogMapper mapper = sqlSession.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);
}
sqlSession.close();
}
@Test
public void queryBlogIF(){
SqlSession sqlSession = MybatisUtils.getSqlSession();
BlogMapper mapper = sqlSession.getMapper(BlogMapper.class);
HashMap map = new HashMap();
map.put("title","Java如此简单");
map.put("author","狂神说");
List<Blog> blogs = mapper.queryBlogIF(map);
for (Blog blog : blogs) {
System.out.println(blog);
}
sqlSession.close();
}
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="anthor != null">
anthor = #{anthor}
when>
<otherwise>
and views = #{views}
otherwise>
choose>
where>
select>
@Test
public void queryBlogChoose(){
SqlSession sqlSession = MybatisUtils.getSqlSession();
BlogMapper mapper = sqlSession.getMapper(BlogMapper.class);
HashMap map = new HashMap();
// map.put("title","Java");
// map.put("author","狂神说");
map.put("views",9999);
List<Blog> blogs = mapper.queryBlogChoose(map);
for (Blog blog : blogs) {
System.out.println(blog);
}
sqlSession.close();
}
1、
2、
先找第一个满足的条件
where 只查title
查author出不来
自动加and
<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>
@Test
public void queryBlogIF(){
SqlSession sqlSession = MybatisUtils.getSqlSession();
BlogMapper mapper = sqlSession.getMapper(BlogMapper.class);
HashMap map = new HashMap();
map.put("title","Java如此简单");
// map.put("author","狂神说");
List<Blog> blogs = mapper.queryBlogIF(map);
for (Blog blog : blogs) {
System.out.println(blog);
}
sqlSession.close();
}
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-DBqzxPNy-1647957128386)(C:\Users\dlmu\AppData\Roaming\Typora\typora-user-images\image-20220321100353305.png)]
结果
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-QBT1s7px-1647957128386)(C:\Users\dlmu\AppData\Roaming\Typora\typora-user-images\image-20220321100412958.png)]
所谓的动态SQL,本质还是SQL语句,只是我们可以在SQL层面,去执行一个逻辑代码
if
where set,choose when
select from user where 1=1 and
<foreach item="id" index="index" collection="ids"
open="ID in (" separator="," close=")">
#{id}
</foreach>
(id=1 or id=2 or id=3)
//查询第1-2-3号记录的博容
List<Blog> queryBlogForeach(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>
@Test
public void queryBlogForeach(){
SqlSession sqlSession = MybatisUtils.getSqlSession();
BlogMapper mapper = sqlSession.getMapper(BlogMapper.class);
HashMap<Object, Object> map = new HashMap<>();
ArrayList<Integer> ids = new ArrayList<>();
map.put("ids",ids);
List<Blog> blogs = mapper.queryBlogForeach(map);
for (Blog blog : blogs) {
System.out.println(blog);
}
sqlSession.close();
}
动态SQL就是在拼接SQL语句,我们只要保证SQL的正确性,按照SQL的格式,去排列组合就可以了
建议:
有的时候,我们可能会将一些功能的部分抽取出来,方便复用!
查询 : 连接数据库,耗资源!
一次查询的结果,给他暂存在一个可以直接取到的地方!-->内存:缓存
我们再次查询相同数据的时候,直接走缓存,就不用走数据库了
1.什么是缓存[Cache]?
2.为什么使用缓存?
3.什么样的数据能使用缓存?
MyBatis包含一个非常强大的查询缓存特性,它可以非常方便地定制和配置缓存。缓存可以极大的提升查询效率。
MyBatis系统中默认定义了两级缓存:一级缓存和二级缓存
一级缓存也叫本地缓存:SqlSession
步骤:
结构:
User.java
UserMapper
//根据id查询用户
User queryUserById(@Param("id") int id);
DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.blue.dao.UserMapper">
<select id="queryUserById" resultType="user">
select * from mybatis.user where id = #{id}
select>
mapper>
test
接口
int updateUser(User user);
sql
<update id="updateUser" parameterType="user">
update mybatis.user set name=#{name},pwd=#{pwd} where id=#{id};
update>
主体
@Data
@AllArgsConstructor
@NoArgsConstructor
public class User {
private int id;
private String name;
private String pwd;
}
test
@Test
public void test1(){
SqlSession sqlSession = MybatisUtils.getSqlSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
User user = mapper.queryUserById(1);
System.out.println(user);
mapper.updateUser(new User(2,"aaaa","bbbbb"));
System.out.println("===============");
User user2 = mapper.queryUserById(1);
System.out.println(user2);
System.out.println(user==user2);
sqlSession.close();
}
结果
结果
一级缓存默认是开启的,只在一次SqlSession中有效,也就是拿到连接到关闭连接这个区间段!
一级缓存就是一个Map。
二级缓存也叫全局缓存,一级缓存作用域太低了,所以诞生了二级缓存
基于namespace级别的缓存,一个名称空间,对应一个二级缓存;
工作机制
步骤:
<setting name="cacheEnabled" value="true"/>
也可以自定义参数
<cache eviction="FIFO"
flushInterval="60000"
size="512"
readOnly="true"/>
@Test
public void test3(){
SqlSession sqlSession = MybatisUtils.getSqlSession();
SqlSession sqlSession2 = MybatisUtils.getSqlSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
User user = mapper.queryUserById(1);
System.out.println(user);
sqlSession.close();
System.out.println("===================");
UserMapper mapper2 = sqlSession2.getMapper(UserMapper.class);
User user2 = mapper2.queryUserById(1);
System.out.println(user2);
System.out.println(user==user2);
sqlSession.close();
}
3.测试
Caused by:java.io.NotserializableException:com.kuang.pojo.User
Ehcache是一种广泛使用的开源]ava分布式缓存。主要面向通用缓存
要在程序中使用ehcache,先要导包!
<ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="http://ehcache.org/ehcache.xsd"
updateCheck="false">
<diskStore path="./tmpdir/Tmp_EhCache"/>
<defaultCache
eternal="false"
maxElementsInMemory="10000"
overflowToDisk="false"
diskPersistent="false"
timeToIdleSeconds="1800"
timeToLiveSeconds="259200"
memoryStoreEvictionPolicy="LRU"/>
<cache
name="cloud_user"
eternal="false"
maxElementsInMemory="5000"
overflowToDisk="false"
diskPersistent="false"
timeToIdleSeconds="1800"
timeToLiveSeconds="1800"
memoryStoreEvictionPolicy="LRU"/>
ehcache>
Redis数据库来做缓存!K-V