MybatisUtil工具类

  在实际开发中,我们可以编写一个MybatisUtil辅助类来进行对进行操作。

1)在静态初始化块中加载mybatis配置文件和StudentMapper.xml文件一次

2)使用ThreadLocal对象让当前线程与SqlSession对象绑定在一起

3)获取当前线程中的SqlSession对象,如果没有的话,从SqlSessionFactory对象中获取SqlSession对象

4)获取当前线程中的SqlSession对象,再将其关闭,释放其占用的资源

  1. /**
  2. * MyBatis工具类
  3. * @author AdminTC
  4. */
  5. public class MyBatisUtil {
  6. private static ThreadLocal<SqlSession> threadLocal = new ThreadLocal<SqlSession>();
  7. private static SqlSessionFactory sqlSessionFactory;
  8. static{
  9. try {
  10. Reader reader = Resources.getResourceAsReader("mybatis.xml");
  11. sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader);
  12. } catch (IOException e) {
  13. e.printStackTrace();
  14. throw new RuntimeException(e);
  15. }
  16. }
  17. private MyBatisUtil(){}
  18. public static SqlSession getSqlSession(){
  19. SqlSession sqlSession = threadLocal.get();
  20. if(sqlSession == null){
  21. sqlSession = sqlSessionFactory.openSession();
  22. threadLocal.set(sqlSession);
  23. }
  24. return sqlSession;
  25. }
  26. public static void closeSqlSession(){
  27. SqlSession sqlSession = threadLocal.get();
  28. if(sqlSession != null){
  29. sqlSession.close();
  30. threadLocal.remove();
  31. }
  32. }
  33. public static void main(String[] args) {
  34. Connection conn = MyBatisUtil.getSqlSession().getConnection();
  35. System.out.println(conn!=null?"连接成功":"连接失败");
  36. }
  37. }

MybatisUtil.java

  

动态SQL

  什么是动态SQL,如下图,当你不知道用户会选择多少个筛选条件的时候,你只有等待用户选择而动态地选择SQL查询条件。

  

动态SQL-选择

  加入IUserDao接口,注意因为与数据库互动需要,Dao接口一般要以类作为参数。

  1. package com.harry.dao;
  2.  
  3. import java.sql.SQLException;
  4. import java.util.List;
  5. import java.util.Set;
  6.  
  7. import com.harry.entity.User;
  8.  
  9. public interface IUserDao {
  10. public boolean doCreate(User entity) throws Exception;
  11.  
  12. public boolean doUpdate(User entity) throws Exception;
  13.  
  14. public boolean doRemove(Set<Integer> ids)throws Exception;
  15.  
  16. public User findById(Integer id)throws Exception;
  17.  
  18. public List<User> findAll() throws Exception;
  19.  
  20. public List<User> findAllSplite(String column, String keyword, Integer currentPage, Integer lineSize) throws Exception;
  21.  
  22. public Integer getAllCount(String column, String keyword) throws Exception;
  23. }

IUserDao

  书写UserDaoImpl,并在其后添加动态查询的查询方法dynaSQLwithSelect。

  1. package com.harry.dao.impl;
  2.  
  3. import java.util.LinkedHashMap;
  4. import java.util.List;
  5. import java.util.Map;
  6. import java.util.Set;
  7.  
  8. import org.apache.ibatis.session.SqlSession;
  9.  
  10. import com.harry.dao.IUserDao;
  11. import com.harry.entity.User;
  12. import com.harry.util.MybatisUtil;
  13.  
  14. public class UserDaoImpl implements IUserDao {
  15.  
  16. @Override
  17. public boolean doCreate(User entity) throws Exception {
  18. // TODO Auto-generated method stub
  19. return false;
  20. }
  21.  
  22. @Override
  23. public boolean doUpdate(User entity) throws Exception {
  24. // TODO Auto-generated method stub
  25. return false;
  26. }
  27.  
  28. @Override
  29. public boolean doRemove(Set<Integer> ids) throws Exception {
  30. // TODO Auto-generated method stub
  31. return false;
  32. }
  33.  
  34. @Override
  35. public User findById(Integer id) throws Exception {
  36. // TODO Auto-generated method stub
  37. return null;
  38. }
  39.  
  40. @Override
  41. public List<User> findAll() throws Exception {
  42. // TODO Auto-generated method stub
  43. return null;
  44. }
  45.  
  46. @Override
  47. public List<User> findAllSplite(String column, String keyword, Integer currentPage, Integer lineSize)
  48. throws Exception {
  49. // TODO Auto-generated method stub
  50. return null;
  51. }
  52.  
  53. @Override
  54. public Integer getAllCount(String column, String keyword) throws Exception {
  55. // TODO Auto-generated method stub
  56. return null;
  57. }
  58.  
  59. public List<User> dynaSQLwithSelect(String uname,Character usex) throws Exception{
  60. SqlSession sqlSession = MybatisUtil.getSqlSession();
  61. try{
  62. Map<String,Object> map = new LinkedHashMap<String, Object>();
  63. map.put("uname",uname);
  64. map.put("usex", usex);
  65. return sqlSession.selectList("dynaSQLwithSelect",map);
  66. }catch(Exception e){
  67. e.printStackTrace();
  68. sqlSession.rollback();
  69. throw e;
  70. }finally{
  71. sqlSession.commit();
  72. MybatisUtil.closeSqlSession();
  73. }
  74. }
  75.  
  76. }

UserDaoImpl

  在User.xml中配置相应的SQL方法映射。  

  1. <!-- map为调用该方法的外界传入 -->
  2. <select id="dynaSQLwithSelect" parameterType="map" resultType="com.harry.entity.User">
  3. select id,username,sex from user
  4. <where>
  5. <!-- 如果map中uname不为null,则在where后添加username = uname; -->
  6. <if test="uname!=null">
  7. and username=#{uname}
  8. </if>
  9. <!-- 如果map中usex不为null,则在where语句后添加 and sex = usex; -->
  10. <if test="usex!=null">
  11. and sex=#{usex}
  12. </if>
  13. </where>
  14. </select>

User.xml

  测试方法

  1. @Test
  2. public void testdynaSQLwithSelect() throws Exception {
  3. UserDaoImpl userDao = new UserDaoImpl();
  4. List<User> list = userDao.dynaSQLwithSelect("张飞", null);
  5. Iterator<User> iterator = list.iterator();
  6. while(iterator.hasNext()){
  7. System.out.println(iterator.next());
  8. }
  9. }

MybatisTest

  动态SQL增删改查基本相同,重点是Mybatis通过在配置文件中书写<where>语句来避免数据库SQL拼接。

动态SQL-更新 

  1. public boolean dynaSQLwithUpdate(Integer uid, String uname, String usex) throws Exception{
  2. //session应该在事务层进行开关,这里为了方便
  3. SqlSession sqlSession = MybatisUtil.getSqlSession();
  4. try{
  5. Map<String,Object> map = new LinkedHashMap<>();
  6. map.put("uid", uid);
  7. map.put("uname", uname);
  8. map.put("usex", usex);
  9. sqlSession.update("dynaSQLwithUpdate",map);
  10. return true;
  11. }catch(Exception e){
  12. e.printStackTrace();
  13. sqlSession.rollback();
  14. throw e;
  15. }finally{
  16. sqlSession.commit();
  17. MybatisUtil.closeSqlSession();
  18. }
  19. }

UserDaoImpl

  1. <update id="dynaSQLwithUpdate" parameterType="map">
  2. UPDATE user
  3. <set>
  4. <if test="uname!=null">
  5. username=#{user.username},
  6. </if>
  7. <if test="usex!=null">
  8. sex=#{usex},
  9. </if>
  10. </set>
  11. where id=#{uid}
  12. </update>

User.xml

动态SQL-删除

  1. public boolean dynaSQLwithDelete(Integer... ids) throws Exception{
  2. //session应该在事务层进行开关,这里为了方便
  3. SqlSession sqlSession = MybatisUtil.getSqlSession();
  4. try{
  5. Map<String, Object> map = new LinkedHashMap<>();
  6. map.put("ids", ids);
  7. sqlSession.delete("dynaSQLwithDelete",map);
  8. return true;
  9. }catch(Exception e){
  10. e.printStackTrace();
  11. sqlSession.rollback();
  12. throw e;
  13. }finally{
  14. sqlSession.commit();
  15. MybatisUtil.closeSqlSession();
  16. }
  17. }

UserDaoImpl

  1. <delete id="dynaSQLwithDelete" parameterType="map">
  2. DELETE FROM user WHERE id IN
  3. <!-- foreach 用来迭代数组元素 -->
  4. <!-- open表示开始符号 -->
  5. <!-- close表示结束符号 -->
  6. <!-- separator表示分隔符 -->
  7. <!-- item表示迭代的数组 -->
  8. <foreach collection="ids" open="(" close=")" separator="," item="id">
  9. #{id}
  10. </foreach>
  11. </delete>

User.xml

动态SQL- 插入

  1. public boolean dynaSQLwithInsert(User... users) throws Exception{
  2. //session应该在事务层进行开关,这里为了方便
  3. SqlSession sqlSession = MybatisUtil.getSqlSession();
  4. try{
  5. Map<String, Object> map = new LinkedHashMap<>();
  6. map.put("users", users);
  7. sqlSession.insert("dynaSQLwithInsert",map);
  8. return true;
  9. }catch(Exception e){
  10. e.printStackTrace();
  11. sqlSession.rollback();
  12. throw e;
  13. }finally{
  14. sqlSession.commit();
  15. MybatisUtil.closeSqlSession();
  16. }
  17. }

UserDaoImpl

  1. <insert id="dynaSQLwithInsert" parameterType="map" useGeneratedKeys="true" keyProperty="id">
  2. INSERT INTO user (username, birthday, sex, address) VALUES
  3. <foreach collection="users" item="user" separator=",">
  4. (#{user.username},#{user.birthday},#{user.sex},#{user.address})
  5. </foreach>
  6. </insert>
  7. </mapper>

User.xml

Mybatis-2源码

框架应用:Mybatis(二) - 动态SQL的更多相关文章

  1. 使用Mybatis实现动态SQL(二)

    使用Mybatis实现动态SQL 作者 : Stanley 罗昊 [转载请注明出处和署名,谢谢!] 写在前面:        *本章节适合有Mybatis基础者观看* 使用Mybatis实现动态SQL ...

  2. 9、SpringBoot+Mybatis整合------动态sql

    开发工具:STS 前言: mybatis框架中最具特色的便是sql语句中的自定义,而动态sql的使用又使整个框架更加灵活. 动态sql中的语法: where标签 if标签 trim标签 set标签 s ...

  3. MyBatis的动态SQL详解

    MyBatis的动态SQL是基于OGNL表达式的,它可以帮助我们方便的在SQL语句中实现某些逻辑,本文详解mybatis的动态sql,需要的朋友可以参考下 MyBatis 的一个强大的特性之一通常是它 ...

  4. mybatis中的.xml文件总结——mybatis的动态sql

    resultMap resultType可以指定pojo将查询结果映射为pojo,但需要pojo的属性名和sql查询的列名一致方可映射成功. 如果sql查询字段名和pojo的属性名不一致,可以通过re ...

  5. MyBatis的动态SQL详解-各种标签使用

    MyBatis的动态SQL是基于OGNL表达式的,它可以帮助我们方便的在SQL语句中实现某些逻辑. MyBatis中用于实现动态SQL的元素主要有: if choose(when,otherwise) ...

  6. Java-MyBatis:MyBatis 3 动态 SQL

    ylbtech-Java-MyBatis:MyBatis 3 动态 SQL 1.返回顶部 1. 动态 SQL MyBatis 的强大特性之一便是它的动态 SQL.如果你有使用 JDBC 或其它类似框架 ...

  7. 一分钟带你了解下MyBatis的动态SQL!

    MyBatis的强大特性之一便是它的动态SQL,以前拼接的时候需要注意的空格.列表最后的逗号等,现在都可以不用手动处理了,MyBatis采用功能强大的基于OGNL的表达式来实现,下面主要介绍下. 一. ...

  8. Mybatis中动态SQL语句中的parameterType不同数据类型的用法

    Mybatis中动态SQL语句中的parameterType不同数据类型的用法1. 简单数据类型,    此时#{id,jdbcType=INTEGER}中id可以取任意名字如#{a,jdbcType ...

  9. Mybatis解析动态sql原理分析

    前言 废话不多说,直接进入文章. 我们在使用mybatis的时候,会在xml中编写sql语句. 比如这段动态sql代码: <update id="update" parame ...

随机推荐

  1. Fatal error: Class 'LearningPHP1\mysqli' not found

    在php文件的头部使用了namespace 结果报错mysqli不在LearningPHP1中, 结论:如果定义了命名空间,在使用mysqli做连接的时候就要指明mysqli所在的命名空间. < ...

  2. Sass之Compass学习笔记

    compass Compass是Sass的工具库,就好像jQuery是js的库一样. sass有了compass的配合,就会更加事半功倍. Sass本身只是一个编译器,Compass在它的基础上,封装 ...

  3. zoj3778 Talented Chef

    As we all know, Coach Gao is a talented chef, because he is able to cook M dishes in the same time. ...

  4. python的multiprocessing模块进程创建、资源回收-Process,Pool

    python的multiprocessing有两种创建进程的方式,每种创建方式和进程资源的回收都不太相同,下面分别针对Process,Pool及系统自带的fork三种进程分析. 1.方式一:fork( ...

  5. Html5笔记之小结

    随着Android,IOS手机,平板等各种App的不断扩增,加上对过去传统HTML的的各种不完善,例如视频依靠Flash,对手机和桌面的不兼容等等.HTML5来了,来解决这些问题了. Html5是W3 ...

  6. 我理解的Java中重载与重写

    程序中我们用方法来实现对对象的操作,但是对象可能有不同的数据类型,这时候对不同的数据类型,进行相同的操作,我们就可以用到方法的重载,即方法名相同,但是具有不同的参数列表. 方法的重载可以根据传递参数的 ...

  7. 容器在 Weave 中如何通信和隔离?- 每天5分钟玩转 Docker 容器技术(65)

    上一节我们分析了 Weave 的网络结构,今天讨论 Weave 的连通和隔离特性. 首先在host2 执行如下命令: weave launch 192.168.56.104 这里必须指定 host1 ...

  8. Java 生产图片验证码

    import java.awt.Color;import java.awt.Font;import java.awt.Graphics;import java.awt.Graphics2D;impor ...

  9. chrome开发工具指南(六)

    检查和编辑页面与样式 使用 Chrome DevTools 的 Elements 面板检查和实时编辑页面的 HTML 与 CSS. 在 Elements 面板中检查和实时编辑 DOM 树中的任何元素. ...

  10. SQL 软解析和硬解析详解

    详见:http://blog.yemou.net/article/query/info/tytfjhfascvhzxcyt329 当客户端进程,将SQL语句通过监听器发送到Oracle时, 会触发一个 ...