MyBatis
环境:
所需知识点:
SSM框架:配置文件,最好的方式,看官网,(SprintMVC,SprintBoot,MyBatis)
ORM 对象关系映射 (Object Relational Mapping):将零散的数据封装成一个对象,
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-5F91zgkX-1656896670001)(C:\Users\潘文锋\AppData\Roaming\Typora\typora-user-images\image-20220416000534296.png)]
如何获取MyBatis
<dependency>
<groupId>org.mybatisgroupId>
<artifactId>mybatisartifactId>
<version>3.5.8version>
dependency>
数据持久化
为什么需要持久化?
Dao层,Service层,Controller层…
优点:
最重要的一点:使用的人多!
Spring SpringMVC SpringBoot
思路:搭建环境–>导入Mybatis–>编写代码–>测试!
搭建数据库
create database `MyBatis`
use `Mybatis`
create table `user`(
`id` int comment '主键',
`name` varchar(50) default null,
`pwd` varchar(30) default null
)engine=innodb default charset=utf8
insert into `user`(`id`,`name`,`pwd`)values
(1,'潘表','123456'),
(1,'张三','123321'),
(1,'李四','123654')
新建项目
<groupId>org.examplegroupId>
<artifactId>MybatisartifactId>
<version>1.0-SNAPSHOTversion>
<dependencies>
<dependency>
<groupId>mysqlgroupId>
<artifactId>mysql-connector-javaartifactId>
<version>5.1.19version>
dependency>
<dependency>
<groupId>org.mybatisgroupId>
<artifactId>mybatisartifactId>
<version>3.4.6version>
dependency>
<dependency>
<groupId>junitgroupId>
<artifactId>junitartifactId>
<version>4.12version>
<scope>testscope>
dependency>
dependencies>
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&userUnicode=true&characterEncoding=UTF-8"/>
<property name="username" value="root"/>
<property name="password" value="123456"/>
dataSource>
environment>
environments>
configuration>
//sqlSessionFactory --> sqlSession
public class MybatisUtils {
private static SqlSessionFactory sqlSessionFactory = null;
static {
//获取sqlSessionFactory
String resource = "org/mybatis/example/mybatis-config.xml";
InputStream inputStream = null;
try {
inputStream = Resources.getResourceAsStream(resource);
} catch (IOException e) {
e.printStackTrace();
}
sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
}
//既然有了 SqlSessionFactory,顾名思义,我们可以从中获得 SqlSession 的实例。
//SqlSession 提供了在数据库执行 SQL 命令所需的所有方法
public static SqlSession getSqlSession(){
return sqlSessionFactory.openSession();
}
}
public class User {
private int id;
private String name;
private String pwd;
public User(int id, String name, String pwd) {
this.id = id;
this.name = name;
this.pwd = pwd;
}
public User() {
}
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 + '\'' +
'}';
}
}
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.project.dao.UserDao">
<select id="getUserList" resultType="com.project.pojo.User">
select * from mybatis.user
select>
mapper>
注意点:
MapperRegistry是什么?
核心配置文件中注册 mappers
public class UserDaoTest {
@Test
public void test(){
SqlSession sqlSession= null;
try{
//第一步:获取sqlSession对象
sqlSession = MybatisUtils.getSqlSession();
//方式一:执行SQL
UserDao mapper = sqlSession.getMapper(UserDao.class);
// List userList = mapper.getUserList();
//方式二:(了解即可,不推荐使用)
List<User> userList = sqlSession.selectList("com.project.dao.UserDao.getUserList");
for (User user : userList) {
System.out.println(user);
}
}finally {
//关闭SqlSession
sqlSession.close();
}
}
}
<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>
可能会遇到的问题:
namespace中的包名要和Dao/mapper接口的包名一致!
查询语句:
1.编写接口
//根据ID查询用户
User getUserById(int id);
2.编写对应的mapper中的sql语句
<select id="getUserById" resultType="com.project.pojo.User" parameterType="int">
select * from mybatis.user where id = #{id}
select>
3.测试
@Test
public void test(){
SqlSession sqlSession= null;
try{
//第一步:获取sqlSession对象
sqlSession = MybatisUtils.getSqlSession();
//方式一:执行SQL
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
// List userList = mapper.getUserList();
//方式二:(了解即可,不推荐使用)
List<User> userList = sqlSession.selectList("com.project.dao.UserMapper.getUserList");
for (User user : userList) {
System.out.println(user);
}
}finally {
//关闭SqlSession
sqlSession.close();
}
}
配置:
<insert id="addUser" parameterType="com.project.pojo.User">
insert into mybatis.user (id,name,pwd) values (#{id},#{name},#{pwd})
insert>
接口:
//添加一个用户
int addUser(User user);
测试:
@Test
//注意:增删改需要使用commit提交事务
public void Test03(){
//新增一个用户
SqlSession sqlSession = null;
try{
sqlSession = MybatisUtils.getSqlSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
int insert = mapper.addUser(new User(4, "王五", "112233"));
sqlSession.commit();
}finally {
sqlSession.close();
}
}
配置:
<update id="updateUser" parameterType="com.project.pojo.User">
update mybatis.user
set name=#{name},pwd=#{pwd}
where id = #{id};
update>
接口:
//修改一个用户
int updateUser(User user);
测试:
@Test
public void Test04(){
//根据id修改用户
SqlSession sqlSession = null;
try{
sqlSession = MybatisUtils.getSqlSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
int update = mapper.updateUser(new User(4, "王五", "123333"));
sqlSession.commit();
}finally {
sqlSession.close();
}
}
配置:
<delete id="deleteUser" parameterType="int">
delete from mybatis.user where id=#{id}
delete>
接口:
//删除一个用户
int deleteUser(int id);
测试:
@Test
public void Test05(){
//根据id删除一个用户
SqlSession sqlSession = null;
try{
sqlSession = MybatisUtils.getSqlSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
int delete = mapper.deleteUser(4);
sqlSession.commit();
}finally {
sqlSession.close();
}
}
注意点:增删改需要提交事务
错误注意点
在项目中使用频率较高
我们的实体类,或者数据库中的表,字段或者参数过多,我们应该考虑使用map优化
配置:
<insert id="addUserByMap" parameterType="map">
insert into mybatis.user (id,name,pwd) values(#{userid},#{username},#{password})
insert>
接口:
//使用map集合添加一个用户
int addUserByMap(HashMap<String,Object> mapper);
测试:
@Test
public void Test06(){
//使用map接口中的键值对作为对象的属性,以此执行insert命令
SqlSession sqlSession = MybatisUtils.getSqlSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
HashMap<String, Object> map = new HashMap<>();
map.put("userid", 5);
map.put("username", "娄本伟");
map.put("password", "332211");
int i = mapper.addUserByMap(map);
System.out.println(i);
sqlSession.commit();
sqlSession.close();
}
配置:
<select id="getUserByName" resultType="com.project.pojo.User">
select * from mybatis.user where name like #{value}
select>
1.java代码执行的时候,传递通配符% %
select * from mybatis.user where name like #{value}
2.在sql拼接中使用通配符
select * from mybatis.user where name like "%"#{value}"%"
接口:
//模糊查询根据名字查询
List<User> getUserByName(String value);
测试:
@Test
public void Test07(){
//根据名字使用模糊查询
SqlSession sqlSession = MybatisUtils.getSqlSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
List<User> ls = mapper.getUserByName("%娄%");
for (User l : ls) {
System.out.println(l);
}
sqlSession.close();
}
configuration(配置)
properties(属性)
settings(设置)
typeAliases(类型别名)
typeHandlers(类型处理器)
objectFactory(对象工厂)
plugins(插件)
environments(环境配置)
environment(环境变量)
transactionManager(事务管理器)
dataSource(数据源)
databaseIdProvider(数据库厂商标识)
mappers(映射器)
MyBatis 可以配置成适应多种环境
不过要记住:尽管可以配置多个环境,但每个 SqlSessionFactory 实例只能选择一种环境。
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-ZuQEyp8p-1656896670006)(C:\Users\潘文锋\AppData\Roaming\Typora\typora-user-images\image-20220420214740443.png)]
xml的标签有放置顺序
学会使用配合多套运行环境
<environments default="test">
<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>
<environment id="test">
<transactionManager type="JDBC"/>
<dataSource type="POOLED">
<property name="driver" value="${driver}"/>
<property name="url" value="${url}"/>
<property name="username" value="${username}"/>
<property name="password" value="${password}"/>
dataSource>
environment>
environments>
Mybatis默认的事务管理器就是 JDBC,连接池:POOLED
我们可以通过properties属性来实现引用配置文件
这些属性都是可外部配置且可动态替换的,既可以在典型的 Java 属性文件中配置,亦可通过properties元素的子元素来传递。[db.properties]
编写一个配置文件
db.properties
driver=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/MyBatis?useSSL=true&useUnicode=true&characterEncoding=UTF-8
username=root
password=123456
在核心配置文件中映入
<properties resource="db.properties" />
<environment id="test">
<transactionManager type="JDBC"/>
<dataSource type="POOLED">
<property name="driver" value="${driver}"/>
<property name="url" value="${url}"/>
<property name="username" value="${username}"/>
<property name="password" value="${password}"/>
dataSource>
environment>
<typeAliases>
<typeAlias type="com.project.pojo.User" alias="user"/>
typeAliases>
也可以指定一个包名,MyBatis会在包下面搜索需要的Java Bean,比如:
扫描实体类的包,他的默认别名就为这个类的 类名,首字母小写
<package name="com.project.pojo"/>
在实体类比较少的时候,使用第一种方法
如果实体类十分多,建议使用第二种
第一种可以DIY别名,第二种则不行,如果非要改,需要在实体类上增加注解
@Alias("opgg")
public class User {
这是 MyBatis 中极为重要的调整设置,它们会改变 MyBatis 的运行时行为。 下表描述了设置中各项设置的含义、默认值等。
设置名 | 描述 | 有效值 | 默认值 |
---|---|---|---|
cacheEnabled | 全局性地开启或关闭所有映射器配置文件中已配置的任何缓存。 | true | false | true |
lazyLoadingEnabled | 延迟加载的全局开关。当开启时,所有关联对象都会延迟加载。 特定关联关系中可通过设置 fetchType 属性来覆盖该项的开关状态。 |
true | false | false |
aggressiveLazyLoading | 开启时,任一方法的调用都会加载该对象的所有延迟加载属性。 否则,每个延迟加载属性会按需加载(参考 lazyLoadTriggerMethods )。 |
true | false | false (在 3.4.1 及之前的版本中默认为 true) |
multipleResultSetsEnabled | 是否允许单个语句返回多结果集(需要数据库驱动支持)。 | true | false | true |
useColumnLabel | 使用列标签代替列名。实际表现依赖于数据库驱动,具体可参考数据库驱动的相关文档,或通过对比测试来观察。 | true | false | true |
useGeneratedKeys | 允许 JDBC 支持自动生成主键,需要数据库驱动支持。如果设置为 true,将强制使用自动生成主键。尽管一些数据库驱动不支持此特性,但仍可正常工作(如 Derby)。 | true | false | False |
autoMappingBehavior | 指定 MyBatis 应如何自动映射列到字段或属性。 NONE 表示关闭自动映射;PARTIAL 只会自动映射没有定义嵌套结果映射的字段。 FULL 会自动映射任何复杂的结果集(无论是否嵌套)。 | NONE, PARTIAL, FULL | PARTIAL |
autoMappingUnknownColumnBehavior | 指定发现自动映射目标未知列(或未知属性类型)的行为。NONE : 不做任何反应WARNING : 输出警告日志('org.apache.ibatis.session.AutoMappingUnknownColumnBehavior' 的日志等级必须设置为 WARN )FAILING : 映射失败 (抛出 SqlSessionException ) |
NONE, WARNING, FAILING | NONE |
defaultExecutorType | 配置默认的执行器。SIMPLE 就是普通的执行器;REUSE 执行器会重用预处理语句(PreparedStatement); BATCH 执行器不仅重用语句还会执行批量更新。 | SIMPLE REUSE BATCH | SIMPLE |
defaultStatementTimeout | 设置超时时间,它决定数据库驱动等待数据库响应的秒数。 | 任意正整数 | 未设置 (null) |
defaultFetchSize | 为驱动的结果集获取数量(fetchSize)设置一个建议值。此参数只可以在查询设置中被覆盖。 | 任意正整数 | 未设置 (null) |
defaultResultSetType | 指定语句默认的滚动策略。(新增于 3.5.2) | FORWARD_ONLY | SCROLL_SENSITIVE | SCROLL_INSENSITIVE | DEFAULT(等同于未设置) | 未设置 (null) |
safeRowBoundsEnabled | 是否允许在嵌套语句中使用分页(RowBounds)。如果允许使用则设置为 false。 | true | false | False |
safeResultHandlerEnabled | 是否允许在嵌套语句中使用结果处理器(ResultHandler)。如果允许使用则设置为 false。 | true | false | True |
mapUnderscoreToCamelCase | 是否开启驼峰命名自动映射,即从经典数据库列名 A_COLUMN 映射到经典 Java 属性名 aColumn。 | true | false | False |
localCacheScope | MyBatis 利用本地缓存机制(Local Cache)防止循环引用和加速重复的嵌套查询。 默认值为 SESSION,会缓存一个会话中执行的所有查询。 若设置值为 STATEMENT,本地缓存将仅用于执行语句,对相同 SqlSession 的不同查询将不会进行缓存。 | SESSION | STATEMENT | SESSION |
jdbcTypeForNull | 当没有为参数指定特定的 JDBC 类型时,空值的默认 JDBC 类型。 某些数据库驱动需要指定列的 JDBC 类型,多数情况直接用一般类型即可,比如 NULL、VARCHAR 或 OTHER。 | JdbcType 常量,常用值:NULL、VARCHAR 或 OTHER。 | OTHER |
lazyLoadTriggerMethods | 指定对象的哪些方法触发一次延迟加载。 | 用逗号分隔的方法列表。 | equals,clone,hashCode,toString |
defaultScriptingLanguage | 指定动态 SQL 生成使用的默认脚本语言。 | 一个类型别名或全限定类名。 | org.apache.ibatis.scripting.xmltags.XMLLanguageDriver |
defaultEnumTypeHandler | 指定 Enum 使用的默认 TypeHandler 。(新增于 3.4.5) |
一个类型别名或全限定类名。 | org.apache.ibatis.type.EnumTypeHandler |
callSettersOnNulls | 指定当结果集中值为 null 的时候是否调用映射对象的 setter(map 对象时为 put)方法,这在依赖于 Map.keySet() 或 null 值进行初始化时比较有用。注意基本类型(int、boolean 等)是不能设置成 null 的。 | true | false | false |
returnInstanceForEmptyRow | 当返回行的所有列都是空时,MyBatis默认返回 null 。 当开启这个设置时,MyBatis会返回一个空实例。 请注意,它也适用于嵌套的结果集(如集合或关联)。(新增于 3.4.2) |
true | false | false |
logPrefix | 指定 MyBatis 增加到日志名称的前缀。 | 任何字符串 | 未设置 |
logImpl | 指定 MyBatis 所用日志的具体实现,未指定时将自动查找。 | SLF4J | LOG4J | LOG4J2 | JDK_LOGGING | COMMONS_LOGGING | STDOUT_LOGGING | NO_LOGGING | 未设置 |
proxyFactory | 指定 Mybatis 创建可延迟加载对象所用到的代理工具。 | CGLIB | JAVASSIST | JAVASSIST (MyBatis 3.3 以上) |
vfsImpl | 指定 VFS 的实现 | 自定义 VFS 的实现的类全限定名,以逗号分隔。 | 未设置 |
useActualParamName | 允许使用方法签名中的名称作为语句参数名称。 为了使用该特性,你的项目必须采用 Java 8 编译,并且加上 -parameters 选项。(新增于 3.4.1) |
true | false | true |
configurationFactory | 指定一个提供 Configuration 实例的类。 这个被返回的 Configuration 实例用来加载被反序列化对象的延迟加载属性值。 这个类必须包含一个签名为static Configuration getConfiguration() 的方法。(新增于 3.2.3) |
一个类型别名或完全限定类名。 | 未设置 |
<settings>
<setting name="cacheEnabled" value="true"/>
<setting name="lazyLoadingEnabled" value="true"/>
<setting name="multipleResultSetsEnabled" value="true"/>
<setting name="useColumnLabel" value="true"/>
<setting name="useGeneratedKeys" value="false"/>
<setting name="autoMappingBehavior" value="PARTIAL"/>
<setting name="autoMappingUnknownColumnBehavior" value="WARNING"/>
<setting name="defaultExecutorType" value="SIMPLE"/>
<setting name="defaultStatementTimeout" value="25"/>
<setting name="defaultFetchSize" value="100"/>
<setting name="safeRowBoundsEnabled" value="false"/>
<setting name="mapUnderscoreToCamelCase" value="false"/>
<setting name="localCacheScope" value="SESSION"/>
<setting name="jdbcTypeForNull" value="OTHER"/>
<setting name="lazyLoadTriggerMethods" value="equals,clone,hashCode,toString"/>
settings>
MapperRegistry:注册绑定我们的Mapper文件
方式一:【推荐使用!没有任何限制】
<mappers>
<mapper resource="com/project/dao/UserMapper.xml"/>
mappers>
方式二:使用class文件绑定注册
<mappers>
<mapper class="com.project.dao.UserMapper"/>
mappers>
方式三:使用扫描包进行注入绑定
<mappers>
<package name="com.project.dao"/>
mappers>
注意点:
声明周期,作用域,是至关重要的,因为错误的使用会导致严重的并发问题
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-KoPBVVMx-1656896670007)(C:\Users\潘文锋\AppData\Roaming\Typora\typora-user-images\image-20220420225837498.png)]
SqlSessionFactoryBuilder
SqlSessionFactory
SqlSession
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-wday8xuk-1656896670008)(C:\Users\潘文锋\AppData\Roaming\Typora\typora-user-images\image-20220420230705350.png)]
这里面的每一个Mapper都是为了执行一个业务~!
实体类
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-1zR6qayh-1656896670009)(C:\Users\潘文锋\AppData\Roaming\Typora\typora-user-images\image-20220420233831796.png)]
数据库字段
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-rQBwSvnB-1656896670009)(C:\Users\潘文锋\AppData\Roaming\Typora\typora-user-images\image-20220420233903240.png)]
当不一致时出现的结果
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-KJ2KHZY3-1656896670010)(C:\Users\潘文锋\AppData\Roaming\Typora\typora-user-images\image-20220420233751245.png)]
我们发现不一致的字段返回值为空
结果集映射
id name pwd
id name password
<resultMap id="getUserById" type="user">
<result column="pwd" property="password"/>
resultMap>
<select id="getUserById" resultType="user" resultMap="getUserById" parameterType="int">
select * from mybatis.user where id = #{id}
select>
如果一个数据库操作,出现了异常,我们需要排错,日志就是最好的助手!
曾经:sout,debug
现在:日志工厂!
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-mS3VDeWi-1656896670011)(C:\Users\潘文锋\AppData\Roaming\Typora\typora-user-images\image-20220421165137276.png)]
<settings>
<setting name="logImpl" value="STDOUT_LOGGING"/>
settings>
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-BBfBWQfZ-1656896670011)(C:\Users\潘文锋\AppData\Roaming\Typora\typora-user-images\image-20220421171914620.png)]
什么是LOG4J?
1.先导入Log4j的包
<dependency>
<groupId>log4jgroupId>
<artifactId>log4jartifactId>
<version>1.2.12version>
dependency>
2.配置mybatis-config.xml
<settings>
<setting name="logImpl" value="LOG4J"/>
settings>
3.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
简单使用
Logger logger = Logger.getLogger(UserDaoTest.class);
logger.info("info:进入了testLog4j");
logger.debug("debug:进入了testLog4j");
logger.error("error:进入了testLog4j");
//实现分页查询
List getUserByLimit(Map map);
<select id="getUserByLimit" resultType="user" resultMap="getUserById" parameterType="map">
select * from mybatis.user limit #{startPage},#{pageSize}
select>
@Test
public void Test01(){
SqlSession sqlSession = MybatisUtils.getSqlSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
HashMap<String, Integer> map = new HashMap<>();
map.put("startPage", 0);
map.put("pageSize",3);
List list = mapper.getUserByLimit(map);
for (Object o : list) {
System.out.println(o);
}
sqlSession.close();
}
//实现分页查询(RowBounds)
List getUserByRowBounds();
<select id="getUserByRowBounds" resultType="user" resultMap="getUserById">
select * from mybatis.user
select>
@Test
public void Test02(){
SqlSession sqlSession = MybatisUtils.getSqlSession();
RowBounds rowBounds = new RowBounds(1,2);
List<Object> objects = sqlSession.selectList("com.project.dao.UserMapper.getUserByRowBounds",null,rowBounds);
for (Object object : objects) {
System.out.println(object);
}
sqlSession.close();
}
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-6EGkWx59-1656896670012)(C:\Users\潘文锋\AppData\Roaming\Typora\typora-user-images\image-20220424215920535.png)]
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-98ALnV8u-1656896670013)(C:\Users\潘文锋\AppData\Roaming\Typora\typora-user-images\image-20220424215939852.png)]
接口
@Select("select * from user")
public ArrayList<User> getUserByList();
配置
<mappers>
<mapper class="com.project.dao.UserMapper"/>
mappers>
测试
@Test
public void test(){
SqlSession sqlSession = MybatisUtils.getSqlSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
List list = mapper.getUserByList();
for (Object o : list) {
System.out.println(o);
}
sqlSession.close();
}
本质:反射机制实现
底层:动态代理!
关于@Param() 注解
接口
@Select("select * from user where id = #{id}")
User getUserById(@Param("id")int id);
测试
@Test
public void getUserByIdTest(){
SqlSession sqlSession = MybatisUtils.getSqlSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
User userById = mapper.getUserById(1);
System.out.println(userById);
sqlSession.close();
}
接口
@Insert("insert into user (`id`,`name`,`pwd`) values(#{id},#{name},#{password})")
int addUser(User user);
测试
@Test
public void addUserTest(){
SqlSession sqlSession = MybatisUtils.getSqlSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
int hello = mapper.addUser(new User(7, "hello", "123321"));
sqlSession.close();
}
接口
@Update("update user set name=#{name},pwd=#{password} where id=#{id}")
int updUser(User user);
测试
@Test
public void updUserTest(){
SqlSession sqlSession = MybatisUtils.getSqlSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
int hello = mapper.updUser(new User(7, "jordan", "123321"));
sqlSession.close();
}
接口
@Delete("delete from user where id=#{id}")
int delUser(@Param("id") int id);
测试
@Test
public void delUserTest(){
SqlSession sqlSession = MybatisUtils.getSqlSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
mapper.delUser(7);
sqlSession.close();
}
<dependency>
<groupId>org.projectlombokgroupId>
<artifactId>lombokartifactId>
<version>1.18.22version>
dependency>
<dependency>
<groupId>org.projectlombokgroupId>
<artifactId>lombokartifactId>
<version>RELEASEversion>
<scope>compilescope>
dependency>
使用
@Data
public class User {
private int id;
private String name;
private String password;
}
优点:
使用Lombok插件可以简化getter和setter的代码,以及构造参数,我们可以使用data注解来创建这些代码
缺点:
破坏了源码的结构,破坏了java语言的规范与统一性
CREATE DATABASE `MyBatis`
USE `Mybatis`
CREATE TABLE `student`
(
`id` INT COMMENT '学号',
`name` VARCHAR(30) NOT NULL COMMENT '姓名',
`tid` INT COMMENT '教室编号',
PRIMARY KEY (`id`),
FOREIGN KEY(`tid`) REFERENCES `teacher`(`id`)
)ENGINE = INNODB DEFAULT CHARSET=utf8
CREATE TABLE `teacher`
(
`id` INT COMMENT '教室编号',
`name` VARCHAR(30) NOT NULL COMMENT '教师姓名',
PRIMARY KEY (`id`)
)ENGINE = INNODB DEFAULT CHARSET=utf8
INSERT `student` VALUES
(1,'张三',1),
(2,'李四',1),
(3,'王五',1),
(4,'赵六',1),
(5,'giao哥',1)
INSERT `teacher` VALUES
(1,'卢本伟')
接口
List getStudents();
配置
<select id="getStudents" resultMap="studentTeacher">
select * from 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 teacher where id = #{id}
select>
测试
@Test
public void test02(){
SqlSession sqlSession = MybatisUtils.getSqlSession();
StudentMapper mapper = sqlSession.getMapper(StudentMapper.class);
List students = mapper.getStudents();
for (Object student : students) {
System.out.println(student);
}
sqlSession.close();
}
配置:
<select id="getStudents2" resultMap="studentsTeacher2">
select s.id sid,s.name sname,t.name tname
from student s,teacher t
where s.tid = t.id
select>
<resultMap id="studentsTeacher2" 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 多对一查询方式:
一对多的处理方式与多对一类似
实体类
@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="getTeacherByStudent" resultMap="TeacherStudent">
select s.id sid,s.name sname,t.id tid,t.name tname
from student s,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>
<select id="getTeacherByStudent2" resultMap="TeacherStudent2">
select * from 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 student where tid = #{tid}
select>
回顾Mysql 多对一查询方式:
注意点:
什么是动态SQL:动态SQL就是指根据不同的条件生成不同的SQL语句
所谓的动态SQL,本质还是SQL语句,只要我们可以在SQL层面,去执行一个逻辑代码
利用动态 SQL 这一特性可以彻底摆脱这种痛苦。
动态 SQL 元素和 JSTL 或基于类似 XML 的文本处理器相似。在 MyBatis 之前的版本中,有很多元素需要花时间了解,MyBatis 3 大大精简了元素种类,现在只需学习原来一半的元素即可 MyBatis 采用功能强大的基于 OGNL 的表达式来淘汰其他大部分元素
环境搭建
CREATE DATABASE `MyBatis`
USE `Mybatis`
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
这条语句提供了可选的查找文本功能。如果不传入 “title”,那么所有处于 “ACTIVE” 状态的 BLOG 都会返回;如果传入了 “title” 参数,那么就会对 “title” 一列进行模糊查找并返回对应的 BLOG 结果(细心的读者可能会发现,“title” 的参数值需要包含查找掩码或通配符字符)。
如果希望通过 “title” 和 “author” 两个参数进行可选搜索该怎么办呢?首先,我想先将语句名称修改成更名副其实的名称;接下来,只需要加入另一个条件即可。
配置sql
<select id="queryBolgIF" parameterType="map" resultType="Blog">
select * from blog where 1=1
<if test="title != null">
and title = #{title}
if>
<if test="author != null">
and author = #{author}
if>
select>
接口
//动态Sql
List<Blog> queryBolgIF(Map map);
测试
@Test
public void test02(){
SqlSession sqlSession = MybatisUtils.getSqlSession();
BlogMapper mapper = sqlSession.getMapper(BlogMapper.class);
HashMap map = new HashMap();
map.put("title", "Java");
List<Blog> blogs = mapper.queryBolgIF(map);
for (Blog blog : blogs) {
System.out.println(blog);
}
sqlSession.close();
}
有时候,我们不想使用所有的条件,而只是想从多个条件中选择一个使用。针对这种情况,MyBatis 提供了 choose 元素,它有点像 Java 中的 switch 语句。
还是上面的例子,但是策略变为:传入了 “title” 就按 “title” 查找,传入了 “author” 就按 “author” 查找的情形。若两者都没有传入,就返回标记为 featured 的 BLOG(这可能是管理员认为,与其返回大量的无意义随机 Blog,还不如返回一些由管理员挑选的 Blog)。
<select id="queryBolgChoose" parameterType="map" resultType="Blog">
select * from blog
<where>
<choose>
<when test="title != null">
title = #{titie}
when>
<when test="author != null">
and author = #{author}
when>
<otherwise>
and views = #{views}
otherwise>
choose>
where>
select>
测试类
@Test
public void test03(){
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.queryBolgChoose(map);
for (Blog blog : blogs) {
System.out.println(blog);
}
sqlSession.close();
}
where 元素只会在子元素返回任何内容的情况下才插入 “WHERE” 子句。而且,若子句的开头为 “AND” 或 “OR”,where 元素也会将它们去除。
<select id="queryBolgIF" parameterType="map" resultType="Blog">
select * from blog
<where>
<if test="title != null">
and title = #{title}
if>
<if test="author != null">
and author = #{author}
if>
where>
select>
set 元素会动态地在行首插入 SET 关键字,并会删掉额外的逗号(这些逗号是在使用条件语句给列赋值时引入的)
<update id="updBlogSet" parameterType="map">
update blog
<set>
<if test="title != null">
title = #{title},
if>
<if test="author != null">
author = #{author},
if>
<if test="views != null">
views = #{views}
if>
set>
where id = #{id}
update>
测试类
@Test
public void test04(){
SqlSession sqlSession = MybatisUtils.getSqlSession();
BlogMapper mapper = sqlSession.getMapper(BlogMapper.class);
HashMap map = new HashMap();
map.put("title", "Java2");
map.put("author", "狂神说2");
map.put("views", "999");
map.put("id", "6587f430c56a4a08995eb453b33c2c4e");
int i = mapper.updBlogSet(map);
sqlSession.close();
}
如果 where 元素与你期望的不太一样,你也可以通过自定义 trim 元素来定制 where 元素的功能。比如,和 where 元素等价的自定义 trim 元素为:
<trim prefix="WHERE" prefixOverrides="AND |OR ">
trim>
prefixOverrides 属性会忽略通过管道符分隔的文本序列(注意此例中的空格是必要的)。上述例子会移除所有 prefixOverrides 属性中指定的内容,并且插入 prefix 属性中指定的内容。
<trim prefix="SET" suffixOverrides=",">
trim>
et 元素会动态地在行首插入 SET 关键字,并会删掉额外的逗号(这些逗号是在使用条件语句给列赋值时引入的)。
来看看与 set 元素等价的自定义 trim 元素吧:
注意,我们覆盖了后缀值设置,并且自定义了前缀值。
有的时候,我们可能会将一些功能的部份抽取出来,方便复用
1.使用SQL标签抽取公共部份
<sql id="if-title-author">
<if test="title != null">
and title = #{title}
if>
<if test="author != null">
and author = #{author}
if>
sql>
2.在需要使用的地方使用include标签引用即可
<select id="queryBlogIF_Sql" parameterType="map" resultType="Blog">
select * from blog
<where>
<include refid="if-title-author"/>
where>
select>
<select id="queryBlogForeach" parameterType="map" resultType="Blog">
select * from blog
<where>
<foreach collection="ids" item="id" open="(" separator="or" close=")">
id = #{id}
foreach>
where>
select>
@Test
public void test06(){
SqlSession sqlSession = MybatisUtils.getSqlSession();
BlogMapper mapper = sqlSession.getMapper(BlogMapper.class);
HashMap map = new HashMap();
ArrayList list = new ArrayList();
list.add(1);
list.add(2);
list.add(3);
//如果list为空则不进入foreach循环,执行select * from blog 语句
map.put("ids",list);
List<Blog> arr = mapper.queryBlogForeach(map);
for (Blog blog : arr) {
System.out.println(blog);
}
sqlSession.close();
}
动态SQL就是在拼接SQL语句,我们只要保证SQL的正确性,按照SQL的格式,去排列组合就可以了
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-AgL7hJWL-1656896670014)(C:\Users\潘文锋\AppData\Roaming\Typora\typora-user-images\image-20220501172357381.png)]一级缓存是默认开启的,只存在于Sqlsession中
缓存失效的情况:
步骤:
<setting name="cacheEnabled" value="true"/>
<cache/>
也可以开启策略
这个更高级的配置创建了一个 FIFO 缓存,每隔 60 秒刷新,最多可以存储结果对象或列表的 512 个引用,而且返回的对象被认为是只读的,因此对它们进行修改可能会在不同线程中的调用者产生冲突。
<cache eviction="FIFO"
flushInterval="60000"
size="512"
readOnly="true"/>
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-cElgyGLr-1656896670014)(C:\Users\潘文锋\AppData\Roaming\Typora\typora-user-images\image-20220501181213868.png)]
@Test
public void test2(){
SqlSession sqlSession1 = MybatisUtils.getSqlSession();
SqlSession sqlSession2 = MybatisUtils.getSqlSession();
UserMapper mapper1 = sqlSession1.getMapper(UserMapper.class);
UserMapper mapper2 = sqlSession2.getMapper(UserMapper.class);
User userById = mapper1.getUserById(1);
sqlSession1.close();
User userById1 = mapper2.getUserById(1);
sqlSession2.close();
}
注意:
如果cache标签没有开启策略需要将对象序列化(实现Serializable接口)
小结:
ehcache