入门
1.简单的sql语句可以使用java注解的形式
package org.mybatis.example;
public interface BlogMapper {
@Select("SELECT * FROM blog WHERE id = #{id}")
Blog selectBlog(int id);
}
2.SqlSession的线程是不安全的,因此是不能被共享的,所以它的最佳的作用域是请求或方法作用域。绝对不能将 SqlSession 实例的引用放在一个类的静态域,甚至一个类的实例变量也不行。也绝不能将 SqlSession 实例的引用放在任何类型的管理作用域中,比如 Servlet 架构中的 HttpSession。如果你现在正在使用一种 Web 框架,要考虑 SqlSession 放在一个和 HTTP 请求对象相似的作用域中。换句话说,每次收到的 HTTP 请求,就可以打开一个 SqlSession,返回一个响应,就关闭它。这个关闭操作是很重要的,你应该把这个关闭操作放到 finally 块中以确保每次都能执行关闭。下面的示例就是一个确保 SqlSession 关闭的标准模式:
SqlSession session = sqlSessionFactory.openSession();
try {
// do work
} finally {
session.close();
}
mapper.xml注意事项
1.使用'where'标签 可以自动去掉条件中的第一个and,举例:
<where>
<if test="userCustom!=null">
<if test="userCustom.sex!=null and userCustom.sex != '' ">
AND user.sex=#{userCustom.sex}
</if>
<if test="userCustom.username!=null and userCustom.username != '' ">
AND user.username LIKE '%${userCustom.username}%'
</if>
</if>
</where>
2.使用sql片段:
如果有部分甚至更多statement中包含了同样的sql片段,可以考虑将sql片段提取出来,用于简化xml。举例:
<sql id="sql_attention">
select
*
FROM
user_push_msg msg
...
ORDER BY
id DESC
</sql>
注意:在sql片段中不要包括 where
这样的提取和代码一样可以帮助我们写sql时逻辑更加清晰,而平时最常用的是:
<sql id="Base_Column_List">
id, user_id, title, content, push_id, type, add_time, isflag, pic_userid, isVip
</sql>
这样避免了我们每次写查询sql的时候填写字段名。
明天接着写,加油!