<select id="selectUsersByProperty" resultType="users"> select * from users where 1=1 <if test="userid != 0"> and userid = #{userid} </if> </select>
<select id="selectUsersByChoose" resultType="users"> select * from users where 1=1 <choose> <when test="username != null and usersex!= ''"> and username=#{username} </when> <otherwise> and userid=1 </otherwise> </choose> </select>
// 如果判断条件不为空则自动添加where关键字,并且会自动去掉第一个条件前面的and或or <select id="selectUsersByPropertyWhere" resultType="users"> select * from users <where> <if test="userid != 0"> and userid = #{userid} </if> <if test="username != null and username != ''"> and username = #{username} </if> </where> </select>
// 允许在表达式外创建一个变量,并可以将其绑定到当前的SQL语句中,一般用于模糊查询 <select id="selectUsersByLikeName" resultType="users"> <bind name="likeName" value"'%'+name+'%'"/> select * from users where username like #{likeName} </select>
// 自动去掉最后一个if语句的多余的逗号 <update id="usersUpdate"> update users <set> <if test="username != null and username != ''"> username = #{username}, </if> <if test="usersex != null and usersex != ''"> usersex = #{usersex}, </if> </set> where userid = #{userid} </update>
<select id="selectUsersByIdUseCollection" resultType="users"> select * from users where userid in <foreach collection="collection" item="userid" open="(" separator="," close=")"> #{userid} </foreach> </select>
<select id="selectUsersByIdUserCollection" resultType="users"> select * from users where userid in <foreach collection="collection" item="userid" open="(" separator="," close=")"> #{userid} </foreach> </select>
<select id="selectUsersByIdUseArray" resultType="users"> select * from users where userid in <foreach collection="array" item="userid" open="(" separator="," close=")"> #{userid} </foreach> </select>
<select id="selectUsersCount" resultType="int"> select count(*) from users where <foreach collection="suibian" separator="and" item="value" index="key"> ${key} = #{value} </foreach> </select>
<insert id="insertUsersBatch"> insert into users values <foreach collection="collection" item="user" separator=","> (default, #{user.username}, #{user.usersex}) </foreach> </insert>
Mybatis会将相同查询条件的SQL语句的查询结果存储在内存或者某种缓存介质当中,当下次遇到相同的查询SQL时候不在执行该SQL,
而是直接从缓存中获取结果,减少服务器的压力,尤其是在查询越多、缓存命中率越高的情况下,使用缓存对性能的提高明显。
如何判断两次查询是完全相同的查询?
mybatis认为,对于两次查询,如果以下条件都完全一样,那么就认为它们是完全相同的两次查询:
mybatis的二级缓存是application级别的缓存,它可以提高对数据库查询的效率,以提高应用的性能。。
二级缓存是sqlSessionFactory上的缓存,可以是由一个SqlSessionFactory创建的不同的SqlSession之间共享缓存数据。
SqlSession在执行commit()或者close()的时候将数据放入到二级缓存。
1. 在映射配置文件中添加<cache/> 2. JavaBean对象必须实现序列化接口