SQL映射器mapper
MyBatis的映射器mapper基于代理模式实现,即CRUD的接口类无需实现类。通过mybatis内置的代理对象进行具体实现。
在进行mapper.xml的配置中,namespace直接写该接口的相对路径。
<mapper namespace="cn.itsource.mybatis.dao.IUserDao">
<select id="queryOne" parameterType="long" resultType="User">
select * from user where id = #{id}
</select>
测试代码如下:
@Test
public void testQueryOne()throws Exception{
//拿到IUserDao的代理对象
IUserDao mapper = MyBatisUtil.getSqlSession().getMapper(IUserDao.class);
System.out.println(mapper.queryOne(1L));
System.out.println(mapper.getClass());
}
测试结果如下:
User{id=7, name='222', pwd='222', age=17}
class com.sun.proxy.$Proxy4
高级结果映射ResultMap
resultMap包含以上参数,其中id,result是最常用最基本的参数。
id属性负责映射pojo类与表的id,result用于映射pojo中无外键关联的属性与表头。
association用于映射外键关联
高级结果映射的关联查询方式包括嵌套查询和嵌套结果
嵌套结果:通过外连接查询,直接得到想要的数据结果。只发送一条sql语句。代码如下:
<resultMap id="UserMap" type="User">
<!--column是库表中的列名,property是对应的pojo的属性 -->
<id column="id" property="id"/>
<result column="username" property="username"/>
<result column="password" property="password"/>
<!--外键关联 javaType表示该外键的类属性-->
<association property="department" javaType="Department" column="dept_id">
<id column="d_id" property="id"/>
<result column="d_name" property="name"/>
</association>
</resultMap>
嵌套查询: 会有1+n的问题,会发送一条sql语句用于查询主表,然后会发送n条sql语句用于加载查询关联的表的信息。mapper中的代码如下:
<!--嵌套查询-->
<select id="queryAllByManySql" resultMap="anotherUserMap">
select u.id,u.username,u.password,u.dept_id from user u
</select>
<resultMap id="anotherUserMap" type="User">
<id column="id" property="id"/>
<result column="username" property="username"/>
<result column="password" property="password"/>
<association property="department" javaType="Department" select="selectDept" column="dept_id">
<id column="d_id" property="id"/>
<result column="d_name" property="name"/>
</association>
</resultMap>
<select id="selectDept" parameterType="long" resultType="Department">
select * from department d where id = #{id}
</select>
MyBatis缓存
一级缓存:存在于SqlSession中,对象被销毁自动消失。一级缓存是默认存在的。
二级缓存:存在于SqlSessionFactory中 ,需要自己手动配置 ,在想要使用二级缓存的maper.xml中配置即可。
在查询的过程中,第一次查询都直接向数据库发送请求,后面就直接先访问一级缓存,如果一级缓存中不存在,在配置二级缓存的情况下会访问二级缓存。再后才会向数据库再次发送请求