mybatis正向反向工程操作数据库

本文详细介绍了Mybatis的定制SQL、映射配置、注解使用、参数传递、结果集映射、动态SQL、缓存策略及逆向工程等内容,帮助理解并实践Mybatis的高效数据库操作。

                                   Mybatis操作数据库

1是支持定制化sql 存储过程以及高级映射的休息的持久层框架
避免了几乎所有的jdbc代码 和手动配置参数以及获取结果集
mybatis可以使用简单得xml或注解用于配置和原始映射 将接口和加吧的pojo保存到数据库中


1mapper接口和mapper.xml配置文件在同一个包下
2mapper接口 文件名和mapper.xml文件名要一致
3mapper.xml配置文件名的名称空间取值一定是mapper接口的全类名
4mapper.xml配置文件中的id值 一定要和mapper接口反复噶名一直
5mapper.xml配置文件中的参数类型一定要和mapper接口的参数类型一致
6mapper.xml配置文件中的返回值类型 必须要和mapper皆苦的返回值类型一直

注解 @keymap的使用
可以把返回值作为map集合

Mybatis中 settings设置标签
mybatis 的核心配置之typeAliases
我们在编写sql 的配置文件中,经常会出现大量的相同的全类名。
这些全类名都是一样的字符串,我们就可以给一个类型定义一个简短的别名。去使用这个别名表示一个具体的类型。


12Mybatis 参数的传递
指的是 mapper接口中方法的参数值如何传递到mapper的#{}中去


12.一个普通的数据类型

12.2多个普通的数据类型
public List<User> queryUsersByNameorSex(String name, Integer sex);


 

@Param注解命名参数
<!--    public List<User> queryUsersByNameorSex(
               @Param("name") String name,
               @Param("sales") Integer sex);
             -->

12.3传递一个Map对象作为参数

<!--    public  List<User> queryUserByMap(Map<String,Object> parammap);

          map.put("name","水浒传"); ====>   #{name};
            map.put("sales",14)  ======>   #{sales};
            -->
!--    public  List<User> queryUserByMap(Map<String,Object> parammap);-->
    <select id="queryUserByMap" resultType="com.atguigu.pojo.User">
        select id ,`name` ,price,`author`,sales,stock,`img_path` from  t_book   where name=#{name} or sales=#{sales}

    </select>
@Test
public  void queryUserByMap(){
    SqlSession sqlSession = sqlSessionFactory.openSession();
    try {


        UserMapper mapper = sqlSession.getMapper(UserMapper.class);

        Map<String,Object> map=new LinkedHashMap<>();
        map.put("name","水浒传");
        map.put("sales",14);
         for(User user:mapper.queryUserByMap(map)){
             System.out.println(user);
         }
    }finally {
        sqlSession.close();
    }
}


12.4一个Pojo数据类型

12.5模糊查询
需求:现在要根据用户名产需用户对象 ,也就是希望插叙如下 select *from t_book  where name lile "%大%"         

@param注解  命名参数


13自定义结果集<resultMap> </resultMap>
可以把查询得到的结果集映射称为需要的数据返回,在适应ResultMap之前 我们都是使用ResultType属性每行自定转换数据类型
自动映射:自动的建立 列和javaBean属性的对应关系         
映射是指建立对应的关系

自动映射规则: 把每一个列名的值取出来 ,去找javaBean中过相同名称的属性赋值
 

<resultMap id="resultMap" type="com.atguigu.pojo.User">
    <id column="id" property="id"></id>
    <result column="name" property="name"></result>
    <result column="price" property="price"></result>
    <result column="author" property="author"></result>
    <result column="sales" property="sales"></result>
    <result column="stock" property="stock"></result>
    <result column="img_path" property="path"></result>
</resultMap>
<select id="queryUserById"  resultMap="resultMap">
    select id ,`name`,price,`author`,sales,stock,`img_path` from  t_book where  id=#{id}
</select>


14动态SQL

14.1 if语句


15.1.2一级缓存失效四种情况

/**
 * 1在不同的Sqlsession中
 */

@Test
public void firstCachFaill() {
    queryUserBySample();
    queryUserBySample();

}

/**
 * 2执行语句的参数不同,缓存中也不存在数据
 * */
@Test
public void firstCachFail2() {
    SqlSession sqlSession = sqlSessionFactory.openSession();
    try{
        UserMapper mapper = sqlSession.getMapper(UserMapper.class);
        BigDecimal price=new BigDecimal("20.9");

        mapper.queryUserBySample(new User(null,"思",price,"阿超",20,25,"as/asd")).forEach(System.out::println);
        mapper.queryUserBySample(new User(null,"想",price,"阿超",20,25,"as/asd")).forEach(System.out::println);
    }finally {
        sqlSession.close();

    }

}

3手动清空缓存

/**
 * 3手动清空缓存
 * */
@Test
public void firstCachFail3() {
    SqlSession sqlSession = sqlSessionFactory.openSession();
    try{
        UserMapper mapper = sqlSession.getMapper(UserMapper.class);
        BigDecimal price=new BigDecimal("20.9");

        mapper.queryUserBySample(new User(null,"思",price,"阿超",20,25,"as/asd")).forEach(System.out::println);
        sqlSession.clearCache();//清空缓存

        mapper.queryUserBySample(new User(null,"想",price,"阿超",20,25,"as/asd")).forEach(System.out::println);
    }finally {
        sqlSession.close();

    }

}


4增删改查操作多条指令
@Test
public void insertUser() {
    SqlSession sqlSession = sqlSessionFactory.openSession();
    try{
        UserMapper mapper = sqlSession.getMapper(UserMapper.class);
        BigDecimal price=new BigDecimal("20.9");

        mapper.insertUser(new User(null,"思",price,"阿超",20,25,"as/asd"));
      //  sqlSession.clearCache();//清空缓存
        
        mapper.insertUser(new User(null,"想",price,"阿超",20,25,"as/asd"));
       sqlSession.commit();

    }finally {
        sqlSession.close();

    }

}


14.2where语句
可以根据包含的内容是否有值,由内容就添加关键字where

15二级缓存
1mybatis 二级缓存默认不开启 需要到 mybatis-config.xml配置
2在Mapper的配置文件中加入cache便签 并且血药被二级缓存对象和实现java的序列化接口


15.2二级缓存演示

<settings>
    <setting name="cacheEnabled" value="true"/>
</settings>
useCache=true 使用二级缓存

 <select id="queryUserBySample" parameterType="com.atguigu.pojo.User" useCache="true" resultType="com.atguigu.pojo.User">

        select id ,`name` ,price,`author`,sales,stock,`img_path` from  t_book
where

          name like concat('%',#{name},'%')


       or price=#{price}


    </select>


//如果name值有效 则只用name模糊查询
//如果name值无效 则price值有效 则使用 price查询
//如果都无效 则使用自定义查询

public  List<User> queryUsersChoose(User user);
<select id=" queryUsersChoose" parameterType="com.atguigu.pojo.User">
        select id ,`name` ,price,`author`,sales,stock,`img_path` from  t_book
       <choose>
           <when test="name!=null">
               name like concat('%',#{name},'%')

           </when>
          <when test="price !=null">
              price=#{price}
          </when>
<otherwise>
    id=6
</otherwise>
       </choose>
    </select>

16set语句

set语句可以删除set关键字 条件后的逗号
update 表名 ser

17完整项目展示:

项目结构:

1. UserMapper  接口

package com.atguigu.mapper;

import com.atguigu.pojo.User;

import java.util.List;

/**
 * @author chao
 * @create -06-2022-06-04-8:20
 */
public interface UserMapper {

    //那user的lastname做为一个普通的

    public List<User> queryUserBySample(User user);

    public  int insertUser(User user);


    //如果name值有效 则只用name模糊查询
    //如果name值无效 则price值有效 则使用 price查询
    //如果都无效 则使用自定义查询
    public  List<User> queryUsersChoose(User user);

    public  int updateUser(User user);

}

32.User

package com.atguigu.pojo;


import java.math.BigDecimal;

/**
 * @author chao
 * @create -06-2022-06-02-10:20
 */
public class User {
    private  Integer id;
    private  String name;
    private BigDecimal price;
    private  String author;
    private  Integer sales;
    private  Integer stock;
    private  String path = "static/img/default.jpg";

    public User() {
    }

    public User(Integer id, String name, BigDecimal price, String author, Integer sales, Integer stock, String path) {
        this.id = id;
        this.name = name;
        this.price = price;
        this.author = author;
        this.sales = sales;
        this.stock = stock;
        this.path = path;

    }

    public Integer getId() {
        return id;
    }

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

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public BigDecimal getPrice() {
        return price;
    }

    public void setPrice(BigDecimal price) {
        this.price = price;
    }

    public String getAuthor() {
        return author;
    }

    public void setAuthor(String author) {
        this.author = author;
    }

    public Integer getSales() {
        return sales;
    }

    public void setSales(Integer sales) {
        this.sales = sales;
    }

    public Integer getStock() {
        return stock;
    }

    public void setStock(Integer stock) {
        this.stock = stock;
    }

    public String getPath() {
        return path;
    }

    public void setPath(String path) {
        this.path = path;
    }

    @Override
    public String toString() {
        return "User{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", price=" + price +
                ", author='" + author + '\'' +
                ", sales=" + sales +
                ", stock=" + stock +
                ", path='" + path + '\'' +
                '}';
    }
}

3UserMapperTest

package com.atguigu.test;

import com.atguigu.mapper.UserMapper;
import com.atguigu.pojo.User;
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.Before;
import org.junit.Test;

import java.math.BigDecimal;

/**
 * @author chao
 * @create -06-2022-06-04-8:30
 */
public class UserMapperTest {
    static SqlSessionFactory sqlSessionFactory;

    @Before
    public void setUp() throws Exception {
        sqlSessionFactory=new SqlSessionFactoryBuilder().build(Resources.getResourceAsStream("mybatis-config.xml"));

    }

    @Test
    public void queryUserBySample() {

        SqlSession sqlSession = sqlSessionFactory.openSession();
        try{
            UserMapper mapper = sqlSession.getMapper(UserMapper.class);
            BigDecimal price=new BigDecimal("20.9");

            mapper.queryUserBySample(new User(null,"思",price,"阿超",20,25,"as/asd")).forEach(System.out::println);
        }finally {
            sqlSession.close();

        }
    }

    /**
     * 1在不同的Sqlsession中
     */

    @Test
    public void firstCachFaill() {
        queryUserBySample();
        queryUserBySample();

    }


    /**
     * 执行语句的参数不同,缓存中也不存在数据
     * */
    @Test
    public void firstCachFail2() {
        SqlSession sqlSession = sqlSessionFactory.openSession();
        try{
            UserMapper mapper = sqlSession.getMapper(UserMapper.class);
            BigDecimal price=new BigDecimal("20.9");

            mapper.queryUserBySample(new User(null,"思",price,"阿超",20,25,"as/asd")).forEach(System.out::println);
            mapper.queryUserBySample(new User(null,"想",price,"阿超",20,25,"as/asd")).forEach(System.out::println);
        }finally {
            sqlSession.close();

        }

    }


    /**
     * 3手动清空缓存
     * */
    @Test
    public void firstCachFail3() {
        SqlSession sqlSession = sqlSessionFactory.openSession();
        try{
            UserMapper mapper = sqlSession.getMapper(UserMapper.class);
            BigDecimal price=new BigDecimal("20.9");

            mapper.queryUserBySample(new User(null,"思",price,"阿超",20,25,"as/asd")).forEach(System.out::println);
            sqlSession.clearCache();//清空缓存

            mapper.queryUserBySample(new User(null,"想",price,"阿超",20,25,"as/asd")).forEach(System.out::println);
        }finally {
            sqlSession.close();

        }

    }


    @Test
    public void insertUser() {
        SqlSession sqlSession = sqlSessionFactory.openSession();
        try{
            UserMapper mapper = sqlSession.getMapper(UserMapper.class);
            BigDecimal price=new BigDecimal("20.9");

            mapper.insertUser(new User(null,"思",price,"阿超",20,25,"as/asd"));
          //  sqlSession.clearCache();//清空缓存

            mapper.insertUser(new User(null,"想",price,"阿超",20,25,"as/asd"));
           sqlSession.commit();

        }finally {
            sqlSession.close();

        }

    }


    @Test
    public void secondfactory() {
        queryUserBySample();
        queryUserBySample();

    }



    @Test
    public void queryUsersChoose() {

        SqlSession sqlSession = sqlSessionFactory.openSession();
        try{
            UserMapper mapper = sqlSession.getMapper(UserMapper.class);
            BigDecimal price=new BigDecimal("20.9");

            mapper.queryUsersChoose(new User(null,"思",price,"阿超",20,25,"as/asd")).forEach(System.out::println);
        }finally {
            sqlSession.close();

        }
    }



    @Test
    public void updateUser() {

        SqlSession sqlSession = sqlSessionFactory.openSession();
        try {
            UserMapper mapper = sqlSession.getMapper(UserMapper.class);
            BigDecimal price = new BigDecimal("20.9");

            mapper.updateUser(new User(34, "思想", price, "阿超", 23, 25, "as/asd"));
            sqlSession.commit();
        } finally {
            sqlSession.close();

        }
    }





}

4配置文件:

UserMapper.xml

其他三个jdbc配制文件  以及mybatis-config.xml 以及 log4配置文件 直接可以网上搜索使用

<?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就是映射  映射mapper接口的方法和SQL语句对应的关系
  name是命名空间
  必须是Mapper接口的全类名
-->
<mapper namespace="com.atguigu.mapper.UserMapper">
<!--    public List<User> queryUserBySample(User user);-->
<!--    拿user的name属性做模糊查询-->

    <cache>
<!--        使用二级缓存-->
    </cache>
    <select id="queryUserBySample" parameterType="com.atguigu.pojo.User" useCache="true" resultType="com.atguigu.pojo.User">

        select id ,`name` ,price,`author`,sales,stock,`img_path` from  t_book
where

          name like concat('%',#{name},'%')


       or price=#{price}


    </select>

    <select id="queryUsersChoose" parameterType="com.atguigu.pojo.User">
        select id ,`name` ,price,`author`,sales,stock,`img_path` from  t_book
        <where>
       <choose>
           <when test="name!=null">
               name like concat('%',#{name},'%')

           </when>
          <when test="price !=null">
              price=#{price}
          </when>
<otherwise>
    id=6
</otherwise>
       </choose>
        </where>
    </select>



<!--    public  int insertUser(User user);-->
    <insert id="insertUser"  parameterType="com.atguigu.pojo.User">
             insert into  t_book(`name`,`price`,`author`,sales,stock,`img_path`) values (#{name},#{price},#{author},#{sales},#{stock},#{path})
    </insert>



<!--    public  int updateUser(User user);-->
    <update id="updateUser" parameterType="com.atguigu.pojo.User">
        update  t_book set   `name`=#{name} , `sales`=#{sales} where id=#{id}
    </update>



















<!--  public User queryUserById(Integer id);-->

<!--    id是唯一标识符  必须跟mapper接口中的方法名一致
        parameterType属性表示参数类型 可选设置
        resultType返回值类型
#{id}表示占位符参数        -->
    <!--    当接口参数为普通类型是 #{}可以写任意内容,但是推荐写对应的属性名-->
<!--    <resultMap id="resultMap" type="com.atguigu.pojo.User">-->
<!--        <id column="id" property="id"></id>-->
<!--        <result column="name" property="name"></result>-->
<!--        <result column="price" property="price"></result>-->
<!--        <result column="author" property="author"></result>-->
<!--        <result column="sales" property="sales"></result>-->
<!--        <result column="stock" property="stock"></result>-->
<!--        <result column="img_path" property="path"></result>-->
<!--    </resultMap>-->
<!--    <select id="queryUserById"  resultMap="resultMap">-->
<!--        select id ,`name`,price,`author`,sales,stock,`img_path` from  t_book where  id=#{id}-->
<!--    </select>-->



<!--&lt;!&ndash;    当参数是多个数据类型的时候,有两种方法可以传递参数值-->
<!--           方案一-->
<!--           arg0 arg1......-->

<!--          方案二-->
<!--          param1 param2-->
<!--;&ndash;&gt;-->
<!--&lt;!&ndash;    public List<User> queryUsersByNameorSex(-->
<!--               @Param("name") String name,-->
<!--               @Param("sales") Integer sex);-->

<!--               当我们在参数上使用了注解 ,则我们在sql语句中 使用#{nam}表示注解参数的name的属性值-->
<!--             &ndash;&gt;-->
<!--   <select id="queryUsersByNameorSex" resultType="com.atguigu.pojo.User">-->
<!--       select id ,`name` ,price,`author`,sales,stock,`img_path` from  t_book   where name=#{param1} or sales=#{param2}-->

<!--   </select>-->


<!--&lt;!&ndash;    public  List<User> queryUserByMap(Map<String,Object> parammap);-->

<!--          map.put("name","水浒传"); ====>      name=#{name};-->
<!--            map.put("sales",14)  ======>      sales=#{sales};-->
<!--            &ndash;&gt;-->
<!--    <select id="queryUserByMap" resultType="com.atguigu.pojo.User">-->
<!--        select id ,`name` ,price,`author`,sales,stock,`img_path` from  t_book   where name=#{name} or sales=#{sales}-->

<!--    </select>-->



<!--&lt;!&ndash;    public  int saveUser(User user);&ndash;&gt;-->
<!--&lt;!&ndash;    当参数是一个pojo对象 只需要在#{写上多对应的属性名即可}-->


<!--&ndash;&gt;-->
<!--    <insert id="saveUser"   parameterType="com.atguigu.pojo.User">-->
<!--        insert into  t_book(`name`,`price`,`author`,sales,stock,`img_path`) values (#{name},#{price},#{author},#{sales},#{stock},#{path})-->
<!--    </insert>-->


<!--&lt;!&ndash;    public  List<User> queryUsersLike(String name);-->
<!--需求:现在要根据用户名产需用户对象 ,也就是希望插叙如下 select *from t_book  where name lile "%大%"    &ndash;&gt;-->

<!--&lt;!&ndash;    #{}占位符   ?-->
<!--        ${}  它的作用时是指把指定参数的值输出  然后和sql钟大哥字符作拼接&ndash;&gt;-->
<!--&lt;!&ndash;    <select id="queryUsersLike" resultType="com.atguigu.pojo.User">&ndash;&gt;-->
<!--&lt;!&ndash;        select id ,`name` ,price,`author`,sales,stock,`img_path` from  t_book   where name like '%{name}%'&ndash;&gt;-->

<!--&lt;!&ndash;    </select>&ndash;&gt;-->
<!--    <select id="queryUsersLike" resultType="com.atguigu.pojo.User">-->
<!--        select id ,`name` ,price,`author`,sales,stock,`img_path` from  t_book   where name like concat('%',#{name},'%')-->

<!--    </select>-->



<!--&lt;!&ndash;    resultMap&ndash;&gt;-->



<!--&lt;!&ndash;    public  int  updateUser(User user);&ndash;&gt;-->
<!--    <update id="updateUser" parameterType="com.atguigu.pojo.User">-->
<!--        update  t_book set   `name`=#{name} where id=#{id}-->
<!--    </update>-->


<!--&lt;!&ndash;    public  int deleteByID(Integer id);&ndash;&gt;-->
<!--    <delete id="deleteByID" parameterType="com.atguigu.pojo.User">-->
<!--        delete  from  t_book where id=#{id}-->
<!--    </delete>-->


<!--&lt;!&ndash;    public Map<Integer,User> querUserMap();&ndash;&gt;-->
<!--    <select id="querUserMap" resultType="com.atguigu.pojo.User">-->
<!--        select id ,`name`,price,`author`,sales,stock,`img_path` from  t_book-->

<!--    </select>-->

</mapper>

18mybatis逆向工程

MyBatis逆向工程,简称 MBG。是一个专门为 MyBatis 框架使用者定制的代码生成器。可以快速的根据表生成对应的映射文件,接口,以及Bean类对象。在Mybatis 中,有一个可以自动对单表生成的增,删,改,查代码的插件。
叫mybatis-generator-core-1.3.2 。
它可以帮我们对比数据库表之后,生成大量的这个基础代码。这些基础代码有:
1、数据库表对应的javaBean对象
2、这些javaBean对象对应的Mapper接口3、这些Mapper接口对应的配置文件

逆向工程直接根据你的MySQL数据库所拥有的表 ,直接生成mybatis项目。同时包含增删改查语句,

我们可以直接使用,不需要自己写数据库SQL语句

项目展示:

1只需一个运行程序

package com.atguigu.mbg;

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

import java.io.File;
import java.io.IOException;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

/**
 * @author chao
 * @create -06-2022-06-04-11:50
 */
public class Runner {
    public static void main(String[] args) throws IOException, XMLParserException, InvalidConfigurationException, SQLException, InterruptedException {
        List<String> warnings = new ArrayList<String>();
        boolean overwrite = true;
        File configFile = new File("mybatis_mbg/mbg.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);

    }
}

2同样需要上述三个配置文件

3额外的mbg.xml配置文件 更具自己的项目工程路径 以及数据库改写就行

注意:

 <!-- Mybatis3Simple--> //使用Mybatis3Simple为生成简单版

<?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>
    <!-- 数据库驱动-->

    <context id="DB2Tables"  targetRuntime="MyBatis3">
<!--        Mybatis3Simple-->
        

        <commentGenerator>
            <property name="suppressDate" value="true"/>
            <!-- 是否去除自动生成的注释 true:是 : false:否 -->
            <property name="suppressAllComments" value="true"/>
        </commentGenerator>
        <!--数据库链接URL,用户名、密码 -->
        <jdbcConnection driverClass="com.mysql.jdbc.Driver" connectionURL="jdbc:mysql://localhost:19990/book?useUnicode=true&amp;characterEncoding=utf8&amp;useSSL=false" userId="root" password="">
        </jdbcConnection>
        <javaTypeResolver>
            <property name="forceBigDecimals" value="false"/>
        </javaTypeResolver>
        <!-- 生成模型的包名和位置-->
        <javaModelGenerator targetPackage="com.atguigu.pojo"
                            targetProject=".\mybatis_mbg\src">
            <property name="enableSubPackages" value="true"/>
            <property name="trimStrings" value="true"/>
        </javaModelGenerator>
        <!-- 生成映射文件的包名和位置-->
        <sqlMapGenerator targetPackage="com.atguigu.mapper"  targetProject=".\mybatis_mbg\src">
            <property name="enableSubPackages" value="true"/>
        </sqlMapGenerator>


        <!-- 生成DAO的包名和位置-->
        <javaClientGenerator type="XMLMAPPER"
                             targetPackage="com.atguigu.mapper"
                             targetProject=".\mybatis_mbg\src">
            <property name="enableSubPackages" value="true"/>
        </javaClientGenerator>
        <!-- 要生成哪些表-->
<!--        <table 标签 一个标签一个数据库表-->
        <table tableName="t_book" domainObjectName="User"></table>
          </context>
</generatorConfiguration>

5逆向生成的项目展示

自动生成数据库SQL语句UserMapper 接口,我们只需编写测试调用即可

此处生成逆向工程豪华版

 <context id="DB2Tables"  targetRuntime="MyBatis3">
<!--        Mybatis3Simple-->   //使用Mybatis3Simple为生成简单版

6测试程序

实现增删改查功能 

package com.atguigu.test;

import com.atguigu.mapper.UserMapper;
import com.atguigu.pojo.User;
import com.atguigu.pojo.UserExample;
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.Before;
import org.junit.Test;

import java.math.BigDecimal;
import java.util.List;

import static org.junit.Assert.*;

/**
 * @author chao
 * @create -06-2022-06-04-12:40
 */
public class UserMapperTest {
    static SqlSessionFactory sqlSessionFactory;

    @Before
    public void setUp() throws Exception {
        sqlSessionFactory=new SqlSessionFactoryBuilder().build(Resources.getResourceAsStream("mybatis-config.xml"));

    }

    @Test
    //用于求记录数
    public void countByExample() {
        //求销售大于20的书

        SqlSession sqlSession = sqlSessionFactory.openSession();
        try {

            UserMapper mapper = sqlSession.getMapper(UserMapper.class);

            UserExample userExample=new UserExample();
            //创建一个条件对象
            UserExample.Criteria criteria = userExample.createCriteria();
            criteria.andSalesGreaterThan(20);//销售大于20
            long count = mapper.countByExample(userExample);
            System.out.println(count);
            sqlSession.commit();
        }finally {
            sqlSession.close();
        }
    }

    @Test
    public void deleteByExample() {
        SqlSession sqlSession = sqlSessionFactory.openSession();
        try {

            UserMapper mapper = sqlSession.getMapper(UserMapper.class);
 UserExample userExample=new UserExample();
            UserExample.Criteria criteria = userExample.createCriteria();
            criteria.andNameEqualTo("思");
            UserExample.Criteria or = userExample.or();
            or.andNameEqualTo("想");
            mapper.deleteByExample(userExample);
            sqlSession.commit();
        }finally {
            sqlSession.close();
        }
    }

    @Test
    public void deleteByPrimaryKey() {
        SqlSession sqlSession = sqlSessionFactory.openSession();
        try {

            UserMapper mapper = sqlSession.getMapper(UserMapper.class);

            int i = mapper.deleteByPrimaryKey(23);
            System.out.println(i);
            sqlSession.commit();
        }finally {
            sqlSession.close();
        }
    }

    @Test
    public void insert() {
        SqlSession sqlSession = sqlSessionFactory.openSession();
        try {

            UserMapper mapper = sqlSession.getMapper(UserMapper.class);

            BigDecimal price = new BigDecimal("20.9");

            mapper.insert(new User(null, "思想2", price, "阿超", 233, 25, "as/asd"));
            sqlSession.commit();
        }finally {
            sqlSession.close();
        }
    }

    @Test
    public void insertSelective() {
        SqlSession sqlSession = sqlSessionFactory.openSession();
        try {

            UserMapper mapper = sqlSession.getMapper(UserMapper.class);


            sqlSession.commit();
        }finally {
            sqlSession.close();
        }
    }

    @Test
    public void selectByExample() {
        SqlSession sqlSession = sqlSessionFactory.openSession();
        try {

            UserMapper mapper = sqlSession.getMapper(UserMapper.class);

//            List<User> list = mapper.selectByExample(null);
////            list.forEach(System.out::println);
            UserExample userExample=new UserExample();
            UserExample.Criteria criteria = userExample.createCriteria();
            criteria.andAuthorEqualTo("龙伍");

            UserExample.Criteria or = userExample.or();
            or.andNameEqualTo("思");
            List<User> list = mapper.selectByExample(userExample);
            list.forEach(System.out::println);
            sqlSession.commit();
        }finally {
            sqlSession.close();
        }
    }

    @Test
    public void selectByPrimaryKey() {
        SqlSession sqlSession = sqlSessionFactory.openSession();
        try {

            UserMapper mapper = sqlSession.getMapper(UserMapper.class);

            User user = mapper.selectByPrimaryKey(25);
            System.out.println(user);
            sqlSession.commit();
        }finally {
            sqlSession.close();
        }
    }

    @Test
    public void updateByExampleSelective() {
        SqlSession sqlSession = sqlSessionFactory.openSession();
        try {

            UserMapper mapper = sqlSession.getMapper(UserMapper.class);
           UserExample userExample=new UserExample();
           UserExample userExample1=new UserExample();
            UserExample.Criteria criteria = userExample.createCriteria();
            criteria.andNameEqualTo("思想2");

            BigDecimal price = new BigDecimal("20.9");
            int update = mapper.updateByExampleSelective(new User(null, "思想3", price, "阿超", 233, 25, "as/asd"), userExample);
            System.out.println(update);
            sqlSession.commit();
        }finally {
            sqlSession.close();
        }
    }

    @Test
    public void updateByExample() {
        SqlSession sqlSession = sqlSessionFactory.openSession();
        try {

            UserMapper mapper = sqlSession.getMapper(UserMapper.class);
            //根据条件更新非空的的字段

            UserExample userExample=new UserExample();
            UserExample userExample1=new UserExample();
            UserExample.Criteria criteria = userExample.createCriteria();
            criteria.andNameEqualTo("思想2");

            BigDecimal price = new BigDecimal("20.9");
            int update = mapper.updateByExample(new User(null, "思想3", price, "阿超", 233, 25, "as/asd"), userExample);
            System.out.println(update);
            sqlSession.commit();
        }finally {
            sqlSession.close();
        }
    }

    @Test
    public void updateByPrimaryKeySelective() {
        SqlSession sqlSession = sqlSessionFactory.openSession();
        try {

            UserMapper mapper = sqlSession.getMapper(UserMapper.class);

            BigDecimal price = new BigDecimal("20.9");
            mapper.updateByPrimaryKeySelective(new User(37, "思想4", price, "阿超", 233, 25, "as/asd"));


            sqlSession.commit();
        }finally {
            sqlSession.close();
        }
    }

    @Test
    public void updateByPrimaryKey() {
        SqlSession sqlSession = sqlSessionFactory.openSession();
        try {

            UserMapper mapper = sqlSession.getMapper(UserMapper.class);
            BigDecimal price = new BigDecimal("20.9");
            mapper.updateByPrimaryKeySelective(new User(37, "思想4", price, "阿超", 233, 25, "as/asd"));

            sqlSession.commit();
        }finally {
            sqlSession.close();
        }
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值