mybatis查询接收结果集
-
一条,实体类对象或集合接收
-
多条,集合接收;单条TooManyResultsException
-
mybatis设置了默认类型别名 resulttype中可以使用
-
返回map,resulttype=map
-
直接将数据转换为字段和值的键值对,返回给前端就是一个json对象
-
多条map:①List<Map>接收 ②@MapKey("设置唯一id"),用map接收 ③map数组接收(待验证)
-
-
特殊处理
-
模糊查询 “%”#{}"%"
-
批量删除 ${ids}
-
动态设置表名(分库分表用) ${tableName}
-
获取自增主键 useGeneratedKeys="true" KeyProperties="id" ,执行后,主键设置到对象中
-
-
ResultMap自定义映射
-
id属性唯一标识,type属性设置映射关系中的实体类类型
-
id标签映射主键值,result标签映射其他属性值:<id property="eid" column="id">
-
多对一处理(User Dept)
-
级联属性 property = dept.did column=did
-
association标签:两种
-
使用property = dept javaType ;子标签id、result
-
关联查询:使用property=dept select="DeptMapper.xml的namespace.SQLID column="did"(column可看作下一个查询的条件)
-
-
association第二种方法关联的对象可以延迟加载.在配置文件配置,开启后fetchType属性动手控制效果. lazy(默认)、eager
-
-
一对多处理collection
-
属性 property="users"(属性名) ofType="Emp"(表示集合中存储的类型)
-
关联查询
-
-
动态SQL
-
使用场景:多条件拼接
-
if标签
select * from sys_user where 1=1 <if test="username !=null and username != ''"> and username = #{username} </if>
-
where标签:只能去掉前面的and
select * from sys_user <where> <if test="username !=null and username != ''"> and username = #{username} </if> </where>
-
trim标签:标签中有内容时生效,无内容时没有效果
prefix将trim中内容前面添加指定内容 prefixOverrides 将trim标签中内容前面去掉指定内容 select * from sys_user <trim prefix='where' prefixOverrides='and|or'> <if test="username !=null and username != ''"> and username = #{username} </if> </trim>
-
choose、when、otherwise相当于if...else if....else :
-
choose包裹 多个when和一个otherwise
-
-
foreach标签
delete from sys_user where uid in <foreach collection="uids" item="uid" separator="," open="(",close=”)“> #{uid} </foreach>
-
sql标签:sql片段
<sql id="userColumns">uid,username,password</sql> <select id ="xxx" resultType="User"> select <include refid="userColumns"></include> from sys_user </select>
MyBatis缓存
-
一级缓存(默认开启)
-
SqlSession级别的,通过同一个sqlsession查询的数据会被缓存
-
失效情况
-
两次查询条件不同
-
两次查询期间执行了任何增删改
-
两次查询期间手动清空了缓存 clearCache().
-
-
-
二级缓存
-
SqlSessionFactory级别,通过同一个sqlSessionFactory生成的sqlsession查询的数据会被缓存
-
开启满足以下条件:
-
核心配置文件中cacheEnabled="true",默认为true,不需要设置。
-
在映射文件中设置标签<cache/>,标签中type属性可以设置二级缓存使用第三方框架缓存
-
必须在sqlsession关闭或提交之后才会保存到二级缓存,否则在一级缓存。
-
查询的数据所转换的实体类类型必须实现序列化的接口
-
-
失效:进行了增删改,一二级都失效。
-
-
二级缓存相关配置
-
eviction属性:缓存回收策略,默认是LRU
-
LRU(Least Recently Used)最近最少使用,
-
FIFO(First in First out) 先进先出
-
SOFT 软引用,移除基于垃圾回收器状态的软引用规则的对象
-
WEAK 弱引用,更积极地移除基于垃圾收集器状态和弱引用规则的对象
-
-
flushInterval属性:刷新间隔,单位毫秒
-
默认情况是不设置,也就是没有刷新间隔,缓存仅仅调用语句时刷新
-
-
size属性:引用数目,正整数
-
代表缓存最多可以存储多少个对象,太大容易导致内存溢出
-
-
readOnly属性:只读,true/false
-
只读缓存,会给所有调用者返回缓存对象的相同实例,这些对象不能被修改,性能优
-
false,读写缓存,会返回缓存对象的拷贝(通过序列化),安全但性能差一些
-
-
-
缓存查询顺序:先查询二级缓存,未命中查询一级缓存,未命中查询数据库。sqlsession关闭之后,一级缓存的数据会进入二级缓存。