MyBatis中增删改查

用了大概一天半的时间又重新学了一边mybatis框架,下面是感悟和代码并且有目录截图等

感悟

  1. 感觉第二笔效果还是比第一遍抢多了
  2. 学习到了一个新工具,mybatisx(黑色的小鸟吖)
  3. 此处省略很多哈哈哈

步入正题哈哈哈,刚刚看了下笔记居然没有修改

这里我把增删改查分开写了哈,等会我会注明代码分别放到什么文件里面,这样方便你们测试运行学习等

代码目录截图

项目是MybatisDemo03这个项目,01,02是别的东西

mybatis

配置文件

  1. 需要手动配置下property标签里面的东西,账号密码,数据库东西我会放在下面

    <?xml version="1.0" encoding="UTF-8" ?>
    <!DOCTYPE configuration
         PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
         "http://mybatis.org/dtd/mybatis-3-config.dtd">
    <configuration>
     <environments default="development">
         <environment id="development">
             <transactionManager type="JDBC"/>
             <dataSource type="POOLED">
                 <property name="driver" value="com.mysql.jdbc.Driver"/>
                 <property name="url" value="jdbc:mysql://127.0.0.1:3306/mybatis"/>
                 <property name="username" value="***"/>
                 <property name="password" value="**"/>
             </dataSource>
         </environment>
     </environments>
     <mappers>
    
         <mapper resource="com/xiaonan/mapper/BrandMapper.xml"/>
     </mappers>
    </configuration>

实体类

  1. 复制进去,切记换包名,idea好像可以直接就换好了

    package com.xiaonan.pojo;
    
    /**
     * 品牌
     *
     * alt + 鼠标左键:整列编辑
     *
     * 在实体类中,基本数据类型建议使用其对应的包装类型
     */
    
    public class Brand {
     // id 主键
     private Integer id;
     // 品牌名称
     private String brandName;
     // 企业名称
     private String companyName;
     // 排序字段
     private Integer ordered;
     // 描述信息
     private String description;
     // 状态:0:禁用  1:启用
     private Integer status;
     
     public Integer getId() {
         return id;
     }
     public void setId(Integer id) {
         this.id = id;
     }
     public String getBrandName() {
         return brandName;
     }
     public void setBrandName(String brandName) {
         this.brandName = brandName;
     }
     public String getCompanyName() {
         return companyName;
     }
     public void setCompanyName(String companyName) {
         this.companyName = companyName;
     }
     public Integer getOrdered() {
         return ordered;
     }
     public void setOrdered(Integer ordered) {
         this.ordered = ordered;
     }
     public String getDescription() {
         return description;
     }
     public void setDescription(String description) {
         this.description = description;
     }
     public Integer getStatus() {
         return status;
     }
     public void setStatus(Integer status) {
         this.status = status;
     }
     @Override
     public String toString() {
         return "Brand{" +
                 "id=" + id +
                 ", brandName='" + brandName + '\'' +
                 ", companyName='" + companyName + '\'' +
                 ", ordered=" + ordered +
                 ", description='" + description + '\'' +
                 ", status=" + status +
                 '}';
     }
    }
    

空的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.xiaonan.mapper.BrandMapper">
</mapper>

空的mapper接口文件

package com.xiaonan.mapper;
public interface BrandMapper {

}

空的test测试类

package com.xiaonan.test;
public class MybatisTest {

}

以上文件准备好,开始代码部分

查询是最多的一个

查询

mapper接口文档

//直接遍历集合
List<Brand> selectAll();

mapper接口配置文档

    <!--
          数据库的字段和实体类的属性名称不一样时
            *起别名:对不一样的列明起别名
               *缺点每次都要定义一次别名
            *定义sql片段
            *resultMap
                1.定义<resultMap>标签
                2.在select标签中,使用resultMap属性替换resulttype属性
    -->

    <resultMap id="brandsesultMap" type="com.xiaonan.pojo.Brand">
        <!--
              id:唯一标识
              type:映射的类型,支持别名
              column:数据库表中字段的名字
              property:实体类中的名字,这里也就是别名
              result:完成字段的映射
        -->
        <result column="brand_name" property="brandName"/>
        <result column="company_name" property="companyName"/>
    </resultMap>
    <select id="selectAll" resultMap="brandsesultMap">
        select * from tb_brand;
    </select>

    <!-- sql片段-->
    <!--
    <sql id="brand_column">
      id,brand_name as brandName, company_name as companyName, ordered, description, status
    </sql>
    <select id="selectAll" resultType="com.xiaonan.pojo.Brand">
        select
             <include refid="brand_column"/>
        from tb_brand;
    </select>
    -->
    
    <!--起别名  -->
    <!--
    <select id="selectAll" resultType="com.xiaonan.pojo.Brand">
        select id,brand_name as brandName, company_name as companyName, ordered, description, status from  tb_brand;
    </select>
    -->
    
    <!-- 数据库字段和实体类属性名称不一样
    <select id="selectAll" resultType="com.xiaonan.pojo.Brand">
        select * from  tb_brand;
    </select>
    -->

测试类test

@Test
    public void selectAll() throws IOException {
        String resource = "mybatis-config.xml";
        InputStream inputStream = Resources.getResourceAsStream(resource);
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
        SqlSession sqlSession=sqlSessionFactory.openSession();
        BrandMapper brandMapper=sqlSession.getMapper(BrandMapper.class);
        List<Brand> list=brandMapper.selectAll();
        System.out.println(list);
        sqlSession.close();
    }

根据id查询

mapper接口

Brand selecyByid(int id);

mapper配置文档

<select id="selecyByid" resultMap="brandsesultMap">
        select * from tb_brand where id=#{id};
</select>

测试类

@Test
    public void selectById() throws IOException {
        String resource = "mybatis-config.xml";
        InputStream inputStream = Resources.getResourceAsStream(resource);
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
        SqlSession sqlSession=sqlSessionFactory.openSession();
        BrandMapper brandMapper=sqlSession.getMapper(BrandMapper.class);
        Brand brand=brandMapper.selecyByid(1);
        System.out.println(brand);
        sqlSession.close();
    }

条件查询

散装查询,对象查询,map集合查询
mapper接口文件

//List<Brand> selectByCondition(@Param("status") int status,@Param("companyName") String companyName,@Param("brandName") String brandName);

//List<Brand> selectByCondition(Brand brand);

List<Brand> selectByCondition(Map map);

mapper配置文件

<!-- 条件查询 -->
    <!--
    <select id="selectByCondition" resultMap="brandsesultMap">
            select *
            from tb_brand
            where status=#{status}
            and company_name like #{companyName}
            and brand_name like #{brandName}
    </select>
    -->

    <!-- 动态sql -->
    <!--
         *if:条件判断
            *test:逻辑表达式
         *问题:
             *恒等式:过度作用
             *where标签
    -->
    <!--
    <select id="selectByCondition" resultMap="brandsesultMap">
            select *
            from tb_brand
            where 1=1
            <if test="status !=null">
              and status=#{status}
            </if>
            <if test="companyName !='' and companyName !=null">
                and company_name like #{companyName}
            </if>
            <if test="brandName !=null and brandName!='' ">
                and brand_name like #{brandName}
            </if>
    </select>
    -->
    <select id="selectByCondition" resultMap="brandsesultMap">
        select *
        from tb_brand
        <where>
            <if test="status !=null">
                and status=#{status}
            </if>
            <if test="companyName !='' and companyName !=null">
                and company_name like #{companyName}
            </if>
            <if test="brandName !=null and brandName!='' ">
                and brand_name like #{brandName}
            </if>
        </where>
    </select>

测试类

    @Test
    public void selectByCondition() throws IOException {

        //散装
        int status =1;
        String companyName="华为";
        String brnadName="华为";

        companyName="%"+companyName+"%";
        brnadName="%"+brnadName+"%";

        //对象
        //Brand brand=new Brand();
        //brand.setStatus(1);
        //brand.setCompanyName("%华为%");
        //brand.setBrandName("%华为%");

        //map集合
        Map map=new HashMap();
        map.put("status",status);
        map.put("companyName",companyName);
        map.put("brandName",brnadName);


        String resource = "mybatis-config.xml";
        InputStream inputStream = Resources.getResourceAsStream(resource);
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
        SqlSession sqlSession=sqlSessionFactory.openSession();
        BrandMapper brandMapper=sqlSession.getMapper(BrandMapper.class);
        //List<Brand> list=brandMapper.selectByCondition(status,companyName,brnadName);
        //List<Brand> list=brandMapper.selectByCondition(1,"%华为%","%华为");

        //对象
        //List<Brand> list=brandMapper.selectByCondition(brand);

        //集合
        List<Brand> list=brandMapper.selectByCondition(map);
        System.out.println(list);
        sqlSession.close();
    }

添加

mapper接口文件

void add(Brand brand);

mapper配置文件

<insert id="add"  useGeneratedKeys="true" keyProperty="id">
        insert into tb_brand (brand_name,company_name,ordered,description,status)
        values (#{brandName},#{companyName},#{ordered},#{description},#{status});
</insert>

测试类

@Test
    public void add() throws IOException {
        //对象
        Brand brand=new Brand();
        brand.setStatus(1);
        brand.setCompanyName("测试");
        brand.setBrandName("测试");
        brand.setDescription("测试1111");
        brand.setOrdered(100);


        String resource = "mybatis-config.xml";
        InputStream inputStream = Resources.getResourceAsStream(resource);
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
        SqlSession sqlSession=sqlSessionFactory.openSession(true);
        BrandMapper brandMapper=sqlSession.getMapper(BrandMapper.class);
        brandMapper.add(brand);
        System.out.println("id===="+brand.getId());
        sqlSession.commit();
        
        sqlSession.close();
    }

删除

批量删除(介绍还是用配置文件)
mapper接口文件

void deleteByIds(@Param("ids")int [] ides);

mapper配置文件

<!--
        mybatis会将数组参数,封装为一个map集合
        *默认,array=数组
        *使用@Param注解改变map集合默认key的名称

-->

    <delete id="deleteByIds">
          delete from tb_brand where id
          in(
              <foreach collection="ids" item="id" separator=",">
                  #{id}
              </foreach>
          );
    </delete>

测试类

 @Test
    public void deleteByIds() throws IOException {
        int [] ids={4,5};

        String resource = "mybatis-config.xml";
        InputStream inputStream = Resources.getResourceAsStream(resource);
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
        SqlSession sqlSession=sqlSessionFactory.openSession(true);
        BrandMapper brandMapper=sqlSession.getMapper(BrandMapper.class);
        brandMapper.deleteByIds(ids);
        sqlSession.commit();
        sqlSession.close();
    }

重点!!!!!

在mybatis中不仅可以配置文件开发但是还可以注解开发,这里我介绍介绍不过不提倡注解开发,因为sql长了有点力不从心的感觉

注解开发

删除,根据id删除
mapper接口文件,这次用不到mapper配置文件了

@Delete("delete from tb_brand where id=#{id}")
void deleteByid(int id);

测试类

    //注解开发
    @Test
    public void deleteById() throws IOException {
        int id=6;
        String resource = "mybatis-config.xml";
        InputStream inputStream = Resources.getResourceAsStream(resource);
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
        SqlSession sqlSession=sqlSessionFactory.openSession(true);
        BrandMapper brandMapper=sqlSession.getMapper(BrandMapper.class);
        brandMapper.deleteByid(id);
        sqlSession.commit();
        sqlSession.close();
    }

注解开发,就上面俩文件,mapper接口文件还要一个测试类接口,没有mapper配置文件

增,删如果运行ok,但是数据库表中没有变化,那是没有提交数据,需要这样操作,在测试类里面这样修改下即可

//两种方法
//1:直接在这里就填写参数为true
//SqlSession sqlSession=sqlSessionFactory.openSession(true);
//2:这里不填写参数的话 那就在sql执行之后
// SqlSession sqlSession=sqlSessionFactory.openSession();
//sqlSession.commit();

数据库,直接复制到工具里面运行即可

-- 删除tb_brand表
drop table if exists tb_brand;
-- 创建tb_brand表
create table tb_brand
(
    -- id 主键
    id           int primary key auto_increment,
    -- 品牌名称
    brand_name   varchar(20),
    -- 企业名称
    company_name varchar(20),
    -- 排序字段
    ordered      int,
    -- 描述信息
    description  varchar(100),
    -- 状态:0:禁用  1:启用
    status       int
);
-- 添加数据
insert into tb_brand (brand_name, company_name, ordered, description, status)
values ('三只松鼠', '三只松鼠股份有限公司', 5, '好吃不上火', 0),
       ('华为', '华为技术有限公司', 100, '华为致力于把数字世界带入每个人、每个家庭、每个组织,构建万物互联的智能世界', 1),
       ('小米', '小米科技有限公司', 50, 'are you ok', 1);
       
SELECT * FROM tb_brand;

这是全部的东西,处理改,我忘记写了哈哈哈哈,不过大同小异,感觉不错的麻烦点个赞哈哈哈

文章全部是本人原创,请勿转发,谢谢配合,版权所有-南香香-你会喜欢我吗

评论区
头像
    头像
    南香香 .
      

    真认真,好样的