IBatis(MyBatis)入门
mybatis前身是ibatis;
mybatis特点:
- 半自动化,需要自己写SQL语句,自己定义映射。设计灵活,有延迟加载,缓存,映射等;
- 对数据库的兼容性比hibernate差。移植性不好,但可编写灵活和高性能的SQL语句。
mybatids映射采用
<select id="getUserByid" resultType"类地址">
<!--映射-->
select pk_id id,
fxxx
xx
xx
from x
</select>
mybatis主配置文件
<?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>
<typeAliases>
<typeAlias type="com.wang.model.User" alias="user"/>
</typeAliases>
<environments default="test">
<environment id="test">
<transactionManager type="jdbc"></transactionManager>
<dataSource type="POOLED">
<property name="driver" value="com.mysql.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost:3306/hibernate"/>
<property name="username" value="root"/>
<property name="password" value="123456"/>
</dataSource>
</environment>
</environments>
<mappers>
<mapper resource="com/wang/batis/user.xml"/>
</mappers>
</configuration>
避免N+1Sql的现象
N+1 ,一般出现在1对多的情况下
当遍历 one 多个对象下的 many集合的时候,sql会在遍历many集合的时候再查一次one,这个sql是多余的。
解决方法1:
在一方配置的时候<colloction>
不要设置返回方式为resultMap,而是使用 column, select方法
然后在多方的时候,对应的select应该用联表查询,这样可避免上述多余sql问题
Mybatis映射
普通关系的映射,用result标签;
jdbc驱动不能执行多条sql
allowMultiQueries
<resultMap id="映射名" type="别名或者类权限定名">
<id property="属性名" column="表名"/>
<result property ="属性名" column="表名"/>
</resultMap>
一对多
这些map映射可以放在一个配置文件或者两个配置文件都可以。,文字中 many代表多方对象,one代表1方对象
一方配置
<!-- 一方的属性映射 -->
<resultMap id="一方映射名" type="别名或者类权限定名">
<id property="主键属性" column="表名"/>
<result property="name" column=""/>
<!--一方关联的多方集合属性的映射-->
<collection
property="集合属性名"
column="pk_id(当前表的pk_id传入到select里面,因为后面的参数select要接受一个参数)"
select="多方命名空间(namespace).
select Many By Fk_id">
</collection>
</resultMap>
多方配置
<!-- 多方的属性映射 -->
<resultMap id="多方映射名"
type="别名或者类权限定名">
<id property="主键属性名" column="表名"/>
<result property/>
<association
property ="one方属性名"
column="fk_one_ID"
select="select Many By fk_one_id"/>
</resultMap>
<!-- 获取多方对象的单个对象 -->
<select id="getManyObjectById"
resultMap="many">
select * from t_many where pk_id = #{id}
</select>
<!-- 获取一方某id下的多方对象 -->
<select id="select Many By Fk_one_id" resultMap="many">
select
*
from
t_many
where
fk_one_id = #{one_id};
</select>
多对多
<mapper namespace="manytomany">
<!-- 返回结果的映射,将user的属性组装 -->
<resultMap type="course" id="courseMap">
<id property="id" column="pk_id"/>
<result property="name" column="f_name"/>
<collection property="students" resultMap="studentMap"></collection>
</resultMap>
<resultMap type="student" id="studentMap">
<id property="id" column="sid"/>
<result property="name" column="sname"/>
<!-- <collection property="courses" resultMap="courseMap"></collection> -->
</resultMap>
<select id="getAllCourse" resultMap="courseMap">
select
s.pk_id as sid,
s.f_name as sname,
c.*
from t_student s left join t_course_stu cs on cs.pk_fk_sid = s.pk_id
left join t_course c on cs.pk_fk_cid = c.pk_id
</select>
</mapper>