Mybatis
官方文档:https://mybatis.org/mybatis-3/zh/getting-started.html
第一个Mybatis程序
maven配置信息
pom.xml
- maven依赖配置信息,build中的代码解决aven无法被导出或者生效的解决方案
<?xml version="1.0" encoding="UTF8"?>
<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.0</modelVersion>
<groupId>org.example</groupId>
<artifactId>Myabtis-Study-01</artifactId>
<packaging>pom</packaging>
<version>1.0-SNAPSHOT</version>
<modules>
<module>mybatis-01</module>
</modules>
<dependencies>
<!-- 导入mysql驱动-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.47</version>
</dependency>
<!-- mybatis-->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.5.2</version>
</dependency>
<!-- junit-->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
</dependency>
</dependencies>
<!--在build中配置resources,来防止我们资源导出失败的问题-->
<build>
<resources>
<resource>
<directory>src/main/resources</directory>
<includes>
<include>**/*.properties</include>
<include>**/*.xml</include>
</includes>
<filtering>true</filtering>
</resource>
<resource>
<directory>src/main/java</directory>
<includes>
<include>**/*.properties</include>
<include>**/*.xml</include>
</includes>
<filtering>true</filtering>
</resource>
</resources>
</build>
</project>
mybatis配置信息
mybatis-config.xml
- mybatis配置信息
<?xml version="1.0" encoding="UTF8" ?>
<!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=false&allowPublicKeyRetrieval=true&serverTimezone=UTC"/>
<property name="username" value="root"/>
<property name="password" value="root"/>
</dataSource>
</environment>
</environments>
<mappers>
<mapper resource="com/xgm/dao/UserMapper.xml"/>
</mappers>
</configuration>
工具类
MybatisUtils
- 工具类
package com.xgm.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;
//SqlSessionFactory --》SqlSession
public class MybatisUtils {
private static SqlSessionFactory sqlSessionFactory;
static {
try {
//使用Mybatis第一步:获取 SqlSessionFactory 对象
String resource = "mybatis-config.xml";
InputStream inputStream = Resources.getResourceAsStream(resource);
sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
} catch (IOException e) {
e.printStackTrace();
}
}
//既然有了 SqlSessionFactory ,我们就有了 SqlSession 的对象
//SqlSession 完全包含面向数据库执行sql命令所需的所有方法
public static SqlSession getSqlSession(){
return sqlSessionFactory.openSession();
}
}
对象类
User
package com.xgm.pojo;
public class User {
private int id;
private String name;
private String pwd;
public User() {
}
public User(int id, String name, String pwd) {
this.id = id;
this.name = name;
this.pwd = pwd;
}
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 + '\'' +
'}';
}
}
方法接口
UserMapper
package com.xgm.dao;
import com.xgm.pojo.User;
import java.util.List;
public interface UserMapper {
List<User> getUserList();
User getUserById(int id);
void addUser(User user);
void deleteUserById(int id);
void updateUserById(User user);
}
UserMapper.xml
<?xml version="1.0" encoding="UTF8" ?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<!--namespace=绑定了一个对应的Dao/Mapper接口-->
<mapper namespace="com.xgm.dao.UserMapper">
<select id="getUserList" resultType="com.xgm.pojo.User">
select * from mybatis.user;
</select>
</mapper>
测试代码
UserMapperTest
package com.xgm.dao;
import com.xgm.pojo.User;
import com.xgm.utils.MybatisUtils;
import org.apache.ibatis.session.SqlSession;
import org.junit.Test;
import java.util.List;
public class UserMapperTest {
@Test
public void test(){
//第一步:获得sqlSession对象
SqlSession sqlSession = MybatisUtils.getSqlSession();
//方式一:执行sql
UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
List<User> userList = userMapper.getUserList();
for (User user : userList) {
System.out.println(user);
}
//关闭
sqlSession.close();
}
}
CRUD
- 增删改查
select
<select id="getUserById" parameterType="int" resultType="com.xgm.pojo.User">
select * from mybatis.user where id = #{id};
</select>
test
@Test
public void getUserById(){
SqlSession sqlSession = MybatisUtils.getSqlSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
User userById = mapper.getUserById(1);
System.out.println(userById);
sqlSession.close();
}
insert
<insert id="addUser" parameterType="com.xgm.pojo.User">
insert into mybatis.user (id, name, pwd) values (#{id},#{name},#{pwd});
</insert>
test
@Test
public void addUser(){
SqlSession sqlSession = MybatisUtils.getSqlSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
mapper.addUser(new User(5,"小捞","123456"));
//提交事务
sqlSession.commit();
sqlSession.close();
}
update
<update id="updateUserById" parameterType="com.xgm.pojo.User">
UPDATE mybatis.user SET name = #{name},pwd = #{pwd} WHERE (id = #{id});
</update>
test
@Test
public void updateUserById(){
SqlSession sqlSession = MybatisUtils.getSqlSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
mapper.updateUserById(new User(5,"小改","123456"));
//提交事务
sqlSession.commit();
sqlSession.close();
}
delete
<delete id="deleteUserById" parameterType="com.xgm.pojo.User">
delete from mybatis.user where id = #{id};
</delete>
test
@Test
public void deleteUserById(){
SqlSession sqlSession = MybatisUtils.getSqlSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
mapper.deleteUserById(5);
//提交事务
sqlSession.commit();
sqlSession.close();
}
Map
- 多个参数传入需要用到Map
- 或者对象属性过多也可以使用Map
- 项目多用
示例
update
void updateUserById2(Map<String,Object> map);
<update id="updateUserById2" parameterType="map">
UPDATE mybatis.user SET name = #{username},pwd = #{userpwd} WHERE (id = #{id});
</update>
//使用Map进行update
@Test
public void updateUserById2(){
SqlSession sqlSession = MybatisUtils.getSqlSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
Map map = new HashMap<String, Object>();
map.put("username","小紫");
map.put("userpwd","123456");
map.put("id",1);
mapper.updateUserById2(map);
//提交事务
sqlSession.commit();
sqlSession.close();
}
select
User getUserById2(Map<String,Object> map);
<select id="getUserById2" parameterType="map" resultType="com.xgm.pojo.User">
select * from mybatis.user where name = #{name} and pwd = #{pwd};
</select>
//使用Map进行select
@Test
public void getUserById2(){
SqlSession sqlSession = MybatisUtils.getSqlSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
Map map = new HashMap<String, Object>();
map.put("name","小紫");
map.put("pwd","123456");
User userById = mapper.getUserById2(map);
System.out.println(userById);
sqlSession.close();
}
模糊查询
List<User> getUserByLike(String name);
<select id="getUserByLike" resultType="com.xgm.pojo.User">
select * from mybatis.user where name like #{name};
</select>
@Test
public void getUserByLike(){
SqlSession sqlSession = MybatisUtils.getSqlSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
List<User> userByLike = mapper.getUserByLike("%小%");
System.out.println(userByLike);
sqlSession.close();
}
也可在sql中使用通配符,但可能会有sql注入的问题!
<select id="getUserByLike" resultType="com.xgm.pojo.User">
select * from mybatis.user where name like "%"#{name}"%";
</select>
配置解析
1.核心配置文件
-
mybatis-config.xml
-
MyBatis 的配置文件包含了会深深影响 MyBatis 行为的设置和属性信息
配置文档的顶层结构如下:
configuration(配置)
properties(属性)
settings(设置)
typeAliases(类型别名)
typeHandlers(类型处理器)
objectFactory(对象工厂)
plugins(插件)
environments(环境配置)
environment(环境变量)
transactionManager(事务管理器)
dataSource(数据源)
databaseIdProvider(数据库厂商标识)
mappers(映射器)
2.环境配置(environments)
注意一些关键点:
- 默认使用的环境 ID(比如:default=“development”)。
- 每个 environment 元素定义的环境 ID(比如:id=“development”)。
- 事务管理器的配置(比如:type=“JDBC”)。
- 数据源的配置(比如:type=“POOLED”)。
默认环境和环境 ID 顾名思义。 环境可以随意命名,但务必保证默认的环境 ID 要匹配其中一个环境 ID。
<environments default="development">
<environment id="development">
<transactionManager type="JDBC">
<property name="..." value="..."/>
</transactionManager>
<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>
事务管理器默认 JDBC,数据源默认 POOLED
事务管理器(transactionManager)
在 MyBatis 中有两种类型的事务管理器(也就是 type="[JDBC|MANAGED]"):
- JDBC – 这个配置直接使用了 JDBC 的提交和回滚设施,它依赖从数据源获得的连接来管理事务作用域。
- MANAGED – 这个配置几乎没做什么。它从不提交或回滚一个连接,而是让容器来管理事务的整个生命周期(比如 JEE 应用服务器的上下文)。 默认情况下它会关闭连接。然而一些容器并不希望连接被关闭,因此需要将 closeConnection 属性设置为 false 来阻止默认的关闭行为。
数据源(dataSource)
dataSource 元素使用标准的 JDBC 数据源接口来配置 JDBC 连接对象的资源。
- 大多数 MyBatis 应用程序会按示例中的例子来配置数据源。虽然数据源配置是可选的,但如果要启用延迟加载特性,就必须配置数据源。
有三种内建的数据源类型(也就是 type="[UNPOOLED|POOLED|JNDI]"):
- UNPOOLED– 这个数据源的实现会每次请求时打开和关闭连接。虽然有点慢,但对那些数据库连接可用性要求不高的简单应用程序来说,是一个很好的选择。 性能表现则依赖于使用的数据库,对某些数据库来说,使用连接池并不重要,这个配置就很适合这种情形。
- POOLED– 这种数据源的实现利用“池”的概念将 JDBC 连接对象组织起来,避免了创建新的连接实例时所必需的初始化和认证时间。 这种处理方式很流行,能使并发 Web 应用快速响应请求。
- JNDI – 这个数据源实现是为了能在如 EJB 或应用服务器这类容器中使用,容器可以集中或在外部配置数据源,然后放置一个 JNDI 上下文的数据源引用。
3.属性(properties)
这些属性可以在外部进行配置,并可以进行动态替换。你既可以在典型的 Java 属性文件中配置这些属性,也可以在 properties 元素的子元素中设置。
db.properties
driver=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/mybatis?useSSL=false&allowPublicKeyRetrieval=true&serverTimezone=UTC
username=root
password=root
<!--引入外部配置文件db.properties-->
<properties resource="db.properties"/>
<!--也可以自定义一些动态属性-->
<properties>
<property name="" value=""/>
</properties>
设置好的属性可以在整个配置文件中用来替换需要动态配置的属性值。比如:
<dataSource type="POOLED">
<property name="driver" value="${driver}"/>
<property name="url" value="${url}"/>
<property name="username" value="${username}"/>
<property name="password" value="${password}"/>
</dataSource>
注意点:
- 可以直接引入外部文件
- 可以在其中增加一些属性配置
- 如果两个文件有同一个字段,优先使用外部配置文件的!
4.类型别名(typeAliases)
类型别名可为 Java 类型设置一个缩写名字。 它仅用于 XML 配置,意在降低冗余的全限定类名书写。
<!--方法一:在该包下搜索JavaBean,并将其名称的首字母置为小写(大小写都可,建议小写)-->
<!--如果有注解,则别名为其注解值 @Alias("")-->
<typeAliases>
<package name="com.xgm.pojo"/>
</typeAliases>
<!--方法二:可自行DIY别名,但使用较少-->
<typeAliases>
<typeAlias type="com.xgm.pojo.User" alias="User"></typeAlias>
</typeAliases>
一些为常见的 Java 类型内建的类型别名。它们都是不区分大小写的,注意,为了应对原始类型的命名重复,采取了特殊的命名风格。可参照官方文档:xml配置
5.设置(settings)
一个配置完整的 settings 元素的示例如下:
<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>
可参照官方文档
6.映射器(mappers)
既然 MyBatis 的行为已经由上述元素配置完了,我们现在就要来定义 SQL 映射语句了。 但首先,我们需要告诉 MyBatis 到哪里去找到这些语句。 在自动查找资源方面,Java 并没有提供一个很好的解决方案,所以最好的办法是直接告诉 MyBatis 到哪里去找映射文件。 你可以使用相对于类路径的资源引用,或完全限定资源定位符,或类名和包名等。
方式一:使用resource直接定位(建议)
<mappers>
<mapper resource="com/xgm/dao/UserMapper.xml"/>
</mappers>
方式二:使用class文件绑定注册
<mappers>
<mapper class="com.xgm.dao.UserMapper"></mapper>
</mappers>
注意点:
- 接口和他的Mapper配置文件必须同名!
- 接口和他的Mapper配置文件必须在同一个包下!
方式三:使用扫描包进行注入绑定
<mappers>
<package name="com.xgm.dao"/>
</mappers>
注意点:
- 接口和他的Mapper配置文件必须同名!
- 接口和他的Mapper配置文件必须在同一个包下!
8.作用域(Scope)和生命周期
作用域和生命周期类别是至关重要的,因为错误的使用会导致非常严重的并发问题。
SqlSessionFactoryBuilder
- 这个类可以被实例化、使用和丢弃,一旦创建了 SqlSessionFactory,就不再需要它了
- SqlSessionFactoryBuilder 实例的最佳作用域是方法作用域(也就是局部方法变量)
SqlSessionFactory
- 可以理解成是:数据库连接池
- SqlSessionFactory 一旦被创建就应该在应用的运行期间一直存在,没有任何理由丢弃它或重新创建另一个实例
- 因此 SqlSessionFactory 的最佳作用域是应用作用域
- 最简单的就是使用单例模式或者静态单例模式
SqlSession
- 每个线程都应该有它自己的 SqlSession 实例
- SqlSession 的实例不是线程安全的,因此是不能被共享的,所以它的最佳的作用域是请求或方法作用域
- 绝对不能将 SqlSession 实例的引用放在一个类的静态域,甚至一个类的实例变量也不行
- 用完之后立刻关闭,避免资源占用
Mapper
我理解是一个SqlSession的实现类
解决属性名和字段名不一致问题
例子:数据库中的pwd字段名字和User类中的属性password名字不一致。
解决方法:
1.起别名
<select id="getUserById" resultType="com.xgm.pojo.User">
select id,name,pwd as password from mybatis.user where id = #{id};
</select>
2.resultMap
-
resultMap
元素是 MyBatis 中最重要最强大的元素。 -
ResultMap 的设计思想是,对简单的语句做到零配置,对于复杂一点的语句,只需要描述语句之间的关系就行了。
-
但是 HashMap 并不是一个很好的领域模型。你的程序更可能会使用 JavaBean 或 POJO(Plain Old Java Objects,普通老式 Java 对象)作为领域模型。
结果集映射
User: id name pwd
UserMap: id name password
<!--结果集映射-->
<resultMap id="UserMap" type="com.xgm.pojo.User">
<!-- column数据库中的字段,property实体类中的属性 -->
<result property="id" column="id"/>
<result property="name" column="name"/>
<result property="password" column="pwd"/>
</resultMap>
<select id="getUserById" resultMap="UserMap">
select * from mybatis.user where id = #{id};
</select>
日志
日志工厂
设置名 | 描述 | 有效值 | 默认值 |
---|---|---|---|
logImpl | 指定 MyBatis 所用日志的具体实现,未指定时将自动查找。 | SLF4J | LOG4J | LOG4J2 | JDK_LOGGING | COMMONS_LOGGING | STDOUT_LOGGING | NO_LOGGING | 未设置 |
1.STDOUT_LOGGING
- STDOUT_LOGGING标准日志输出
使用
<!--标准的日志工厂的实现-->
<settings>
<setting name="logImpl" value="STDOUT_LOGGING"/>
</settings>
2.LOG4J
简介
- Log4j是Apache的一个开源项目,通过使用Log4j,我们可以控制日志信息输送的目的地是控制台、文件、GUI组件,甚至是套接口服务器、NT的事件记录器、UNIX Syslog守护进程等
- 我们也可以控制每一条日志的输出格式
- 这些可以通过一个配置文件来灵活地进行配置,而不需要修改应用的代码。
- 通过定义每一条日志信息的级别,我们能够更加细致地控制日志的生成过程
使用
先导入log4j的包
<dependencies>
<!-- https://mvnrepository.com/artifact/log4j/log4j -->
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.17</version>
</dependency>
</dependencies>
log4j.properties
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/xgm.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
配置mybatis-config.xml
<settings>
<setting name="logImpl" value="LOG4J"/>
</settings>
分页
Limit分页
SELECT * from user limit <startIndex>,<pageSize>;
用Mybatis实现分页
接口
List<User> getUserLimit(Map<String,Integer> map);
Mapper.xml
<select id="getUserLimit" parameterType="map" resultType="user">
select * from mybatis.user limit #{startIndex},#{pageSize};
</select>
Test
@Test
public void getUserLimit(){
SqlSession sqlSession = MybatisUtils.getSqlSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
Map map = new HashMap<String, Integer>();
map.put("startIndex",0);
map.put("pageSize",2);
List<User> userList = mapper.getUserLimit(map);
for (Object o : userList) {
System.out.println( o);
}
}
使用分页插件
不会用
使用注解开发
面向接口编程
解耦!
使用注解开发
简单的sql语句使用注解开发比较方便,但是对于别名或者复杂的sql语句用xml配置文件更好。
底层主要应用反射!
- 注解在接口上实现
@Select("select * from user")
List<User> getUsers();
- 需要在核心配置文件中绑定接口!
<!-- 绑定接口-->
<mappers>
<mapper class="com.xgm.dao.UserMapper"/>
</mappers>
- 测试
@Test
public void test(){
SqlSession sqlSession = MybatisUtils.getSqlSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
List<User> users = mapper.getUsers();
for (User user : users) {
System.out.println(user);
}
sqlSession.close();
}
本质:反射机制实现
底层:动态代理
CRUD
先在工具类中实现自动提交事务
//自动提交事务:true
public static SqlSession getSqlSession(){
return sqlSessionFactory.openSession(true);
}
编写接口,添加注解
//多个参数需要使用注解 @Param,将简单类型转换为引用类型
@Select("select * from user where id = #{id}")
User getUserById(@Param("id") int id);
//#{password} == @Param("password")
@Insert("insert into user(id,name,pwd) values (#{id},#{name},#{password})")
void addUser(@Param("id") int id,@Param("name") String name,@Param("password") String pwd);
@Update("update user set name = #{name},pwd = #{pwd} where id = #{id}")
void updateUser(User user);
@Delete("delete from user where id = #{id}")
void deleteUser(@Param("id") int id);
测试
只写一个,其他调用对应的方法即可
@Test
public void test2(){
SqlSession sqlSession = MybatisUtils.getSqlSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
User userById = mapper.getUserById(2);
System.out.println(userById);
sqlSession.close();
}
Lombok
偷懒神器,可自动生成Getter、Setter、有参构造、无参构造等等
@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
@ExtensionMethod (Experimental, activate manually in plugin settings)
使用方法
- 安装插件,piugins直接搜Lombok(小辣椒图标)
- 在pom.xml中添加依赖
<!-- https://mvnrepository.com/artifact/org.projectlombok/lombok -->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.16</version>
<scope>provided</scope>
</dependency>
-
在实体类上加注解
例子
@Data
@AllArgsConstructor
@NoArgsConstructor
public class User {
private int id;
private String name;
private String pwd;
}
多对一
测试环境搭建
按照查询嵌套处理
子查询
StudentMapper.xml
<select id="getStudent" resultMap="StudentTeacher">
select * from student;
</select>
<!-- 复杂的属性,我们需要单独处理 对象:association 集合: collection -->
<resultMap id="StudentTeacher" type="Student">
<association property="teacher" column="tid" javaType="Teacher" select="getTeacher"></association>
</resultMap>
<select id="getTeacher" resultType="Teacher">
select * from teacher where id = #{tid}
</select>
按照结果嵌套处理
联表查询
<select id="getStudent2" resultMap="StudentTeacher2">
select s.id sid,s.name sname,t.id tid,t.name tname
from teacher t,student s
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="id" column="tid"/>
<result property="name" column="tname"/>
</association>
</resultMap>
一对多
一样的环境搭建
按照查询嵌套处理
子查询
StudentMapper.xml
<!-- 按照结果嵌套处理-->
<select id="getStudent2" resultMap="StudentTeacher2">
select s.id sid,s.name sname,t.id tid,t.name tname
from teacher t,student s
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="id" column="tid"/>
<result property="name" column="tname"/>
</association>
</resultMap>
按照结果嵌套处理
联表查询
<!-- 按照查询嵌套处理-->
<select id="getStudent" resultMap="StudentTeacher">
select * from student;
</select>
<!-- 复杂的属性,我们需要单独处理 对象:association 集合: collection -->
<resultMap id="StudentTeacher" type="Student">
<association property="teacher" column="tid" javaType="Teacher" select="getTeacher"></association>
</resultMap>
<select id="getTeacher" resultType="Teacher">
select * from teacher where id = #{tid}
</select>
小结
- 关联-association【多对一】
- 集合-collection 【一对多】
- JavaType & ofType
- JavaType 用来指定实体类中属性的类型
- ofType 用来指定映射到List或者集合中的pojo类型,就是泛型中的约束类型!
注意点
- 保证SQL的可读性,尽量保证通俗易懂
- 注意一对多和多对一中,属性名和字段的问题!
- 如果问题不好排查错误,可以使用日志。
动态SQL
测试环境搭建
mybatis-08
IF
判断传入参数是否符合要求,追加sql语句
接口
//if
List<Blog> getBlog(Map map);
xml
<select id="getBlog" 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>
test
//if
@Test
public void getBlog(){
SqlSession sqlSession = MybatisUtils.getSqlSession();
BlogMapper mapper = sqlSession.getMapper(BlogMapper.class);
HashMap map = new HashMap();
map.put("title","Mybatis");
map.put("author","xgm");
List<Blog> blogList = mapper.getBlog(map);
for (Blog blog : blogList) {
System.out.println(blog);
}
sqlSession.close();
}
choose(when,otherwise)
<select id="querBlogChoose" parameterType="map" resultType="blog">
select * from 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>
set
<update id="updateBlog" parameterType="map">
update blog
<set>
<if test="title != null">
title = #{title},
</if>
<if test="author != null">
author = #{author},
</if>
</set>
where id = #{id}
</update>
trim(where,set)
<trim prefix="where" suffixOverrides="AND|OR">
……
</trim>
<trim prefix="set" suffixOverrides=",">
……
</trim>
SQL片段
把公共的部分抽取出来,方便使用
- 用sql标签抽取公共部分
<sql id="if-title-author">
<if test="title != null">
title = #{title},
</if>
<if test="author != null">
author = #{author},
</if>
</sql>
- 在使用的地方使用include标签引用
<include refid="if-title-author"></include>
注意事项:
- 最好基于单表来定义我们的sql片段(简单的sql语言)
- 不要存在where标签
Foreach
xml
<select id="queryBlogForeach" parameterType="map" resultType="blog">
select * from blog
<where>
<foreach collection="ids" item="id" open="(" close=")" separator="or">
id = #{id}
</foreach>
</where>
</select>
test
@Test
public void queryBlogForeach(){
SqlSession sqlSession = MybatisUtils.getSqlSession();
BlogMapper mapper = sqlSession.getMapper(BlogMapper.class);
HashMap map = new HashMap();
ArrayList<Integer> ids = new ArrayList<Integer>();
ids.add(1);
ids.add(2);
ids.add(3);
map.put("ids",ids);
List<Blog> blogList = mapper.queryBlogForeach(map);
for (Blog blog : blogList) {
System.out.println(blog);
}
sqlSession.close();
}
动态SQL其实就是普通的SQL语句,只不过用java语句进行判断,只要我们的SQL不错误,按格式写,就可以正常执行
缓存(Cache)
简介
解决高并发系统问题
减少和数据库的交互次数,减少系统开销,提高系统效率
查询使用缓存
一级缓存
缓存失效的原因:
- 查询不同的数据
- 增删改操作,会刷新原来的缓存
- 查询不同 的Mapper.xml
- 手动清理缓存
sqlSession.clearCache();
一级缓存默认是开启的,只在一次sqlSession中有效,即连接到close这个区间起作用
一级缓存就是一个Map
二级缓存
步骤:
- 开启全局缓存
<!--显示的开启全局缓存-->
<setting name="cacheEnabled" value="true"/>
- 在要使用二级缓存的Mapper中开启
<!--在当前的Mapper.xml中使用二级缓存-->
<cache/>
<!--也可以自定义参数-->
-
测试
@Test public void test2(){ SqlSession sqlSession = MybatisUtils.getSqlSession(); UserMapper mapper = sqlSession.getMapper(UserMapper.class); SqlSession sqlSession2 = MybatisUtils.getSqlSession(); UserMapper mapper2 = sqlSession2.getMapper(UserMapper.class); User userById = mapper.getUserById(1); System.out.println(userById); sqlSession.close(); System.out.println("===================="); User userById2 = mapper2.getUserById(1); System.out.println(userById2); System.out.println(userById == userById2); sqlSession2.close(); }
- 问题:
- 我们需要将实体类序列化!否则就会报错!
public class User implements Serializable { }
小结:
- 只要开启了二级缓存,在同一个Mapper下有效
- 所有的数据都会先放在一级缓存中
- 只有当会话提交,或者关闭的时候,才会提交到二级缓存中!
缓存原理
-
用户访问:用户会先访问二级缓存,然后到一级缓存,若都没有则会创建sqlSession进入数据库进行查询
-
数据存入缓存:在sqlSession开启到关闭期间,数据将会放到sqlSession的一级缓存当中,当sqlSession关闭后,若开启了二级缓存,一级缓存的内容将会存放到二级缓存当中,也就是Mapper的二级缓存当中。