一、初识Mybatis
1、什么是Mybatis?
MyBatis 是一款优秀的持久层框架,它支持自定义 SQL、存储过程以及高级映射。MyBatis 免除了几乎所有的 JDBC 代码以及设置参数和获取结果集的工作。MyBatis 可以通过简单的 XML 或注解来配置和映射原始类型、接口和 Java POJO(Plain Old Java Objects,普通老式 Java 对象)为数据库中的记录。
2、发展历程
MyBatis 本是apache的一个开源项目iBatis, 2010年这个项目由apache software foundation 迁移到了google code,并且改名为MyBatis 。2013年11月迁移到Github。
iBATIS一词来源于“internet”和“abatis”的组合,是一个基于Java的持久层框架。iBATIS提供的持久层框架包括SQL Maps和Data Access Objects(DAOs)
3、特点
-
简单易学:本身就很小且简单。没有任何第三方依赖,最简单安装只要两个jar文件+配置几个sql映射文件易于学习,易于使用,通过文档和源代码,可以比较完全的掌握它的设计思路和实现。
-
灵活:mybatis不会对应用程序或者数据库的现有设计强加任何影响。 sql写在xml里,便于统一管理和优化。通过sql语句可以满足操作数据库的所有需求。
-
解除sql与程序代码的耦合:通过提供DAO层,将业务逻辑和数据访问逻辑分离,使系统的设计更清晰,更易维护,更易单元测试。sql和代码的分离,提高了可维护性。
-
提供映射标签,支持对象与数据库的orm字段关系映射
-
提供对象关系映射标签,支持对象关系组建维护
-
提供xml标签,支持编写动态sql。 [2]
4、网站地址
二、第一个Mybatis程序
1、搭建环境
<dependencies>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.5.2</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
</dependencies>
2、创建一个项目
2.1、编写工具类及配置文件
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
<environments default="development">
<environment id="development">
<transactionManager type="JDBC"/>
<dataSource type="POOLED">
<property name="driver" value="${driver}"/>
<property name="url" value="jdbc:mysql://127.0.0.1:3306/mybatis?useUnicode=true&characterEncoding=utf-8&useSSL=false&serverTimezone=GMT"/>
<property name="username" value="${username}"/>
<property name="password" value="${password}"/>
</dataSource>
</environment>
</environments>
<!-- 配置mapper初始化-->
<mappers>
<mapper resource="com/mam/dao/UserMapper.xml"/>
</mappers>
</configuration>
//从 XML 中构建 SqlSessionFactory
public class MybatisUtils {
//将SqlSessionFactory 提取为成员变量,方便后续操作
private static SqlSessionFactory sqlSessionFactory;
private static InputStream inputStream;
static {
try {
//通过流加载配置文件
String resource = "mybatis-config.xml";
inputStream = Resources.getResourceAsStream(resource);
sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
} catch (IOException e) {
e.printStackTrace();
}
}
//返回一个openSession对象,该对象完全包含了面向数据库执行sql命令所需的所有方法
public static SqlSession getSqlSession(){
return sqlSessionFactory.openSession();
}
}
3、编写代码
1、实体类
//实体类,属性一一对应数据库中的字段
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 + '\'' +
'}';
}
}
2、dao/Mapper层
public interface UserDao {
List<User> getUserAll();
}
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<!--namespace: 命名空间,对应Dao/Mapper类的全路径,让其形成对应关系-->
<mapper namespace="com.mam.dao.UserDao">
<!-- select 查询语句-->
<select id="getUserAll" resultType="com.mam.pojo.User">
select * from user
</select>
</mapper>
4、测试
public class UserDaoTest {
@Test
public void test01(){
//通过工具类获得sqlSession对象
SqlSession sqlSession = MybatisUtils.getSqlSession();
//方式一:getMapper
UserDao dao = sqlSession.getMapper(UserDao.class);
List<User> userAll = dao.getUserAll();
for (User user : userAll) {
System.out.println(user);
}
//关闭sqlSession
sqlSession.close();
}
}
第一次执行,报如下错误:
java.lang.ExceptionInInitializerError
解决方案:在mybatis核心配置文件中加入:
<!-- 对每一个mapper都需要: 配置注册mapper初始化-->
<mappers>
<mapper resource="com/mam/dao/UserMapper.xml"/>
</mappers>
第二次执行,报如下错误:
java.lang.ExceptionInInitializerError
at com.mam.dao.UserDaoTest.test01(UserDaoTest.java:15)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)
at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:78)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:57)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
at org.junit.runner.JUnitCore.run(JUnitCore.java:137)
at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:68)
at com.intellij.rt.execution.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:47)
at com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:242)
at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:70)
Caused by: org.apache.ibatis.exceptions.PersistenceException:
### Error building SqlSession.
### The error may exist in com/mam/dao/UserMapper.xml
### Cause: org.apache.ibatis.builder.BuilderException: Error parsing SQL Mapper Configuration. Cause: java.io.IOException: Could not find resource com/mam/dao/UserMapper.xml
at org.apache.ibatis.exceptions.ExceptionFactory.wrapException(ExceptionFactory.java:30)
at org.apache.ibatis.session.SqlSessionFactoryBuilder.build(SqlSessionFactoryBuilder.java:80)
at org.apache.ibatis.session.SqlSessionFactoryBuilder.build(SqlSessionFactoryBuilder.java:64)
at com.mam.utils.MybatisUtils.<clinit>(MybatisUtils.java:21)
... 23 more
Caused by: org.apache.ibatis.builder.BuilderException: Error parsing SQL Mapper Configuration. Cause: java.io.IOException: Could not find resource com/mam/dao/UserMapper.xml
at org.apache.ibatis.builder.xml.XMLConfigBuilder.parseConfiguration(XMLConfigBuilder.java:121)
at org.apache.ibatis.builder.xml.XMLConfigBuilder.parse(XMLConfigBuilder.java:98)
at org.apache.ibatis.session.SqlSessionFactoryBuilder.build(SqlSessionFactoryBuilder.java:78)
... 25 more
Caused by: java.io.IOException: Could not find resource com/mam/dao/UserMapper.xml
at org.apache.ibatis.io.Resources.getResourceAsStream(Resources.java:114)
at org.apache.ibatis.io.Resources.getResourceAsStream(Resources.java:100)
at org.apache.ibatis.builder.xml.XMLConfigBuilder.mapperElement(XMLConfigBuilder.java:372)
at org.apache.ibatis.builder.xml.XMLConfigBuilder.parseConfiguration(XMLConfigBuilder.java:119)
... 27 more
原因:
maven由于他的约定大于配置,所以可能遇到我们写的配置文件,无法被导出或者生效的问题。
解决方案:
在pom.xml文件中加入:
<!-- 在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>
三、Mybatis实现CRUD
首先,我们还是先来继续看一下mapper文件中一些属性
1、namespace
命名空间:包名必须要和Dao/Mapper接口的包名保持一致
2、select
选择,查询语句
-
id : 对应Mapper接口中的方法名
-
resultType : 对应SQL语句执行的返回值
-
parameterType:参数类型
3、增删改
mapper接口:
public interface UserMapper {
//查询所有用户
List<User> getUserAll();
//根据id查询用户
User queryUserById(int id);
//插入用户
int addUser(User user);
//修改用户
int updateUser(User user);
//删除用户
int deleteUser(int id);
}
mapper.xml:
<!--namespace: 命名空间,对应Dao/Mapper类的全路径,让其形成对应关系-->
<mapper namespace="com.mam.dao.UserMapper">
<!-- select 查询语句-->
<select id="getUserAll" resultType="com.mam.pojo.User">
select * from user
</select>
<select id="queryUserById" parameterType="int" resultType="com.mam.pojo.User">
select * from user where id = #{id}
</select>
<insert id="addUser" parameterType="com.mam.pojo.User">
insert into mybatis.user (id,name ,pwd) values (#{id},#{name},#{pwd})
</insert>
<update id="updateUser" parameterType="com.mam.pojo.User">
update user set name = #{name} ,pwd = #{pwd} where id=#{id}
</update>
<delete id="deleteUser" parameterType="int">
delete from user where id = #{id}
</delete>
</mapper>
测试类:
public class UserDaoTest {
@Test
public void test01(){
//通过工具类获得sqlSession对象
SqlSession sqlSession = MybatisUtils.getSqlSession();
//方式一:getMapper
UserMapper dao = sqlSession.getMapper(UserMapper.class);
List<User> userAll = dao.getUserAll();
for (User user : userAll) {
System.out.println(user);
}
//关闭sqlSession
sqlSession.close();
}
@Test
public void queryUserByIdTest() {
SqlSession sqlSession = MybatisUtils.getSqlSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
User user = mapper.queryUserById(1);
System.out.println("user = " + user);
sqlSession.close();
}
@Test
public void addUserTest(){
SqlSession sqlSession = MybatisUtils.getSqlSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
int lmx = mapper.addUser(new User(5, "lmx", "123456"));
if (lmx > 0) {
System.out.println("插入成功");
}
//增删改必须要提交事务
sqlSession.commit();
sqlSession.close();
}
@Test
public void updateUserTest(){
SqlSession sqlSession = MybatisUtils.getSqlSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
int kls = mapper.updateUser(new User(4, "kls", "111111"));
if (kls > 0) {
System.out.println("修改成功");
}
sqlSession.commit();
sqlSession.close();
}
@Test
public void deleteUserTest(){
SqlSession sqlSession = MybatisUtils.getSqlSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
int kls = mapper.deleteUser(4);
if (kls > 0) {
System.out.println("删除成功");
}
sqlSession.commit();
sqlSession.close();
}
}
注意:增删改必需要提交事务
4、传入Map参数类型
假设,我们的实体类,或者数据库当中的表,字段或者参数过多,我们应当考虑将传入参数由实体类替换为Map类型
代码示例:
mapper接口:
//插入用户,传入参数为map类型
int addUser2(Map<String,Object> map);
xml文件:
<!--#{} 传入的是map中的键-->
<insert id="addUser2" parameterType="map">
insert into mybatis.user (id,name ,pwd) values (#{userId},#{userName},#{password})
</insert>
测试文件:
@Test
public void addUser2Test(){
SqlSession sqlSession = MybatisUtils.getSqlSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
Map<String, Object> map = new HashMap<String, Object>();
map.put("userId",4);
map.put("userName","kls");
map.put("password","999999");
int lmx = mapper.addUser2(map);
if (lmx > 0) {
System.out.println("插入成功");
}
//增删改必须要提交事务
sqlSession.commit();
sqlSession.close();
}
四、Maybatis配置解析
1、核心配置文件
-
mybatis-config.xml
-
MyBatis 的配置文件包含了会深深影响 MyBatis 行为的设置和属性信息。
configuration(配置) properties(属性) settings(设置) typeAliases(类型别名) typeHandlers(类型处理器) objectFactory(对象工厂) plugins(插件) environments(环境配置) environment(环境变量) transactionManager(事务管理器) dataSource(数据源) databaseIdProvider(数据库厂商标识) mappers(映射器)
2、环境配置(environments)
MyBatis 可以配置成适应多种环境
不过要记住:尽管可以配置多个环境,但每个 SqlSessionFactory 实例只能选择一种环境。
配置不同的环境,选用不同的环境id即可
Mybatis默认的事务管理器就是JDBC,连接池:POOLED
3、属性(properties)
我们可以通过properties属性来实现引用配置文件
这些属性可以在外部进行配置,并可以进行动态替换。你既可以在典型的 Java 属性文件中配置这些属性,也可以在 properties 元素的子元素中设置。【db.properties】
xml文件中,规定了标签的编写顺序!
编写一个配置文件:
url=jdbc:mysql://127.0.0.1:3306/mybatis?useUnicode=true&characterEncoding=utf-8&useSSL=false&serverTimezone=GMT
driver=com.mysql.cj.jdbc.Driver
username=root
password=root
在核心配置文件中引入:
<!-- 引入外部配置文件-->
<properties resource="db.properties">
<property name="username" value="root"/>
<property name="password" value="root"/>
</properties>
注意:
-
可以直接引入外部文件
-
可以在其中增加一些属性配置
-
外部文件[db.properties]配置优先级 > properties中属性配置
4、类型别名(typeAliases)
-
类型别名可为 Java 类型设置一个缩写名字。 它仅用于 XML 配置,意在降低冗余的全限定类名书写。
<!-- 引入外部配置文件-->
<properties resource="db.properties">
<property name="username" value="root"/>
<property name="password" value="root"/>
</properties>
-
也可以指定一个包名,MyBatis 会在包名下面搜索需要的 Java Bean,比如:
<!-- 开启包扫描-->
<typeAliases>
<package name="com.mam.pojo"/>
</typeAliases>
扫描实体类的包,它的默认别名就为这个类的类名,首字母小写
-
在实体类比较少的时候,推荐使用第一种方式。
-
如果实体类较多,建议开启包扫描
-
区别:第一种可以自定义别名,第二种默认为类名小写(包扫描如果要自定义,可以使用注解)
5、设置(settings)
这是 MyBatis 中极为重要的调整设置,它们会改变 MyBatis 的运行时行为。
<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>
具体介绍详见Mybatis官方文档。
6、其他配置
-
-
Mybatis-plugs
-
通用mapper
-
7、映射器(mappers)
既然 MyBatis 的行为已经由上述元素配置完了,我们现在就要来定义 SQL 映射语句了。 但首先,我们需要告诉 MyBatis 到哪里去找到这些语句。 在自动查找资源方面,Java 并没有提供一个很好的解决方案,所以最好的办法是直接告诉 MyBatis 到哪里去找映射文件。 你可以使用相对于类路径的资源引用,或完全限定资源定位符(包括 file:///
形式的 URL)
方式一:
<!-- 对每一个mapper都需要: 配置注册mapper初始化-->
<mappers>
<mapper resource="com/mam/mapper/UserMapper.xml"/>
</mappers>
方式二:
<mappers>
<mapper class="com.mam.mapper.UserMapper"/>
</mappers>
注意点:
-
接口必须和他的Mapper配置文件同名!
-
接口必须和他的Mapper配置文件在同一个包下!
方式三:
<mappers>
<package name="com.mam.mapper"/>
</mappers>
注意点:
-
接口必须和他的Mapper配置文件同名!
-
接口必须和他的Mapper配置文件在同一个包下!
8、生命周期
不同作用域和生命周期类别是至关重要的,因为错误的使用会导致非常严重的并发问题。
sqlSessionFactoryBuilder:
-
一旦创建了sqlSessionFactory,就不需要他了
-
局部变量
sqlSessionFactory:
-
我们可以将其理解为:数据库连接池
-
sqlSessionFactory 一旦被创建就应该在应用的运行期一直存在,没有任何理由丢弃它或者重新创建另一个实例。
-
因此sqlSessionFactory 的最佳作业域是应用作用域
-
最简单的就是使用单例模式或者静态单例模式。
sqlSession:
-
我们可以将其看作连接到连接池的一个请求
-
sqlSession的实例不是线程安全的,因此是不能被共享的,所以它的最佳的作用域是请求或者方法作用域。
-
用完之后需要赶紧关闭,否则资源被占用
上图的每一个Mapper 就代表一个具体的业务。
五、结果集映射(解决属性名和字段名不一致的问题)
1、问题
当pojo实体类中的属性与数据库字段不一致时(数据库字段pwd,User类属性名password):
本质是:
select * from user where id = #{id}
//mybatis类型处理器处理 pwd 无法与password形成对应关系
select id,name,pwd from user where id = #{id}
解决方法一:
-
起别名
<select id="queryUserById" parameterType="int" resultType="com.mam.pojo.User">
select id,name,pwd as password from user where id = #{id}
</select>
2、ResultMap
结果集映射
<!-- 结果集映射-->
<resultMap id="UserMap" type="user">
<!-- column 数据库中的字段,property实体类-->
<result column="id" property="id"/>
<result column="name" property="name"/>
<result column="pwd" property="password"/>
</resultMap>
<select id="queryUserById" parameterType="int" resultMap="UserMap">
select * from user where id = #{id}
</select>
-
resultMap
元素是 MyBatis 中最重要最强大的元素。 -
ResultMap 的设计思想是,对简单的语句做到零配置,对于复杂一点的语句,只需要描述语句之间的关系就行了。
-
ResultMap
最优秀的地方在于,虽然你已经对它相当了解了,但是根本就不需要显式地用到他们。 -
如果这个世界总是这么简单就好了。
六、日志
1、日志工程
如果一个数据库操作,出现了异常,我们需要排错。日志就是最好的助手
过去:sout,debug方式去排错
现在:通过日志工厂!
-
SLF4J
-
LOG4J [掌握]
-
LOG4J2
-
JDK_LOGGING
-
COMMONS_LOGGING
-
STDOUT_LOGGING [掌握]
-
NO_LOGGING
在Mybatis中具体使用哪个日志实现,在设置中设定
STDOUT_LOGGING:标准日志输出
在mybatis核心配置文件中,配置我们的日志
<settings>
<setting name="logImpl" value="STDOUT_LOGGING"/>
</settings>
2、LOG4J
什么是log4j:
-
我们也可以控制每一条日志的输出格式
-
通过定义每一条日志信息的级别,我们能够更加细致地控制日志的生成过程
-
可以通过一个配置文件来灵活地进行配置,而不需要修改应用的代码。
使用步骤:
1、导包
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.17</version>
</dependency>
2、添加配置文件log4j.properties
# \u8BBE\u7F6E\u5168\u5C40\u7684\u65E5\u5FD7\u8F93\u51FA\u7EA7\u522B\u662Fdebug
# \u8BBE\u7F6E\u5168\u5C40\u7684\u8F93\u51FA\u6E90\u662Fstdout-\u8F93\u51FA\u5230\u63A7\u5236\u53F0
log4j.rootLogger=debug, stdout
# \u8BBE\u7F6Estdout\u8F93\u51FA\u6E90\u7684\u76F8\u5173\u4FE1\u606F
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%5p [%t] - %m%n
# \u8BBE\u7F6Efile\u8F93\u51FA\u6E90\u7684\u76F8\u5173\u4FE1\u606F\uFF08\u8F93\u51FA\u5230\u78C1\u76D8\u6587\u4EF6\u4E2D\uFF09
log4j.appender.LOGFILE=org.apache.log4j.FileAppender
# \u6307\u5B9A\u65E5\u5FD7\u6587\u4EF6\u7684\u78C1\u76D8\u8DEF\u5F84
# linux\u4E0B /usr/log/logInfo.log
log4j.appender.LOGFILE.File=d:\logInfo.log
log4j.appender.LOGFILE.Append=true
log4j.appender.LOGFILE.layout=org.apache.log4j.PatternLayout
log4j.appender.LOGFILE.layout.ConversionPattern=%d{ISO8601} %-6r [%15.15t] %-5p %30.30c %x - %m\n
3、进行查询测试
简单使用:
-
在要使用log4j的类中,导入包import org.apache.log4j.Logger;
-
日志对象,参数为当前类的class对象
static Logger logger = Logger.getLogger(UserDaoTest.class);
-
日志级别
@Test
public void testLog4j(){
logger.info("info:进入方法");
logger.debug("debug:进入方法");
logger.error("error:进入方法");
}
七、分页
为什么要分页? ——减少数据的处理量
1、使用Limit分页
语法:SELECT * FROM USER LIMIT startIndex,pageSize; select * from user limit 3; #[0,n]
使用Mybatis实现分页,核心SQL
-
接口
//分页查询
List<User> queryUserByLimit(Map<String,Integer> map);
-
Mapper.xml
<!-- 分页查询-->
<select id="queryUserByLimit" parameterType="map" resultMap="UserMap">
select * from mybatis.user limit #{startIndex},#{pageSize}
</select>
-
测试
@Test
public void testLimit(){
SqlSession sqlSession = MybatisUtils.getSqlSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
Map<String, Integer> map = new HashMap<String, Integer>();
map.put("startIndex",2);
map.put("pageSize",2);
List<User> users = mapper.queryUserByLimit(map);
for (User user : users) {
System.out.println(user);
}
sqlSession.close();
}
2、RowBounds分页
1.接口
//分页查询2
List<User> queryUserByRowBounds();
2.Mapper.xml
<!-- 分页查询2-->
<select id="queryUserByRowBounds" resultMap="UserMap">
select * from mybatis.user
</select>
3.测试
xx
@Test
public void testRowBounds(){
SqlSession sqlSession = MybatisUtils.getSqlSession();
RowBounds rowBounds = new RowBounds(1, 2);
List<User> userList = sqlSession.selectList("com.mam.mapper.UserMapper.queryUserByRowBounds", null, rowBounds);
for (User user : userList) {
System.out.println("user = " + user);
}
sqlSession.close();
}
3、分页插件
了解即可!
八、使用注解开发
1、面向接口编程
-
之前我们学习过面向对象编程,也学习过接口,但在真正的开发中,很多时候我们会选择面向接口编程
根本原因: 解耦,可拓展,提高复用,分层开发中,上层不用管具体的实现,大家都遵守共同的标准,使得开发变得容易,规范性更好。
-
在一个面向对象的系统中,系统的各种功能是由许许多多的不同对象协作完成的。在这种情况下,各个对象内部是如何实现自己的,对系统设计人员来讲就不那么重要了;
-
而各个对象之间的协作关系则成为系统涉及的关键,小到不同类之间的通信,大到各模块之间的交互,在系统设计之初都是要着重考虑的,这也是系统设计的主要工作内容。面向接口编程就是指按照这种思想来编程。
关于接口的理解
-
接口从更深层次的理解,应是定义(规范,约束)与实现(名实分离的原则)的分离。
-
接口的本身反映了系统设计人员对系统的抽象理解。
-
接口应有两类:
-
第一类是一个个体的抽象,它可对应为一个抽象体(abstract class)
-
第二类是对一个个体某一方面的抽象,即形成一个抽象面(interface)
-
-
一个个体有可能有多个抽象面,抽象体和抽象面是有区别的。
三个面向区别
-
面向对象是指,我们考虑问题时,以对象为单位,考虑它的属性及方法。
-
面向过程是指,我们考虑问题时,以一个具体的流程(事务过程)为单位,考虑它的实现。
-
接口涉及与非接口设计是针对复用技术而言的,与面向对象(过程)不是一个问题,更多的体现就是对系统整体的架构。
2、使用注解开发
1.注解在接口上实现
@Select("select * from user")
List<User> queryUsers();
2.需要在核心配置文件中绑定接口
<mappers>
<mapper class="com.mam.mapper.UserMapper"/>
</mappers>
3.测试
@Test
public void test(){
SqlSession sqlSession = MybatisUtils.getSqlSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
List<User> users = mapper.queryUsers();
for (User user : users) {
System.out.println("user = " + user);
}
sqlSession.close();
}
本质:反射机制实现
底层:静态代理
3、CRUD
我们可以在工具类创建的时候实现自动提交事务!
public static SqlSession getSqlSession(){
return sqlSessionFactory.openSession(true);
}
接口:
public interface UserMapper {
@Select("select * from user")
List<User> queryUsers();
@Insert("insert into user (id,name,pwd) values(#{id},#{name},#{password})")
int addUser(User user);
@Delete("delete from user where id = #{id}")
int deleteUser(@Param("id") int id);
@Update("update user set name = #{name},pwd = #{password} where id = #{id}")
int updateUser(User user);
}
注意:
我们必须要将接口注册绑定到我们的核心配置文件当中
@Param()注解:
-
基本类型的参数或者String类型,需要加上
-
引用类型不用加
-
如果只有一个基本类型的话,可以忽略
-
我们在SQL中引用的就是我们这里的@Param()中设定的属性名
#{} 和${}区别
#{}是预编译处理,$ {}是字符串替换。
mybatis在处理#{}时,会将sql中的#{}替换为?号,调用PreparedStatement的set方法来赋值,使用 #{} 可以有效的防止SQL注入,提高系统安全性。
mybatis在处理 $ { } 时,就是把 ${ } 替换成变量的值。
九、多对一处理
-
多个学生,对应一个老师
-
对于学生这边而言,关联...多个学生,关联一个老师【多对一】
-
对于老师而言,集合:一个老师,有很多学生【一对多】
SQL:
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);
1、测试环境搭建
1.导入Lombok
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.20</version>
<scope>provided</scope>
</dependency>
2.新建实体类
@Data
public class Student {
private int id;
private String name;
private Teacher teacher;
}
@Data
public class Teacher {
private int id;
private String name;
}
3.建立Mapper接口
public interface StudentMapper {
}
public interface TeacherMapper {
@Select("select * from teacher where id = #{id}")
Teacher getTeacher(@Param("id") int id);
}
4.建立Mapper.xml文件
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.mam.mapper.StudentMapper">
</mapper>
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.mam.mapper.TeacherMapper">
</mapper>
5.在核心配置文件中绑定注册我们的Mapper接口或者文件
<mappers>
<mapper class="com.mam.mapper.TeacherMapper"/>
<mapper class="com.mam.mapper.StudentMapper"/>
</mappers>
6.测试查询是否能够成功
public class TestMapper {
@Test
public void testTeacher(){
SqlSession sqlSession = MybatisUtils.getSqlSession();
TeacherMapper mapper = sqlSession.getMapper(TeacherMapper.class);
Teacher teacher = mapper.getTeacher(1);
System.out.println("teacher = " + teacher);
sqlSession.close();
}
}
2、按照查询嵌套处理
<mapper namespace="com.mam.mapper.StudentMapper">
<!--
思路:
1.查询所有的学生信息
2.根据查询出来的学生的tid,寻找对应的老师
-->
<select id="getStudent" resultMap="studentTeacher">
select * from student
</select>
<resultMap id="studentTeacher" type="Student">
<!-- 复杂的属性,我们需要单独处理 对象 association 集合:collection-->
<association property="teacher" column="tid" javaType="Teacher" select="getTeacher"/>
</resultMap>
<select id="getTeacher" resultType="teacher">
select * from teacher where id = #{id}
</select>
</mapper>
3、按照结果嵌套处理
<select id="getStudent2" resultMap="studentTeacher2">
select s.id sid , s.name sname , t.name tname
from student s,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>
十、一对多处理
1、测试环境搭建
实体类:
@Data
public class Teacher {
private int id;
private String name;
// 一个老师对应多个学生
private List<Student> students;
}
2、按照结果嵌套处理
接口:
public interface TeacherMapper {
//获取老师
Teacher getTeacher(@Param("tid") int id);
}
xml文件:
<select id="getTeacher" parameterType="int" 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"/>
<!-- 复杂的属性,我们需要单独处理 对象 association 集合:collection
javaType 指定属性的类型;
集合中的泛型西悉尼,用ofType获取
-->
<collection property="students" ofType="student">
<result property="id" column="sid"/>
<result property="name" column="sname"/>
</collection>
</resultMap>
3、按照查询嵌套处理
接口:
public interface TeacherMapper {
//获取老师
Teacher getTeacher(@Param("tid") int id);
Teacher getTeacher2(@Param("tid") int id);
}
xml:
<select id="getTeacher2" parameterType="int" resultMap="TeacherStudent2">
select * from mybatis.teacher where id = #{tid}
</select>
<resultMap id="TeacherStudent2" type="teacher">
<collection property="students" ofType="student" column="id" select="getStudent"/>
</resultMap>
<select id="getStudent" resultType="student" parameterType="int">
select * from mybatis.student where tid = #{id}
</select>
4、小结
1.关联:association【多对一】
2.集合 - collection 【一对多】
3.javaType & ofType
1.JavaType 用来指定实体类中属性的类型
2.ofType 用来指定映射到List或者集合中的pojo类型,泛型中的约束类型
注意点
-
保证SQL的可读性,尽量通俗易懂
-
注意一对多和多对一中,属性名和字段的问题
-
如果问题不好排查错误,可以使用日志,建议log4j
十一、动态SQL
1、环境搭建:
sql文件:
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
创建一个基础工程
-
导包
-
编写配置文件
<?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "http://mybatis.org/dtd/mybatis-3-config.dtd"> <configuration> <!-- 引入外部配置文件--> <properties resource="db.properties"> <property name="username" value="root"/> <property name="password" value="root"/> </properties> <settings> <!-- 标准的日志输出--> <setting name="logImpl" value="STDOUT_LOGGING"/> <!-- 指定日志使用log4j--> <!-- <setting name="logImpl" value="LOG4J"/>--> <!-- 是否开启驼峰命名自动映射,即从经典数据库列名 A_COLUMN 映射到经典 Java 属性名 aColumn。--> <setting name="mapUnderscoreToCamelCase" value="true"/> </settings> <!-- 给实体类配置别名--> <!-- <typeAliases>--> <!-- <typeAlias type="com.mam.pojo.User" alias="User"/>--> <!-- </typeAliases>--> <!-- 给实体类包下面的所有实体配置别名--> <typeAliases> <package name="com.mam.pojo"/> </typeAliases> <!-- mybatis运行环境信息,default指定默认的运行环境--> <environments default="development"> <environment id="development"> <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> <mappers> <mapper class="com.mam.mapper.BlogMapper"/> </mappers> </configuration>
-
编写实体类
@Data public class Blog { private String id; private String title; private String author; private Date createTime; private int views; }
-
编写对应的Mapper接口和xml文件
public interface BlogMapper {
}
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.mam.mapper.BlogMapper">
</mapper>
2、IF
接口:
public interface BlogMapper {
int addBlog(Blog blog);
List<Blog> queryBlogIF(Map map);
}
xml:
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.mam.mapper.BlogMapper">
<insert id="addBlog" parameterType="blog">
insert into mybatis.blog (id, title, author, create_time, views)
values(#{id}, #{title}, #{author}, #{createTime}, #{views})
</insert>
<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>
</mapper>
3、choose、when、otherwise
接口:
public interface BlogMapper {
List<Blog> queryBlogChoose(Map map);
}
xml:
<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>
views = #{views}
</otherwise>
</choose>
</where>
</select>
4、trim、where、set
where:
where 元素只会在子元素返回任何内容的情况下才插入 “WHERE” 子句。而且,若子句的开头为 “AND” 或 “OR”,where 元素也会将它们去除。
<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>
set:
set 元素会动态地在行首插入 SET 关键字,并会删掉额外的逗号(这些逗号是在使用条件语句给列赋值时引入的)。
<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>
5、SQL片段
有的时候,我们可能会将一些公共的部分抽取出来,方便复用
-
使用SQL标签抽取公共的部分
<sql id="if-sql"> <if test="title != null"> and title = #{title} </if> <if test="author != null"> and author = #{author} </if> </sql>
-
在需要使用的地方使用include标签引用即可
<include refid="if-sql"></include>
注意事项:
-
最好基于表单来定于SQL片段
-
不要存在where标签
6、Foreach
接口:
List<Blog> queryBlogForeach(Map map);
xml:
<select id="queryBlogForeach" parameterType="map" resultType="blog">
select * from mybatis.blog
<where>
<foreach collection="ids" item="id" open="(" close=")" separator="or">
id = #{id}
</foreach>
</where>
</select>
7、总结
所谓的动态SQL,本质还是SQL语句,只是我们可以在SQL层面,去执行一些逻辑代码
什么是动态SQL:动态SQL就是指根据不同的条件生成不同的SQL语句。
动态SQL就是在拼接SQL语句,我们只要保证SQL的正确性,按照SQL的格式,去排列组合就可以了
建议:
-
先在Mysql中写出完整的SQL,再对应的去修改成为我们的SQL,实现通用即可
十二、缓存
1、简介
查询: 连接数据库 ,耗资源 一次查询的结果,将他暂存到一个可以直接取到的地方 -->内存 : 缓存 我们再次查询相同数据的时候,直接走缓存,就不要走数据库了
-
什么是缓存[Cache]?
-
存在内存中的临时数据
-
将用户经常查询的数据放在缓存(内存)中,用户去查询数据就不用从磁盘上(关系型数据库数据文件)查询,从缓存中查询,从而提高查询效率,解决了高并发系统的性能问题。
-
-
为什么使用缓存?
-
减少喝数据库的交互次数,减少系统开销,提高系统效率。
-
-
什么样的数据库能使用缓存?
-
经常查询并且不经常改变的数据。【可以使用缓存】
-
2、Mybatis缓存
-
MyBatis包含一个非常强大的查询缓存特性,它可以非常方便的定制喝配置缓存,缓存可以极大的提升查询效率。
-
MyBatis系统中默认定义了两级缓存:一级缓存和二级缓存
-
默认情况下,只有一级缓存开启。(SqlSession级别的缓存,也称为本地缓存)
-
二级缓存需要手动开启和配置,他是基于namespace级别的缓存。
-
为了提高拓展性,MyBatis定义了缓存接口Cache,我们可以通过实现Cache接口来自定义二级缓存
-
3、一级缓存
-
一级缓存也叫本地缓存:SqlSession
-
与数据库同义词会话期间查询到的数据会放到本地缓存中
-
以后如果获取到相同的数据,直接从缓存中拿,没必要再去查询数据库
-
测试:
public class MyTest {
@Test
public void test(){
SqlSession sqlSession = MybatisUtils.getSqlSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
User user = mapper.queryUser(1);
System.out.println(user);
System.out.println("============================");
User user2 = mapper.queryUser(1);
System.out.println(user2);
System.out.println(user == user2);
sqlSession.close();
}
}
查看日志输出:
-
映射语句文件中的所有 select 语句的结果将会被缓存。
-
映射语句文件中的所有 insert、update 和 delete 语句会刷新缓存。
public class MyTest {
@Test
public void test(){
SqlSession sqlSession = MybatisUtils.getSqlSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
User user = mapper.queryUser(1);
System.out.println(user);
mapper.updateUser(new User(2,"李明旭","123456"));
System.out.println("============================");
User user2 = mapper.queryUser(1);
System.out.println(user2);
System.out.println(user == user2);
sqlSession.close();
}
}
-
缓存会使用最近最少使用算法(LRU, Least Recently Used)算法来清除不需要的缓存。
-
缓存不会定时进行刷新(也就是说,没有刷新间隔)。
-
缓存会保存列表或对象(无论查询方法返回哪种)的 1024 个引用。
-
缓存会被视为读/写缓存,这意味着获取到的对象并不是共享的,可以安全地被调用者修改,而不干扰其他调用者或线程所做的潜在修改。
一级缓存就是一个Map
4、二级缓存
-
二级缓存也叫全局缓存,一级缓存作用域太低了,所以诞生了二级缓存
-
基于namespace级别的缓存,一个名称空间,对应一个二级缓存
-
工作机制
-
一个会话查询一条数据,这个数据就会被放在当前会话的一级缓存中;
-
如果当前会话关闭了,这个会话对应的一级缓存就没了,但是我们想要的是,会话关闭了,一级缓存中的数据被保存到二级缓存中;
-
新的会话查询信息,就可以从二级缓存中获取内容;
-
不同的mapper查出的数据会放在自己对应的缓存(map)中
-
步骤:
1.开启全局缓存
<settings>
<!-- 标准的日志输出-->
<setting name="logImpl" value="STDOUT_LOGGING"/>
<!-- 指定日志使用log4j-->
<!-- <setting name="logImpl" value="LOG4J"/>-->
<!-- 是否开启驼峰命名自动映射,即从经典数据库列名 A_COLUMN 映射到经典 Java 属性名 aColumn。-->
<setting name="mapUnderscoreToCamelCase" value="true"/>
<!-- 显式的开启全局缓存-->
<setting name="cacheEnabled" value="true"/>
</settings>
2.在要使用二级缓存的Mapper.xml中开启
<cache/>
也可以加入一些配置参数:
<cache eviction="FIFO"
flushInterval="60000"
size="512"
readOnly="true"/>
3.测试:
1. 问题:
java.io.NotSerializableException
我们将实体类序列化即可
小结:
-
只要开启了二级缓存,在同一个Mapper下就有效
-
所有的数据都会先放在一级缓存中;
-
只有当会话提交,或者关闭的时候,才会提交到二级缓存中!
5、缓存原理
6、自定义缓存 - ehcache
ehcache是一种广泛使用的开源java分布式缓存,主要面向通用缓存
1.先导包
<!-- https://mvnrepository.com/artifact/org.mybatis.caches/mybatis-ehcache -->
<dependency>
<groupId>org.mybatis.caches</groupId>
<artifactId>mybatis-ehcache</artifactId>
<version>1.1.0</version>
</dependency>
2.在mapper中指定使用我们的ehcache缓存实现
<cache type="org.mybatis.caches.ehcache.EhcacheCache"/>
3.添加配置文件:
ehcache.xml
<?xml version="1.0" encoding="UTF-8" ?>
<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>