Mybatis第三天

 Mybatis第三天


 1.动态sql语句

  1. if

    <if test="条件">
                    
    </if>

     

  2. where:在sql语句的开头加上where,并去除头部的and或or

    <where>
        <if test = "">
        </if>
        <if test = "">
        </if>
    </where>

     

  3. set:在sql语句前添加set,并把sql语句中最后的”,”去除

    <set>
        <if test = "">
        </if>
        <if test = "">
        </if>
    </set>

     

  4. trim:可以完成set或者是where标记的功能

    <trim prefix="前缀" prefixOverrides="去除的前缀" suffix="后缀" suffixOverrides="去除的后缀">        
        <if test="">
                    
        </if>
        <if test="">
                    
        </if>        
    </trim>

     

  5. choose+when+otherwise

    <select>
        <where>
        <choose>
            <when test="">
                    sql语句
            </when>
            <when test="">
                    sql语句
            </when>
            <otherwise>
                    sql语句
            </otherwise>
        </choose>        
        </where>        
    </select>

     

  6. SQL 片段

    <sql id="sql名">公共语句或字段</sql> //公共代码
    
    <include refid="sql名"/> //引用

     

  7. foreach

    <select id="" resultType="">
        select <include refid="users"/>from users        
        <where>
            <!-- 防止集合为空 -->
        <if test="ids.size()!=0">
            <!--
                        collection:指定输入对象中的集合属性
                        item:每次遍历生成的对象
                        open:开始遍历时的拼接字符串
                        close:结束时拼接的字符串
                        separator:遍历对象之间需要拼接的字符串
                        select * from user where id in (1,2,3)
               -->
           <foreach collection="ids" item="id" open="id in(" close=")" separator=",">
            #{id}
           </foreach>
            </if>
        </where>    
    </select>

     

  8. 模糊查询

    sql语句  where name like concat('%',#{name},'%')

     

2.逆向工程(generator)

 

  1.下载jar包

 

    

 

  2.配置逆向工程文件

 

    1)在工程根目录下新建xml文件

      

    2)配置文件

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE generatorConfiguration
  PUBLIC "-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN"
  "http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd">

<generatorConfiguration>
  <!-- 路径是jar包的路径,最好路径不含中文 -->
  <classPathEntry location="E:\\java\\mybatis-generator-core-1.3.5.jar" />

  <context id="DB2Tables" targetRuntime="MyBatis3">
  
      <!-- 是否去除逆向生成中的注释 true:是;false:否-->
    <commentGenerator>
        <property name="suppressAllComments" value="true" />
    </commentGenerator>
    
    <!-- 配置数据库连接信息 -->
    <jdbcConnection driverClass="com.mysql.jdbc.Driver"
        connectionURL="jdbc:mysql://localhost:3306/mybatis"
        userId="root"
        password="root">
    </jdbcConnection>

    <javaTypeResolver >
      <property name="forceBigDecimals" value="false" />
    </javaTypeResolver>

    <!-- 实体类bean所在的位置 -->
    <javaModelGenerator targetPackage="com.zhiyou100.zfx.bean" targetProject="./src">
      <property name="enableSubPackages" value="true" />
      <property name="trimStrings" value="true" />
    </javaModelGenerator>

    <!-- 映射文件mapper的位置 -->
    <sqlMapGenerator targetPackage="com.zhiyou100.zfx.mapper"  targetProject="./resources">
      <property name="enableSubPackages" value="true" />
    </sqlMapGenerator>

    <!-- dao类所在位置 -->
    <javaClientGenerator type="XMLMAPPER" targetPackage="com.zhiyou100.zfx.dao"  targetProject="./src">
      <property name="enableSubPackages" value="true" />
    </javaClientGenerator>

    <!-- 表与实体类 -->
    <table schema="mybatis" tableName="users" domainObjectName="Users"
    enableCountByExample="false" enableDeleteByExample="false" enableSelectByExample="false" enableUpdateByExample="false">
    <!-- Example结尾的最好用false,有些方法还是自己写为好 -->
      <property name="useActualColumnNames" value="true"/>
      <generatedKey column="ID" sqlStatement="DB2" identity="true" />
      <columnOverride column="DATE_FIELD" property="startDate" />
      <ignoreColumn column="FRED" />
      <columnOverride column="LONG_VARCHAR_FIELD" jdbcType="VARCHAR" />
    </table>

  </context>
  
</generatorConfiguration>

 

    3)编写java启动类,执行逆向工程的配置文件,生成数据库中指定表的bean和dao层

      
package com.zhiyou100.zfx.test;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import org.mybatis.generator.api.MyBatisGenerator;
import org.mybatis.generator.config.Configuration;
import org.mybatis.generator.config.xml.ConfigurationParser;
import org.mybatis.generator.internal.DefaultShellCallback;

public class test {

    public static void main(String[] args) throws Exception{
    List<String> warnings = new ArrayList<String>();
    boolean overwrite = true;
    File configFile = new File("generator.xml");
    ConfigurationParser cp = new ConfigurationParser(warnings);
    Configuration config = cp.parseConfiguration(configFile);
    DefaultShellCallback callback = new DefaultShellCallback(overwrite);
    MyBatisGenerator myBatisGenerator = new MyBatisGenerator(config, callback, warnings);
    myBatisGenerator.generate(null);
    }

}

 

 

3.分页助手(pageHelper)

 

  1)引入jar包

    

 

 

  2)在配置文件conf.xml中添加

    

 

 

  3)dao类和相应的映射文件中要有查询方法

      dao类

 

package com.zhiyou100.zfx.dao;

import java.util.List;

import com.zhiyou100.zfx.bean.Users;

public interface UsersMapper {
    /**
     * 根据id删
     */
    int deleteByPrimaryKey(Integer id);

    /**
     * 全部添加
     */
    int insert(Users record);

    /**
     * 部分添加
     */
    int insertSelective(Users record);

    /**
     * 通过id查询
     */
    Users selectByPrimaryKey(Integer id);

    /**
     * 按主键选择性修改
     */
    int updateByPrimaryKeySelective(Users record);

    /**
     * 通过主键修改
     */
    int updateByPrimaryKey(Users record);
    
    List<Users> selectAll();
}

 

 

    mapper

<?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="com.zhiyou100.zfx.dao.UsersMapper">

  <!-- resultMap -->
  <resultMap id="BaseResultMap" type="com.zhiyou100.zfx.bean.Users">
    <id column="id" jdbcType="INTEGER" property="id" />
    <result column="NAME" jdbcType="VARCHAR" property="NAME" />
    <result column="age" jdbcType="INTEGER" property="age" />
  </resultMap>
  
  <!-- 公共代码块 -->
  <sql id="Base_Column_List">    
    id, NAME, age
  </sql>
  
  <!-- 根据id查 -->
  <select id="selectByPrimaryKey" parameterType="java.lang.Integer" resultMap="BaseResultMap">    
    select 
    <include refid="Base_Column_List" />
    from users
    where id = #{id,jdbcType=INTEGER}
  </select>
  
  <!-- 查询所有 -->
  <select id="selectAll" resultMap="BaseResultMap">
      select <include refid="Base_Column_List" /> from users
  </select>
  
  <!-- 根据id删 -->
  <delete id="deleteByPrimaryKey" parameterType="java.lang.Integer">   
    delete from users
    where id = #{id,jdbcType=INTEGER}
  </delete>
  
  <!-- 增加全部 -->
  <insert id="insert" parameterType="com.zhiyou100.zfx.bean.Users"> 
    <selectKey keyProperty="id" order="AFTER" resultType="java.lang.Integer">
      VALUES IDENTITY_VAL_LOCAL()
    </selectKey>
    insert into users (NAME, age)
    values (#{NAME,jdbcType=VARCHAR}, #{age,jdbcType=INTEGER})
  </insert>
  
  <!-- 增加部分  -->
  <insert id="insertSelective" parameterType="com.zhiyou100.zfx.bean.Users">   
    <selectKey keyProperty="id" order="AFTER" resultType="java.lang.Integer">
      VALUES IDENTITY_VAL_LOCAL()
    </selectKey>
    insert into users
    <trim prefix="(" suffix=")" suffixOverrides=",">
      <if test="NAME != null">
        NAME,
      </if>
      <if test="age != null">
        age,
      </if>
    </trim>
    <trim prefix="values (" suffix=")" suffixOverrides=",">
      <if test="NAME != null">
        #{NAME,jdbcType=VARCHAR},
      </if>
      <if test="age != null">
        #{age,jdbcType=INTEGER},
      </if>
    </trim>
  </insert>
  
  <!-- 修改部分 -->
  <update id="updateByPrimaryKeySelective" parameterType="com.zhiyou100.zfx.bean.Users">    
    update users
    <set>
      <if test="NAME != null">
        NAME = #{NAME,jdbcType=VARCHAR},
      </if>
      <if test="age != null">
        age = #{age,jdbcType=INTEGER},
      </if>
    </set>
    where id = #{id,jdbcType=INTEGER}
  </update>
  
  <!-- 通过id修改 -->
  <update id="updateByPrimaryKey" parameterType="com.zhiyou100.zfx.bean.Users">    
    update users
    set NAME = #{NAME,jdbcType=VARCHAR},
      age = #{age,jdbcType=INTEGER}
    where id = #{id,jdbcType=INTEGER}
  </update>
</mapper>

 

  4)编写测试类

@Test
void selectByPage() {
    //1.使用PageHelper类设置起始页和每页显示的页数
    int pageNum = 1;
    int pageSize = 3;        
    PageHelper.startPage(pageNum, pageSize);
        
    //2.调用查询所有的方法
    List<Users> list = usersMapper.selectAll();
        
    //3.把查询的结果封装到Pageinfo中
    PageInfo<Users> pageinfo = new PageInfo<>(list);
        
    System.out.println(pageinfo);
                
}

posted on 2019-08-31 10:53  飞升羊羽  阅读(107)  评论(0)    收藏  举报

导航