1:原理:ORM模型
2:核心对象
SqlSession <–SqlSessionFactory【open session()方法】 <–SqlSessionFactory builder【bulid()方法】
SqlSession -->select,insert,update,delete
3:配置文件
3.1环境:
事务:
数据源
代码:
<configuration>
<!-- 1、环境 -->
<environments default="mysql">
<environment id="mysql">
<!--1.1事务管理 -->
<transactionManager type="JDBC"></transactionManager>
<!--1.2数据源(数据库) -->
<dataSource type="POOLED">
<property name="driver" value="com.mysql.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost:3306/mybatis?serverTimezone=UTC"/>
<property name="username" value="root"/>
<property name="password" value="123456"/>
</dataSource>
</environment>
</environments>
3.2映射文件–映射文件位置
<!-- 2、映射文件的位置 -->
<mappers>
<!-- class="类路径:mapper.customerMapper" -->
<mapper resource="mapper/orderMapper.xml"/>
<mapper resource="mapper/productMapper.xml"/>
</mappers>
</configuration>
4:映射文件
<select><update><insert><delete>
5:动态SQL
<if>.
…:多种条件选择,只要属性中的表达式为true,就会执行元素中的条件语句。
<choose>(when,otherwise)....
:单一选择,可以从多个选项中选择一个符合要求的去执行,
<where>:
元素会主动判断组合条件下拼装的SQL语句,只有元素中的条件成立后,才会拼接SQL语句中加入的where语句,否则将不会添加,即使where之后的内容有多余的“AND”或者“OR”,where元素也会自动把他们去除
<set>:
元素主要用于更新操作,其主要作用是在动态包含的sql语句前输出一个SET关键字,并将SQL语句中的最后一个多余的逗号去除。注意:在映射文件中使用和元素组合进行update语句动态SQL组装时,要确保传入的更新字段不能为空,不然会出现SQL语法错误。
<trim>:
元素是去除一些特殊的字符串。它的prefix属性代表的是语句的前缀(作用就是添加东西),它的prefixOverrides属性代表的是需要去除的那些特殊字符串。
<foreach>
元素对传入的集合进行遍历并进行了动态SQL组装,然后批量查询出对应条件的信息。
6:关联映射:
<resultMap>
:用来映射映射或对应复杂的属性与数据表之间的关系,id是用来对应主键和对象的属性。
<result>
:用来对应普通字段与对象的属性
1:1—`association
1.1.1 property:指定映射到的实体类属性,与表字段一一对应
1.1.2 column:指定表中对应的字段
1.1.3 javaType :指定映射到实体对象属性的类型
1.1.4 select:指定引入嵌套查询的子SQL语句,该属性用于关联映射中的嵌套查询。
例子:
<?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">
<mapper namespace="mapper.PersonMapper.xml">
<!-- namespace 包名+本文件全名 -->
<select id="findPersonById"
parameterType="Integer"
resultType="IdCardWithPersonResult">
<!-- resultType设置一个返回属性用于下面select属性的id -->
select * from t_person where id=#{id}
</select>
<resultMap type="Person" id="IdCardWithPersonResult">
<id property="id" column="id" />
<result property="name" column="name"/>
<result property="age" column="age"/>
<association property="card_id"
column="card_id"
javaType="po.idCard"
select="mapper.idCardMapper.findCodeById"/>
</resultMap>
</mapper>
1:n或者n:n---<collection>
例子:
<select id="findorderbyid2"
parameterType="Integer"
resultMap="OrderResult2">
select o.*,p.id as pid,p.name,p.price
from t_order o,t_product p,t_midder mi
where mi.order_id=o.id
and mi.product_id=p.id
and o.id=#{id}
</select>
<resultMap type="po.order" id="OrderResult2">
<id property="id" column="id" />
<result property="number" column="number" />
<collection property="productlist" ofType="po.product">
<id property="id" column="pid" />
<result property="name" column="name" />
<result property="price" column="price" />
</collection>
</resultMap>