Mybatis
1、入门
安装
要使用 MyBatis, 只需将 mybatis-x.x.x.jar 文件置于类路径(classpath)中即可。
如果使用 idea中Maven 来构建项目,则需将下面的依赖代码置于 pom.xml 文件中:
<?xml version="1.0" encoding="UTF-8"?>
<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>MyBatisBei</artifactId>
<version>1.0-SNAPSHOT</version>
<!--导入依赖-->
<dependencies>
<!--MyBatis-->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.5.7</version>
</dependency>
<!--Mysql-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.47</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
<?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>
<typeAliases>
<package name="com.entity"/>
</typeAliases>
<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/Kmdb"/>
<property name="username" value="root"/>
<property name="password" value="root"/>
</dataSource>
</environment>
</environments>
<mappers>
<mapper resource="com/dao/TimeDataMapper.xml"/>
</mappers>
</configuration>
2、简介
3、CRUD
1、万能的Map
假设,我们的实体类,或数据库中的表,字段或者参数过多时,我们应该考虑使用Map!
//新增时间数据
int setTimeData2(Map map);
//新增-Map
public void insert2(){
SqlSession sqlSession=MybatisUtils.getSqlseesion();
TimeDataMapper timeDataMapper=sqlSession.getMapper(TimeDataMapper.class);
Map<String,Object> map=new HashMap<String, Object>();
map.put("type","粉丝数");
map.put("id",5002);
timeDataMapper.setTimeData2(map);
sqlSession.commit();//提交事务
//关闭Sqlsession
MybatisUtils.closeSqlsession(sqlSession);
}
<!--新增2-Map-->
<insert id="setTimeData2" parameterType="map">
insert into timedata values(default,#{type},default,#{id})
</insert>
Map传递参数,sql直接去key即可!
多个参数用Map,或者注解
2、模糊查询
1、在代码传参时加%
List<TimeData> timeData= timeDataMapper.getUser2("%作%");
2、在sql拼接
<!--根据类型模糊查询-->
<select id="getUser2" resultType="com.entity.TimeData">
select * from timedata where dataType like "%"#{type}"%"
</select>
4、配置解析
1、核心配置文件
MyBatis 的配置文件包含了会深深影响 MyBatis 行为的设置和属性信息。 配置文档的顶层结构如下:
configuration(配置)
properties(属性)
settings(设置)
typeAliases(类型别名)
typeHandlers(类型处理器)
objectFactory(对象工厂)
plugins(插件)
environments(环境配置)
environment(环境变量)
transactionManager(事务管理器)
dataSource(数据源)
databaseIdProvider(数据库厂商标识)
mappers(映射器)
2、环境配置(environments)
不过要记住:尽管可以配置多个环境,但每个 SqlSessionFactory 实例只能选择一种环境。
学会使用多套配置环境!
Mybatis默认的事务管理器是JDBC,连接池:POOLED
3、属性(properties)
我们可以通过properties来实现引用配置文件。
这些属性可以在外部进行配置,并可以进行动态替换。你既可以在典型的 Java 属性文件中配置这些属性,也可以在 properties 元素的子元素中设置。【db.properties】
编写一个配置文件
driver=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/Kmdb
username=root
在核心配置文件中引入
<!--引入外部配置文件-->
<properties resource="db.properties">
<property name="password" value="root"/>
</properties>
- 可以直接引入外部文件
- 可以在其中增加一些属性配置
- 如果两个文件有同一个字段优先使用外部配置文件!因为会先运行内部配置文件,再运行外部配置文件,所以内部配置文件会被外部配置文件覆盖!
4、类型别名(typeAliases)
-
类型别名可为 Java 类型设置一个缩写名字。
<!--别名设置--> <typeAliases> <!--给实体起类别名--> <typeAlias type="com.pojo.TimeData" alias="timedata"/> </typeAliases>
-
也可以指定一个包名,MyBatis 会在包名下面搜索需要的 Java Bean,比如:
<!--别名设置--> <typeAliases> <!--指定包的别名--> <package name="com.pojo"/> </typeAliases>
-
扫描整个包,他的默认别名就是每个实体类的类名,首字母小写!
-
在实体类比较少的情况下使用第一种方式
-
如果实体类十分多建议使用第二种
-
第一种可以DIY别名(自定义别名),第二种则不行,如果非要改需要再实体类增加注解
@Alias("hello") public class TimeData {}
-
5、设置(settings)
这是 MyBatis 中极为重要的调整设置,它们会改变 MyBatis 的运行时行为。
6、映射器(mappers)
方式一:直接绑定xml【推荐使用】
<!--设置映射XML文件-->
<mappers>
<mapper resource="com/dao/TimeDataMapper.xml"/>
</mappers>
方式二:使用class文件绑定注册
<!--设置映射XML文件-->
<mappers>
<mapper class="com.dao.TimeDataMapper"/>
</mappers>
注意点:
- 接口和他的Mapper配置文件必须同名!
- 接口和他的Mapper配置文件必须在同一个包下!
方式三:使用扫描包进行注入绑定
<!--设置映射XML文件-->
<mappers>
<!--扫描包-->
<package name="com.dao"/>
</mappers>
注意点:
- 接口和他的Mapper配置文件必须同名!
- 接口和他的Mapper配置文件必须在同一个包下!
7、其他配置
8、作用域(Scope)和生命周期
作用域和生命周期类别是至关重要的,因为错误的使用会导致非常严重的并发问题。
SqlsessionFactoryBuilder:
- 一旦创建了 SqlSessionFactory,就不再需要它了。
- 局部变量
SqlsessionFactory:
- 说白了可以想象成:数据库连接池
- SqlsessionFactory一旦被创建就应该在应用的运行期间一直存在,没有任何理由丢弃它或重新创建另一个实例。
- 因此 SqlSessionFactory 的最佳作用域是应用作用域。
- 最简单的就是使用单例模式或者静态单例模式。
Sqlsession
- 链接到连接池的请求!
- SqlSession 的实例不是线程安全的,因此是不能被共享的,所以它的最佳的作用域是请求或方法作用域。
- 用完之后需要赶紧关闭!否则资源被占用。
5、解决属性名和字段名不一致的问题
1、问题
数据库表的字段
实体类的属性
private Long timeDataId;//时间数据id
private String dataType;//数据类型
private String createTime;//插入日期
private Long userIds;//用户id
测试查询,发现userIds为null
解决方法:
- 起别名
2、resultMap
结果集映射
- 元素是 MyBatis 中最重要最强大的元素。
- ResultMap 的设计思想是,对简单的语句做到零配置,对于复杂一点的语句,只需要描述语句之间的关系就行了。
<select id="selectUsers" resultType="map">
select id, username, hashedPassword
from some_table
where id = #{id}
</select>
上述语句只是简单地将所有的列映射到 HashMap
的键上,这由 resultType
属性指定。虽然在大部分情况下都够用,但是 HashMap 并不是一个很好的领域模型。你的程序更可能会使用 JavaBean 或 POJO(Plain Old Java Objects,普通老式 Java 对象)作为领域模型。MyBatis 对两者都提供了支持。
ResultMap
的优秀之处——你完全可以不用显式地配置它们。 虽然上面的例子不用显式配置ResultMap
。- 如果这个世界总是这么简单就好了。
6、日志
6.1、日志工厂
如果一个数据库操作,出现了异常,我们需要排错。日志就是最好的助手!
曾经:sout、debug
现在:日志工厂!
- SLF4J
- LOG4J
- LOG4J2
- JDK_LOGGING
- COMMONS_LOGGING
- STDOUT_LOGGING
- NO_LOGGING
在Mybatis具体使用哪个日志实现,在设置中设定!
STDOUT_LOGGING标准日志输出
6.2、Log4j
什么是Log4j?
- Log4j是Apache的一个开源项目,通过使用Log4j,我们可以控制日志信息输送的目的地是控制台、文件、GUI组件,甚至是套接口服务器、NT的事件记录器、UNIX Syslog守护进程等
- 我们也可以控制每一条日志的输出格式
- 通过定义每一条日志信息的级别
- 通过一个配置文件来灵活地进行配置,而不需要修改应用的代码。
1、导入Log4j的包
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.17</version>
</dependency>
2、log4j.properties
log4j.rootLogger=DEBUG,CONSOLE,file
#log4j.rootLogger=ERROR,ROLLING_FILE
######################################################################################
# Console Appender \u65E5\u5FD7\u5728\u63A7\u5236\u8F93\u51FA\u914D\u7F6E
######################################################################################
log4j.appender.CONSOLE=org.apache.log4j.ConsoleAppender
log4j.appender.Threshold=error
log4j.appender.CONSOLE.Target=System.out
log4j.appender.CONSOLE.layout=org.apache.log4j.PatternLayout
log4j.appender.CONSOLE.layout.ConversionPattern= [%p] %d %c - %m%n
######################################################################################
# DailyRolling File \u6BCF\u5929\u4EA7\u751F\u4E00\u4E2A\u65E5\u5FD7\u6587\u4EF6\uFF0C\u6587\u4EF6\u540D\u683C\u5F0F:log2009-09-11
######################################################################################
log4j.appender.file=org.apache.log4j.DailyRollingFileAppender
log4j.appender.file.DatePattern=yyyy-MM-dd
log4j.appender.file.File=log.log
log4j.appender.file.Append=true
log4j.appender.file.Threshold=error
log4j.appender.file.layout=org.apache.log4j.PatternLayout
log4j.appender.file.layout.ConversionPattern=%d{yyyy-M-d HH:mm:ss}%x[%5p](%F:%L) %m%n
log4j.logger.com.opensymphony.xwork2=error
3、配置log4j为日志的实现
<settings>
<setting name="logImpl" value="LOG4J"/>
</settings>
7、分页
为什么要使用分页?
- 减少数据的处理量
7.1使用Limit分页
select * from table limit 0 10
使用Mybatis实现分页,核心SQL
-
接口
//分页 List<TimeData> getDataTimeLimit(Map<String,Integer> map);
-
Mapper.XML
<!--分页实现查询--> <select id="getDataTimeLimit" resultType="hello" parameterType="map"> select * from timedata limit #{starIndex},#{pageSize} </select>
-
测试
@Test public void getDataTimeLimit(){ SqlSession sqlseesion = MybatisUtils.getSqlseesion(); TimeDataMapper mapper = sqlseesion.getMapper(TimeDataMapper.class); HashMap<String, Integer> map = new HashMap<String, Integer>(); map.put("starIndex",0); map.put("pageSize",2); List<TimeData> dataTimeLimit = mapper.getDataTimeLimit(map); for (TimeData timeData : dataTimeLimit) { System.out.println(timeData.getCreateTime()); } MybatisUtils.closeSqlsession(sqlseesion); }
8、使用注解开发
8.1、使用注解开发
-
注解在接口上实现
@Select("select * from t_sys_user where id=#{id}") List<SysUser> getUserByRealName(@Param("id") Long id);
-
需要在核心配置文件中绑定接口
<mappers> <!--绑定接口--> <mapper class="demo.mapper.SysUserMapper"/> </mappers>
-
测试
9、多对一处理
- 多个学生,对应一个老师
- 对于学生这边而言,关联…多个学生,关联一个老师【多对一】
- 对于老师而言,集合,一个老师,有很多学生【一对多】
按照查询嵌套处理
<select id="getOneLit" resultMap="onetwo">
SELECT* FROM ONE
</select>
<resultMap id="onetwo" type="one">
<id property="id" column="id"/>
<association property="two" column="twoId" javaType="Two" select="ii"/>
</resultMap>
<select id="ii" resultType="Two">
select * from two where id=#{id}
</select>
按结果嵌套处理
<!--按照结果嵌套处理-->
<select id="getOneLit2" resultMap="onetwo2">
SELECT o.`id`,oname,tname
FROM ONE o,two t
WHERE o.`twoId`=t.`id`
</select>
<resultMap id="onetwo2" type="one">
<result property="id" column="id"/>
<result property="oname" column="oname"/>
<association property="two" javaType="Two">
<result property="tname" column="tname"/>
</association>
</resultMap>
10、动态SQL
什么是动态SQL:动态SQL就是指根据不同的条件生成不同的SQL
IF
<select id="selectList" resultMap="userrole">
select u.*,r.id rid,r.roleName from t_sys_user u,t_sys_role r
where u.roleId=r.id
<if test="roleId!=null">
and u.roleId=#{roleId}
</if>
<if test="realName!=null or realNamem!=''">
and u.realName like concat('%',#{realName},'%')
</if>
</select>
<resultMap id="userrole" type="北" autoMapping="true">
<id property="id" column="id"/>
<association property="sysRole" javaType="sysrole">
<id property="id" column="rid"/>
<result property="roleName" column="roleName"/>
</association>
</resultMap>
where
<select id="getUSer" resultType="北">
select * from t_sys_user
<where>
<if test="roleId!=null">
and roleId=#{roleId}
</if>
<if test="realName!=null and realName!=''">
or realName like concat('%',#{realName},'%')
</if>
<if test="realName!=null and realName!=''">
and 1=1
</if>
</where>
</select>
choose,when,otherwise
<select id="getUSer2" resultType="北">
select * from t_sys_user
<where>
<choose>
<when test="roleId!=null">
and roleId=#{roleId}
</when>
<when test="realName!=null and realName!=''">
and realName like concat('%',#{realName},'%')
</when>
<otherwise>
and 1=1
</otherwise>
</choose>
</where>
</select>
所谓的动态SQL,本质还是SQL语句,只是我们可以在SQL层面,去执行一个逻辑代码
SQL片段
有的时候,我们可能将一些公告部分抽取出来用来备用,方便复用!
- 使用SQL标签将公共部分提取出来
- 在需要使用的地方用Include标签引用即可
注意事项:
- 最好基于单表来定义SQL片段!
- 不要存在where标签
Foreach
动态SQL就是在凭借SQL语句,我们只要保证SQL的正确性,按照SQL都是格式,去排列组合就可以了
建议:
- 先在Mysql中写出完整的SQL语句,在对应的去修改成为我们的动态SQL实现通用即可!