Mybatis
一、概述
1.Mybatis是什么?
MyBatis 是一款优秀的持久层框架,一个半 ORM(对象关系映射)框架
2.ORM是什么?
ORM(Object Relational Mapping),对象关系映射
是一种为了解决关系型数据库数据与简单Java对象(POJO)的映射关系的技术。
简单的说,ORM是通过使用描述对象和数据库之间映射的元数据,
将程序中的对象自动持久化到关系型数据库中。
半自动ORM:在查询关联对象或关联集合对象时,需要手动编写sql来完成(Mybatis)
全自动的ORM:查询关联对象或者关联集合对象时,可以根据对象关系模型直接获取(Hibernate)
二、快速入门
1.导入依赖的jar包
<dependencies>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.10</version>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.4.6</version>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.12</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.10</version>
<scope>test</scope>
</dependency>
</dependencies>
2.创建一个pojo类
3.创建Dao层接口
public interface IEmploy {
public UserMy getUserId(Integer id);
}
4.编写mapper映射文件(编写SQL)
<select resultType="com.xinzhi.mybatis.dao.IEmploy" id="getUserId">
select id ,name ,age ,skill,password from user whereid = #{id}
</select>
resultType 返回值类型
parameterType 参数类型
id 接口方法名
#{ } 表示占位符 ‘ ? ’,传入参数
5.编写数据源properties文件
db.url=jdbc:mysql://localhost:3306/mybatis?characterEncoding=utf8
db.user=root
db.password=root
db.driver=com.mysql.jdbc.Driver
6.编写全局配置文件(主要是配置数据源信息)
<configuration>
<!-- 配置文件信息 -->
<properties resource="properties/db.properties"></properties>
<environments default="development">
<environment id="development">
<transactionManager type="JDBC"/>
<dataSource type="POOLED">
<!-- 从配置文件中加载属性 -->
<property name="driver" value="${db.driver}"/>
<property name="url" value="${db.url}"/>
<property name="username" value="${db.user}"/>
<property name="password" value="${db.password}"/>
</dataSource>
</environment>
</environments>
<mappers>
<!-- 加载前面编写的SQL语句的文件 -->
<mapper resource="StudentMapper.xml"/>
</mappers>
</configuration>
7.测试
三、MyBatis 映射文件
1.参数传递
1.1.参数传递的方式
@Param
作用:用注解来简化xml配置的时候(比如Mybatis的Mapper.xml中的sql参数引入)@Param注解的作用是给参数命名,参数命名后就能根据名字得到参数值,正确的将参数传入sql语句中(一般通过#{}的方式,${}会有sql注入的问题)
例:public void a(@Param(“id”)int id,@Param(”name“) String name);
1.2.参数的获取方式
-
#{key}:获取参数的值,预编译到 SQL 中。安全。
-
${key}:获取参数的值,拼接到 SQL 中。有 SQL 注入问题.ORDER BY ${name}
2.多表查询
一对多、一的一时,集合属性用collection标签
多对一时是association标签
其中ofType属性是类的全路径(多对一时是javaType属性),在collection标签内添加result子标签来描述集合存储的类的属性和列名的映射关系
resultMap 自定义映射
-
自定义 resultMap,实现高级结果集映射
-
id :用于完成主键值的映射
column:数据库的列名 property:列结果对应的java属性
-
result :用于完成普通列的映射
-
association :定义关联的对象分装规则(多对一,一对一)
javaType:是一个java类的全类名
-
collection : 复杂类型的集(一对多)
association,例:
<select id="getEmployeeAndDeptStep" resultMap="myEmpAndDeptStep">
select id, last_name, email,gender,d_id from tbl_employee where id =#{id}
</select>
<resultMap type="com.atguigu.mybatis.beans.Employee" id="myEmpAndDeptStep">
<id column="id" property="id" />
<result column="last_name" property="lastName"/>
<result column="email" property="email"/>
<result column="gender" property="gender"/>
<association property="dept" select="com.atguigu.mybatis.dao.DepartmentMapper.getDeptById" column="d_id" fetchType="eager">
</association>
</resultMap>
四、动态sql
动态 SQL 是 MyBatis 强大特性之一。极大的简化我们拼装 SQL 的操作
动态sql的标签
1.if where
-
If 用于完成简单的判断.
-
Where 用于解决 SQL 语句中 where 关键字以及条件中第一个 and 或者 or 的问题
2.trim
- Trim 可以在条件判断完的 SQL 语句前后 添加或者去掉指定的字符
prefix: 添加前缀
prefixOverrides: 去掉前缀
suffix: 添加后缀
suffixOverrides: 去掉后缀
3.set
- set 主要是用于解决修改操作中 SQL 语句中可能多出逗号的问题
4.choose(when、otherwise)
- choose 主要是用于分支判断,类似于 java 中的 switch case,只会满足所有分支中的一个
5.foreach
-
foreach 主要用户循环迭代
collection: 要迭代的集合
item: 当前从集合中迭代出的元素
open: 开始字符
close:结束字符
separator: 元素与元素之间的分隔符
index:
迭代的是 List 集合: index 表示的当前元素的下标 迭代的 Map 集合: index 表示的当前元素的 key
6.sql
- sql 标签是用于抽取可重用的 sql 片段,将相同的,使用频繁的 SQL 片段抽取出来,单独定义,方便多次引用
五、spring整合MyBatis
1.步骤
1.1.导入相关jar包
// junit
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
</dependency>
// mybatis
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.5.2</version>
</dependency>
// mysql-connector-java
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.47</version>
</dependency>
// spring相关
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>5.1.10.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>5.1.10.RELEASE</version>
</dependency>
// aspectJ AOP 织入器
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>1.9.4</version>
</dependency>
// mybatis-spring整合包 【重点】
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>2.0.2</version>
</dependency>
1.2、编写配置文件
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:p="http://www.springframework.org/schema/p"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.5.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd">
<!-- <context:component-scan base-package="cn.service"/> -->
<context:component-scan base-package="cn.xinzhi.dao, cn.xinzhi.service.impl"/>
<!-- 读取数据库配置文件 -->
<context:property-placeholder location="classpath:database.properties"/>
<!-- JNDI获取数据源(使用dbcp连接池) -->
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close" scope="singleton">
<property name="driverClassName" value="${driver}" />
<property name="url" value="${url}" />
<property name="username" value="${user}" />
<property name="password" value="${password}" />
<property name="initialSize" value="${initialSize}"/>
<property name="maxActive" value="${maxActive}"/>
<property name="maxIdle" value="${maxIdle}"/>
<property name="minIdle" value="${minIdle}"/>
<property name="maxWait" value="${maxWait}"/>
<property name="removeAbandonedTimeout" value="${removeAbandonedTimeout}"/>
<property name="removeAbandoned" value="${removeAbandoned}"/>
<!-- sql 心跳 -->
<property name= "testWhileIdle" value="true"/>
<property name= "testOnBorrow" value="false"/>
<property name= "testOnReturn" value="false"/>
<property name= "validationQuery" value="select 1"/>
<property name= "timeBetweenEvictionRunsMillis" value="60000"/>
<property name= "numTestsPerEvictionRun" value="${maxActive}"/>
</bean>
<!-- 事务管理 -->
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource"/>
</bean>
<!-- 配置mybitas SqlSessionFactoryBean-->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource"/>
<property name="mapperLocations" value="classpath:cn/xinzhi/dao/*.xml"></property>
<property name="typeAliasesPackage" value="cn.xinzhi.entity"></property>
</bean>
<!-- AOP 事务处理 开始 -->
<aop:config proxy-target-class="true">
<aop:pointcut expression="execution(* cn.xinzhi.service.impl..*(..))" id="transService"/>
<aop:advisor pointcut-ref="transService" advice-ref="txAdvice" />
</aop:config>
<tx:advice id="txAdvice" transaction-manager="transactionManager">
<tx:attributes>
<tx:method name="add*" propagation="REQUIRED" rollback-for="Exception" />
<tx:method name="set*" propagation="REQUIRED" rollback-for="Exception" />
<tx:method name="update*" propagation="REQUIRED" rollback-for="Exception" />
<tx:method name="change*" propagation="REQUIRED" rollback-for="Exception" />
<tx:method name="del*" propagation="REQUIRED" rollback-for="Exception" />
<tx:method name="get*" propagation="REQUIRED" rollback-for="Exception" />
<tx:method name="search*" propagation="REQUIRED" rollback-for="Exception" />
</tx:attributes>
</tx:advice>
<!-- AOP 事务处理 结束 -->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="basePackage" value="cn.xinzhi.dao" />
<property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"></property>
</bean>
</beans>
1.3、编写数据源properties文件
driver=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/mybatis?useUnicode=true&characterEncoding=utf-8
user=root
password=root
minIdle=45
maxIdle=50
initialSize=5
maxActive=100
maxWait=100
removeAbandonedTimeout=180
removeAbandoned=true