MybatisUtil工具类

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

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

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

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

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

/**
 * MyBatis工具类
 * @author AdminTC
 */
public class MyBatisUtil {
    private static ThreadLocal<SqlSession> threadLocal = new ThreadLocal<SqlSession>();
    private static SqlSessionFactory sqlSessionFactory;
    static{
        try {
            Reader reader = Resources.getResourceAsReader("mybatis.xml");
            sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader);
        } catch (IOException e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        }
    }
    private MyBatisUtil(){}
    public static SqlSession getSqlSession(){
        SqlSession sqlSession = threadLocal.get();
        if(sqlSession == null){
            sqlSession = sqlSessionFactory.openSession();
            threadLocal.set(sqlSession);
        }
        return sqlSession;
    }
    public static void closeSqlSession(){
        SqlSession sqlSession = threadLocal.get();
        if(sqlSession != null){
            sqlSession.close();
            threadLocal.remove();
        }
    }
    public static void main(String[] args) {
        Connection conn = MyBatisUtil.getSqlSession().getConnection();
        System.out.println(conn!=null?"连接成功":"连接失败");
    }
}

MybatisUtil.java

  

动态SQL

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

  

动态SQL-选择

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

package com.harry.dao;

import java.sql.SQLException;
import java.util.List;
import java.util.Set;

import com.harry.entity.User;

public interface IUserDao {
     public boolean doCreate(User entity) throws Exception;

     public boolean doUpdate(User entity) throws Exception;

     public boolean doRemove(Set<Integer> ids)throws Exception;

     public User findById(Integer id)throws Exception;

     public List<User> findAll() throws  Exception;

     public List<User> findAllSplite(String column, String keyword, Integer currentPage, Integer lineSize) throws Exception;

     public Integer getAllCount(String column, String keyword) throws Exception;
}

IUserDao

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

package com.harry.dao.impl;

import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.apache.ibatis.session.SqlSession;

import com.harry.dao.IUserDao;
import com.harry.entity.User;
import com.harry.util.MybatisUtil;

public class UserDaoImpl implements IUserDao {

    @Override
    public boolean doCreate(User entity) throws Exception {
        // TODO Auto-generated method stub
        return false;
    }

    @Override
    public boolean doUpdate(User entity) throws Exception {
        // TODO Auto-generated method stub
        return false;
    }

    @Override
    public boolean doRemove(Set<Integer> ids) throws Exception {
        // TODO Auto-generated method stub
        return false;
    }

    @Override
    public User findById(Integer id) throws Exception {
        // TODO Auto-generated method stub
        return null;
    }

    @Override
    public List<User> findAll() throws Exception {
        // TODO Auto-generated method stub
        return null;
    }

    @Override
    public List<User> findAllSplite(String column, String keyword, Integer currentPage, Integer lineSize)
            throws Exception {
        // TODO Auto-generated method stub
        return null;
    }

    @Override
    public Integer getAllCount(String column, String keyword) throws Exception {
        // TODO Auto-generated method stub
        return null;
    }

    public List<User> dynaSQLwithSelect(String uname,Character usex) throws Exception{
        SqlSession sqlSession = MybatisUtil.getSqlSession();
        try{
            Map<String,Object> map = new LinkedHashMap<String, Object>();
            map.put("uname",uname);
            map.put("usex", usex);
            return sqlSession.selectList("dynaSQLwithSelect",map);
        }catch(Exception e){
            e.printStackTrace();
            sqlSession.rollback();
            throw e;
        }finally{
            sqlSession.commit();
            MybatisUtil.closeSqlSession();
        }
    }

}

UserDaoImpl

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

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

User.xml

  测试方法

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

MybatisTest

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

动态SQL-更新 

public boolean dynaSQLwithUpdate(Integer uid, String uname, String usex) throws Exception{
        //session应该在事务层进行开关,这里为了方便
        SqlSession sqlSession = MybatisUtil.getSqlSession();
        try{
            Map<String,Object> map = new LinkedHashMap<>();
            map.put("uid", uid);
            map.put("uname", uname);
            map.put("usex", usex);
            sqlSession.update("dynaSQLwithUpdate",map);
            return true;
        }catch(Exception e){
            e.printStackTrace();
            sqlSession.rollback();
            throw e;
        }finally{
            sqlSession.commit();
            MybatisUtil.closeSqlSession();
        }
    }

UserDaoImpl

<update id="dynaSQLwithUpdate" parameterType="map">
        UPDATE user
        <set>
            <if test="uname!=null">
                username=#{user.username},
            </if>
            <if test="usex!=null">
                sex=#{usex},
            </if>
        </set>
        where id=#{uid}
    </update>    

User.xml

动态SQL-删除

public boolean dynaSQLwithDelete(Integer... ids) throws Exception{
        //session应该在事务层进行开关,这里为了方便
        SqlSession sqlSession = MybatisUtil.getSqlSession();
        try{
            Map<String, Object> map = new LinkedHashMap<>();
            map.put("ids", ids);
            sqlSession.delete("dynaSQLwithDelete",map);
            return true;
        }catch(Exception e){
            e.printStackTrace();
            sqlSession.rollback();
            throw e;
        }finally{
            sqlSession.commit();
            MybatisUtil.closeSqlSession();
        }
    }

UserDaoImpl

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

User.xml

动态SQL- 插入

public boolean dynaSQLwithInsert(User... users) throws Exception{
        //session应该在事务层进行开关,这里为了方便
        SqlSession sqlSession = MybatisUtil.getSqlSession();
        try{
            Map<String, Object> map = new LinkedHashMap<>();
            map.put("users", users);
            sqlSession.insert("dynaSQLwithInsert",map);
            return true;
        }catch(Exception e){
            e.printStackTrace();
            sqlSession.rollback();
            throw e;
        }finally{
            sqlSession.commit();
            MybatisUtil.closeSqlSession();
        }
    }

UserDaoImpl

<insert id="dynaSQLwithInsert" parameterType="map" useGeneratedKeys="true" keyProperty="id">
        INSERT INTO user (username, birthday, sex, address) VALUES
        <foreach collection="users" item="user" separator=",">
            (#{user.username},#{user.birthday},#{user.sex},#{user.address})
        </foreach>
    </insert>
</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. 从"汉诺塔"经典递归到JS递归函数

    前言 参考<JavaScript语言精粹> 递归是一种强大的编程技术,他把一个问题分解为一组相似的子问题,每一问题都用一个寻常解去解决.递归函数就是会直接或者间接调用自身的一种函数,一般来 ...

  2. selenium+BeautifulSoup实现强大的爬虫功能

    sublime下运行 1 下载并安装必要的插件 BeautifulSoup selenium phantomjs 采用方式可以下载后安装,本文采用pip pip install BeautifulSo ...

  3. Python 使用期物处理并发

    抨击线程的往往是系统程序员,他们考虑的使用场景对一般的应用程序员来说,也许一生都不会遇到--应用程序员遇到的使用场景,99% 的情况下只需知道如何派生一堆独立的线程,然后用队列收集结果. 示例:网络下 ...

  4. Python常用排序算法

    1.冒泡排序 思路:将左右元素两两相比较,将值小的放在列表的头部,值大的放到列表的尾部 效率:O(n²) def bubble_sort(li): for i in range(len(li)-1): ...

  5. MarkDown---超强文本编辑器

    What you see Is What you  get ... --------------------------- Salmon 编辑器界面: ------------------------ ...

  6. React编写input组件传参共用onChange

    之前写页面上的input比较少,所以没有单提出来一个组件,今天研究了下input组件,但共用一个onChange的问题卡了一会儿,查了下发现几个比较好的方法,分享下: 方法一 Input组件 let ...

  7. node.js的fs核心模块读写文件操作 -----由浅入深

    node.js 里fs模块 常用的功能 实现文件的读写 目录的操作 - 同步和异步共存 ,有异步不用同步 - fs.readFile 都不能读取比运行内存大的文件,如果文件偏大也不会使用readFil ...

  8. 前端开发【第3篇:JavaScript序】

    JavaScript历史 聊聊JavaScript的诞生 JavaScirpt鼻祖:Bremdan Eich(布兰登·艾奇),JavaScript的诞生于浏览器的鼻祖网景公司(Netscape),发布 ...

  9. 对Java的数据类型和运算符的理解

    我知道千里之行始于足下,包含着对编程的兴趣,希望能够在这个平台上记录下我学习过程中的点点滴滴! Java的基本构造 标识符和关键字 标识符规则 标识符就是用于给程序中变量,类.方法命名的符号 1.标识 ...

  10. 转:js闭包

    一切都是对象 "一切都是对象"这句话的重点在于如何去理解"对象"这个概念. --当然,也不是所有的都是对象,值类型就不是对象. 首先咱们还是先看看javascr ...