Mybatis(三)

1 Mybaits--动态SQL

  • 动态SQL是Mybatis强大特性之一。极大的简化我们拼装SQL的操作。
  • 动态SQL元素和使用JSTL或其他类似基于XML的文本处理器相似。
  • Mybatis采用功能强大的基于OGNL的表达式来简化操作。
    • if
    • choose(when ,otherwise) 
    • trim(where,set)
    • foreach

1.1 动态SQL之if

package cn.demo2;

/**
 * 描述:POJO
 */
public class Employee {
    private Integer id;
    private String lastName;
    private String gender;
    private String email;
    private Department department;

    public Department getDepartment() {
        return department;
    }

    public void setDepartment(Department department) {
        this.department = department;
    }

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    public String getLastName() {
        return lastName;
    }

    public void setLastName(String lastName) {
        this.lastName = lastName;
    }

    public String getGender() {
        return gender;
    }

    public void setGender(String gender) {
        this.gender = gender;

    }

    @Override
    public String toString() {
        return "Employee{" +
                "email=‘" + email + ‘\‘‘ +
                ", gender=‘" + gender + ‘\‘‘ +
                ", lastName=‘" + lastName + ‘\‘‘ +
                ", id=" + id +
                ‘}‘;
    }
}
package cn.demo2;

import java.util.List;

public interface IEmployeeDAO {

    public List<Employee> getConditionIf(Employee employee);

}
<?xml version="1.0" encoding="UTF-8" ?>
        <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="cn.demo2.IEmployeeDAO">

    <select id="getConditionIf" resultType="cn.demo2.Employee" >
      SELECT id,last_name lastName,email,gender from employee
      WHERE
      <if test="id != null">
        id = #{id}
      </if>
      <if test="lastName != null and lastName != ‘‘">
          and last_name like #{lastName}
      </if>
      <if test="email != null and email.trim() != ‘‘">
          and email = #{email}
      </if>
       <if test="gender == ‘男‘ or gender == ‘女‘">
          and gender = #{gender}
       </if>
    </select>

</mapper>
package cn.test;

import cn.demo2.Employee;
import cn.demo2.IEmployeeDAO;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.junit.Test;

import java.io.IOException;
import java.io.InputStream;
import java.util.List;

public class MybatisTest2 {

    /**
     * 测试查询
     * @throws IOException
     */
    @Test
    public  void demo1() throws IOException {
        String resource = "mybatis-config.xml";
        InputStream inputStream = Resources.getResourceAsStream(resource);
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
        SqlSession session = sqlSessionFactory.openSession();
        IEmployeeDAO dao = session.getMapper(IEmployeeDAO.class);
        Employee employee = new Employee();
        employee.setId(5);
        List<Employee> employees = dao.getConditionIf(employee);
        System.out.print(employees);

        session.close();
    }
}

1.2 动态SQL之where

  • 如果上面的程序中的id没有传入,那么拼接的SQL会多出and。

    • 解决方案一:在where之后加上1=1。
    • 解决方案二:Mybatis推荐使用where标签来将所有的查询条件包括在内,Mybatis就会将where标签中多出的and或or删除自动删除。并且where标签只会去掉第一个多出的and或or等。
package cn.demo2;

/**
 * 描述:POJO
 */
public class Employee {
    private Integer id;
    private String lastName;
    private String gender;
    private String email;
    private Department department;

    public Department getDepartment() {
        return department;
    }

    public void setDepartment(Department department) {
        this.department = department;
    }

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    public String getLastName() {
        return lastName;
    }

    public void setLastName(String lastName) {
        this.lastName = lastName;
    }

    public String getGender() {
        return gender;
    }

    public void setGender(String gender) {
        this.gender = gender;

    }

    @Override
    public String toString() {
        return "Employee{" +
                "email=‘" + email + ‘\‘‘ +
                ", gender=‘" + gender + ‘\‘‘ +
                ", lastName=‘" + lastName + ‘\‘‘ +
                ", id=" + id +
                ‘}‘;
    }
}
<?xml version="1.0" encoding="UTF-8" ?>
        <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="cn.demo2.IEmployeeDAO">

    <select id="getConditionIf" resultType="cn.demo2.Employee" >
      SELECT id,last_name lastName,email,gender from employee
      <where>

          <if test="id != null">
              id = #{id}
          </if>
          <if test="lastName != null and lastName != ‘‘">
              and last_name like #{lastName}
          </if>
          <if test="email != null and email.trim() != ‘‘">
              and email = #{email}
          </if>
          <if test="gender == ‘男‘ or gender == ‘女‘">
              and gender = #{gender}
          </if>

      </where>

    </select>

</mapper>
package cn.test;

import cn.demo2.Employee;
import cn.demo2.IEmployeeDAO;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.junit.Test;

import java.io.IOException;
import java.io.InputStream;
import java.util.List;

public class MybatisTest2 {

    /**
     * 测试查询
     * @throws IOException
     */
    @Test
    public  void demo1() throws IOException {
        String resource = "mybatis-config.xml";
        InputStream inputStream = Resources.getResourceAsStream(resource);
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
        SqlSession session = sqlSessionFactory.openSession();
        IEmployeeDAO dao = session.getMapper(IEmployeeDAO.class);
        Employee employee = new Employee();
        employee.setLastName("%呵%");
        List<Employee> employees = dao.getConditionIf(employee);
        System.out.print(employees);

        session.close();
    }
}

1.2 动态SQL之trim

package cn.demo2;

/**
 * 描述:POJO
 */
public class Employee {
    private Integer id;
    private String lastName;
    private String gender;
    private String email;
    private Department department;

    public Department getDepartment() {
        return department;
    }

    public void setDepartment(Department department) {
        this.department = department;
    }

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    public String getLastName() {
        return lastName;
    }

    public void setLastName(String lastName) {
        this.lastName = lastName;
    }

    public String getGender() {
        return gender;
    }

    public void setGender(String gender) {
        this.gender = gender;

    }

    @Override
    public String toString() {
        return "Employee{" +
                "email=‘" + email + ‘\‘‘ +
                ", gender=‘" + gender + ‘\‘‘ +
                ", lastName=‘" + lastName + ‘\‘‘ +
                ", id=" + id +
                ‘}‘;
    }
}
package cn.demo2;

import java.util.List;

public interface IEmployeeDAO {

    public List<Employee> getConditionIf(Employee employee);

}
<?xml version="1.0" encoding="UTF-8" ?>
        <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="cn.demo2.IEmployeeDAO">

    <select id="getConditionIf" resultType="cn.demo2.Employee" >
      SELECT id,last_name lastName,email,gender from employee
      <!--
        where标签职能消除前面多余的and或者or之类的语句,而如果and或or在之后,那么where就无能为力了
        trim可以来解决这样的问题
            prefix表示在拼接的SQL之前加前缀
            prefixOverrides是将前面多余的and或or等消除
            suffix和prefix相反
            prefixOverrides和prefixOverrides相反
      -->
      <trim prefix="where" suffixOverrides="and">

          <if test="id != null">
              id = #{id} and
          </if>
          <if test="lastName != null and lastName != ‘‘">
            last_name like #{lastName} and
          </if>
          <if test="email != null and email.trim() != ‘‘">
             email = #{email} and
          </if>
          <if test="gender == ‘男‘ or gender == ‘女‘">
              and gender = #{gender}
          </if>

      </trim>

    </select>

</mapper>
package cn.test;

import cn.demo2.Employee;
import cn.demo2.IEmployeeDAO;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.junit.Test;

import java.io.IOException;
import java.io.InputStream;
import java.util.List;

public class MybatisTest2 {

    /**
     * 测试查询
     * @throws IOException
     */
    @Test
    public  void demo1() throws IOException {
        String resource = "mybatis-config.xml";
        InputStream inputStream = Resources.getResourceAsStream(resource);
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
        SqlSession session = sqlSessionFactory.openSession();
        IEmployeeDAO dao = session.getMapper(IEmployeeDAO.class);
        Employee employee = new Employee();
        employee.setLastName("%呵%");
        List<Employee> employees = dao.getConditionIf(employee);
        System.out.print(employees);

        session.close();
    }
}

1.3 动态SQL之分支查询(和Java中的switch--case相似)

package cn.demo2;

/**
 * 描述:POJO
 */
public class Employee {
    private Integer id;
    private String lastName;
    private String gender;
    private String email;
    private Department department;

    public Department getDepartment() {
        return department;
    }

    public void setDepartment(Department department) {
        this.department = department;
    }

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    public String getLastName() {
        return lastName;
    }

    public void setLastName(String lastName) {
        this.lastName = lastName;
    }

    public String getGender() {
        return gender;
    }

    public void setGender(String gender) {
        this.gender = gender;

    }

    @Override
    public String toString() {
        return "Employee{" +
                "email=‘" + email + ‘\‘‘ +
                ", gender=‘" + gender + ‘\‘‘ +
                ", lastName=‘" + lastName + ‘\‘‘ +
                ", id=" + id +
                ‘}‘;
    }
}
package cn.demo2;

import java.util.List;

public interface IEmployeeDAO {

    public List<Employee> getConditionIf(Employee employee);

}
<?xml version="1.0" encoding="UTF-8" ?>
        <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="cn.demo2.IEmployeeDAO">

    <select id="getConditionIf" resultType="cn.demo2.Employee" >
      SELECT id,last_name lastName,email,gender from employee
      <where>
          <choose>
              <when test="id != null">
                  id = #{id}
              </when>
              <when test="lastName != null">
                  last_name like  #{lastName}
              </when>
              <when test="email != null">
                  email = #{email}
              </when>
              <otherwise>
                  gender = #{gender}
              </otherwise>
          </choose>
      </where>
    </select>

</mapper>
package cn.test;

import cn.demo2.Employee;
import cn.demo2.IEmployeeDAO;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.junit.Test;

import java.io.IOException;
import java.io.InputStream;
import java.util.List;

public class MybatisTest2 {

    /**
     * 测试查询
     * @throws IOException
     */
    @Test
    public  void demo1() throws IOException {
        String resource = "mybatis-config.xml";
        InputStream inputStream = Resources.getResourceAsStream(resource);
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
        SqlSession session = sqlSessionFactory.openSession();
        IEmployeeDAO dao = session.getMapper(IEmployeeDAO.class);
        Employee employee = new Employee();
        employee.setLastName("%呵%");
        List<Employee> employees = dao.getConditionIf(employee);
        System.out.print(employees);

        session.close();
    }
}

1.4 动态SQL之更新

 public void updateEmployee(Employee employee);
    <update id="updateEmployee" >
        update employee
        <set>
            <if test="email != null">
                email = #{email},
            </if>
            <if test="lastName != null">
                last_name = #{lastName}
            </if>
            <if test="gender != null">
                gender = #{gender}
            </if>
        </set>
        where id = #{id}
    </update>
 @Test
    public  void demo1() throws IOException {
        String resource = "mybatis-config.xml";
        InputStream inputStream = Resources.getResourceAsStream(resource);
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
        SqlSession session = sqlSessionFactory.openSession();
        IEmployeeDAO dao = session.getMapper(IEmployeeDAO.class);
        Employee employee = new Employee();
        employee.setId(5);
        employee.setLastName("哈哈");
        dao.updateEmployee(employee);
        session.commit();
        session.close();
    }

1.5 动态SQL--forEach

public List<Employee> getEmpsByConditionForEach(List<Integer> ids);
<select id="getEmpsByConditionForEach" resultType="cn.demo2.Employee" >
        select * from employee where id IN
        <foreach collection="list" item="item_id" separator="," open="(" close=")" >
            #{item_id}
        </foreach>
    </select>
 /**
     * 测试查询
     * @throws IOException
     */
    @Test
    public  void demo1() throws IOException {
        String resource = "mybatis-config.xml";
        InputStream inputStream = Resources.getResourceAsStream(resource);
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
        SqlSession session = sqlSessionFactory.openSession();
        IEmployeeDAO dao = session.getMapper(IEmployeeDAO.class);
        dao.getEmpsByConditionForEach(Arrays.asList(5,6,7));
        session.close();
    }

  

  

时间: 2024-09-30 06:43:16

Mybatis(三)的相关文章

Mybatis(三) 映射文件详解

前面说了全局配置文件中内容的详解,大家应该清楚了,现在来说说这映射文件,这章就对输入映射.输出映射.动态sql这几个知识点进行说明,其中高级映射(一对一,一对多,多对多映射)在下一章进行说明. 一.输入映射 输入映射:配置statement中输入参数的类型.有四种 1.1.传递简单类型,八大基本类型,比如int类型 findUserById:根据id进行查询对应user,那么传入的就应该是int类型的值.所以使用别名int来映射传入的值 1.2.传递pojo(代表正常的对象,比如user的jav

关于Mybatis三种批量插入方式对比

第一种:普通for循环插入 @Test public void testInsertBatch2() throws Exception { long start = System.currentTimeMillis(); User user; SqlSession sqlSession = sqlSessionTemplate.getSqlSessionFactory().openSession(false); UserDao mapper = sqlSession.getMapper(User

浅谈Mybatis(三)

一.动态SQL 1.sql片段 解决sql语句的冗余代码问题. <sql id="SELECT_T_USER"> select id,name,password,birthday </sql> <select id="queryUserById" resultType="User"> <include refid="SELECT_T_USER"/> from t_user whe

spring与mybatis三种整合方法

1.采用MapperScannerConfigurer,它将会查找类路径下的映射器并自动将它们创建成MapperFactoryBean.spring-mybatis.xml: <?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.

转:spring与mybatis三种整合方法

哎,csdn没转载功能,只能复制了.. 本文主要介绍Spring与Mybatis三种常用整合方法,需要的整合架包是mybatis-spring.jar,可通过链接http://code.google.com/p/mybatis/下载到. 1.采用数据映射器(MapperFactoryBean)的方式,不用写mybatis映射文件,采用注解方式提供相应的sql语句和输入参数.  (1)Spring配置文件: <!-- 引入jdbc配置文件 -->     <context:property

Mybatis (三)

1 Mybatis的动态SQL简介 动态SQL是Mybatis强大的特性之一,极大的简化我们拼接SQL的操作. 动态SQL元素和使用JSTL或其他类似基于XML的文本处理器相似. Mybatis采用功能强大的OGNL表达式来简化操作. if choose when otherwise trim where set foreach 2 if标签 示例: EmployeeMapper.java package com.xuweiwei.mybatis.mapper; import com.xuwei

Mybatis三

1.session.commit()为什么会引起事物的提交? 先ctrl+鼠标左键点入commit方法中,然后ctrl+H找到DefaultSqlSession这个类,在这个类中找到如下的方法 然后进入这个方法 这里有一个逻辑关系表达式,运算的顺序是  &&  ||  !的顺序依次运算得到的结果是true,那么该方法的返回值是true 所以执行器的提交,会引起事务的提交 2.session.close()会引起事务的回滚?(同上述方法相似,一步一步往上一层找,就可以找到答案,看到它底层的代

深入浅出Mybatis(三)查询

前言 要对数据库进行操纵,得有一个需求,所以拟定了一个下面的需求,实现下面的功能: 根据用户id查询一个用户信息 根据用户名称模糊查询用户信息列表 添加用户 更新用户 删除用户 程序编写 建立User.java实体类 pojo类作为mybatis进行sql映射使用,pojo类通常与数据库表对应, 在src中建立一个名为cn.itcast.mybatis.pojo的包,在包内建立一个名为User.java的类: package com.dtt.com.dtt.mybatis.pojo; impor

mybatis三种缓存

1.一级缓存 ? MyBatis 默认开启了一级缓存,一级缓存是在SqlSession 层面进行缓存的.即,同一个SqlSession ,多次调用同一个Mapper和同一个方法的同一个参数,只会进行一次数据库查询,然后把数据缓存到缓冲中,以后直接先从缓存中取出数据,不会直接去查数据库. ? 但是不同的SqlSession对象,因为不用的SqlSession都是相互隔离的,所以相同的Mapper.参数和方法,他还是会再次发送到SQL到数据库去执行,返回结果. 2.二级缓存 ? 为了克服这个问题,需

mybatis源码解读(三)——数据源的配置

在mybatis-configuration.xml 文件中,我们进行了如下的配置: <!-- 可以配置多个运行环境,但是每个 SqlSessionFactory 实例只能选择一个运行环境常用: 一.development:开发模式 二.work:工作模式 --> <environments default="development"> <!--id属性必须和上面的default一样 --> <environment id="deve