MyBatis练习

1,目标:加深对MyBatis的使用(xml)

  • 查询
    • 查询所有数据
    • 查询详情
    • 条件查询
  • 添加
  • 修改
    • 修改全部字段
    • 修改动态字段
  • 删除
    • 删除一个
    • 批量删除

2、环境准备

        2.1创建并插入一些数据

-- 创建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);

        2.2 创建maven项目并创建对应的包和实体类

util包为工具类用来获取sqlSession对象

package com.Lu.util;

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 java.io.IOException;
import java.io.InputStream;

//从 XML 中构建 SqlSessionFactory
public class UtilsMybatis {
    static SqlSessionFactory sqlSessionFactory;
    static {
        //获取SqlSessionFactory对象
        try {
            String resource = "mybatis-config.xml";
            InputStream inputStream =Resources.getResourceAsStream(resource);
            sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    //获取SqlSession操作对象 执行数据库
    public static SqlSession getSqlSession(){
        return sqlSessionFactory.openSession();
    }
}

         

 2.3依赖导入 mysql mybatis 和junit测试

        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.47</version>
        </dependency>
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.5.2</version>
        </dependency>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
            <scope>test</scope>
        </dependency>

2.4编写mybatis-config.xml文件

<?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>
    <!--    核心配置文件-->
    <typeAliases>
    <!-- 设置返回类型为类名 -->
        <package name="com.Lu.pojo"/>
    </typeAliases>
    <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://localhost:3306/mybatis?useSSL=false"/>
                <property name="username" value="root"/>
                <property name="password" value="root"/>
            </dataSource>
        </environment>
    </environments>
    <!--  mappers 通过name属性指定mapper接口所在的包名  通过resource属性引入classpath路径的相对资源-->
    <mappers>
            <mapper resource="Mapper.xml"/>
    </mappers>
</configuration>

3、编写代码

        3.1在Mapper接口中编写方法(CRUD操作)

        public interface TestMybatis {
            public List<Brand> ShowData();
        }

        3.2编写xml文件

<?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">

<!--namespace =绑定接口-->
<mapper namespace="com.Lu.Mapper.TestMybatis">
    <!--    这里的id为方法名 resultTYpe为返回的类型 parameterType参数类型-->
    <select id="ShowData" resultType="Brand">
        SELECT * FROM tb_brand;
    </select>
</mapper>

        3.3编写测试类

public class Test {
    @org.junit.Test
    public void ShowData(){
        //1、获取sqlSession对象
        SqlSession sqlSession = UtilsMybatis.getSqlSession();
        //2、获取接口
        TestMybatis mapper = sqlSession.getMapper(TestMybatis.class);
        //3、获取事务
        List<Brand> brands = mapper.ShowData();
        for (Brand b:brands) {
            System.out.println(b);
        }
        //4、关闭资源
        sqlSession.close();
    }
}

        结果:

Brand{id=1, brandName='null', companyName='null', ordered=5, description='好吃不上火', status=0}
Brand{id=2,
brandName='null', companyName='null', ordered=100, description='华为致力于把数字世界带入每个人、每个家庭、每个组织,构建万物互联的智能世界', status=1}
Brand{id=3,
brandName='null', companyName='null', ordered=50, description='are you ok', status=1}

         分析结果:由于在实体类Brand中的一些属性和数据库里的属性名不一致导致属性不一致的结果为null

 

        解决:将xml中查询结果返回对象由resultType改为resultMap:

<resultMap id="Brands" type="Brand">
    <result property="brandName" column="brand_name"/>
    <result property="companyName" column="company_name"/>
</resultMap>
<select id="ShowData" resultMap="Brands">
    SELECT * FROM tb_brand;
</select>

Brand{id=1, brandName='三只松鼠', companyName='三只松鼠股份有限公司', ordered=5, description='好吃不上火', status=0}
Brand{id=2, brandName='华为', companyName='华为技术有限公司', ordered=100, description='华为致力于把数字世界带入每个人、每个家庭、每个组织,构建万物互联的智能世界', status=1}
Brand{id=3, brandName='小米', companyName='小米科技有限公司', ordered=50, description='are you ok', status=1}
 

其中 resultMap为查询结果的返回的集合

        resultMap:主要由了两个标签 <result>和 <association>

        <result >用于普通属性 <result  property="" column=""/>

        <association>Java对象 <association property="ds" column="v" javaMap=""/>

        作用:用于解决数据库的字段和Java对象属性名不一致

        property:为Java对象中的属性 column:数据库中字段的名称 javaMap:java对象名称

 3.4 根据id查询

        3.4.1 在interface中增加getBrandById()方法

                public List<Brand> getBrandById(int id);

        3.4.2 编写xml文件

                parameter:传入的参数

<resultMap id="Brands" type="Brand">

        <result property="brandName" column="brand_name"/>
        <result property="companyName" column="company_name"/>
 </resultMap>
<select id="getBrandById" resultMap="Brands" parameterType="_int">
        SELECT * FROM `tb_brand` where id=#{id};
    </select>

        3.4.3 编写测试类与结果

@org.junit.Test
    public void getBrandById(){
        SqlSession sqlSession = UtilsMybatis.getSqlSession();
        TestMybatis mapper = sqlSession.getMapper(TestMybatis.class);
        List<Brand> brandById = mapper.getBrandById(1);
        System.out.println(brandById);
        sqlSession.close();
    }

        [Brand{id=1, brandName='三只松鼠', companyName='三只松鼠股份有限公司', ordered=5,         description='好吃不上火', status=0}]

        3.5 根据id修改信息其他信息

                3.5.1 在interface中加入UpdateById()方法

//根据id修改其他信息 传入一个集合装id和要修改的内容
    public void UpdateById(Map<String,Object> map);

                3.5.2 编写xml文件

<!--   根据id修改其他信息 传入一个集合装id和要修改的内容-->
    <update id="UpdateById" parameterType="map">
        UPDATE tb_brand SET ordered=${order} where id =${id}
    </update>

                3.5.3 编写测试类与结果

@org.junit.Test
    public void UpdateById(){
        SqlSession sqlSession = UtilsMybatis.getSqlSession();
        TestMybatis mapper = sqlSession.getMapper(TestMybatis.class);
        Map<String,Object> map=new HashMap<>();
        map.put("order","20");
        map.put("id",1);
        mapper.UpdateById(map);
        sqlSession.close();
    }

                分析结果:Java代码运行成功但是数据库里没有变化 原因没有提交事务(在执行修改,插入,删除时要提交事务)在UpdateById()方法中加上sqlSession.commit() 为了避免每次都要提交事务可以在回去sqlSession对象中的sqlSessionFactory.openSession()方法;加上truesqlSessionFactory.openSession(true) 即可解决问题

 

         3.6插入数据

                3.6.1 编写interface接口 更具brand对象和Map集合传入要插入的对象 

//插入数据 以集合的方式传入要插入的数据
    public void InsertMapperMap(Map<String,Object> map);
    //插入数据 以对象的方式传入要插入的数据
    public void InsertMapperBrand(Brand brand);

                3.6.2 编写xml文件

<!--   插入数据1 传入集合 -->
    <insert id="InsertMapperMap" parameterType="map">
        insert into tb_brand value (#{id},#{tbName},#{companyName},#{ordered},#{description},#{status})
    </insert>
    <!--   插入数据1 传入对象 -->
    <insert id="InsertMapperBrand" parameterType="brand">
        insert into tb_brand value (#{id},#{brandName},#{companyName},#{ordered},#{description},#{status})
    </insert>

                3.6.3 测试类 结果

    @org.junit.Test
    public void InsertMapperMap(){
        SqlSession sqlSession = UtilsMybatis.getSqlSession();
        TestMybatis mapper = sqlSession.getMapper(TestMybatis.class);
        HashMap<String, Object> map = new HashMap<>();
        map.put("id",4);
        map.put("tbName","时尚小米");
        map.put("companyName","小米");
        map.put("ordered",1);
        map.put("description","满足用户的大部分需求");
        map.put("status",1);
        mapper.InsertMapperMap(map);
        sqlSession.close();
    }
    @org.junit.Test
    public void InsertMapperBrand(){
        SqlSession sqlSession = UtilsMybatis.getSqlSession();
        TestMybatis mapper = sqlSession.getMapper(TestMybatis.class);
        Brand brand = new Brand();
        brand.setId(5);
        brand.setBrandName("小米s");
        brand.setCompanyName("小米");
        brand.setOrdered(3);
        brand.setDescription("满足用户的全部需求");
        brand.setStatus(1);
        mapper.InsertMapperBrand(brand);
        sqlSession.close();
    }
}

          3.7删除数据

                3.7.1 编写intertface 根据id进行删除数据

//删除数据 根据id删除
    public void DeleteMapperById(int id);

                3.7.2 编写xml文件

<!--  根据id删除数据  -->
    <delete id="DeleteMapperById" parameterType="_int">
        delete from tb_brand where id =#{id}
    </delete>

                3.7.3 测试与结果

   @org.junit.Test
    public void DeleteMapperById(){
        SqlSession sqlSession = UtilsMybatis.getSqlSession();
        TestMybatis mapper = sqlSession.getMapper(TestMybatis.class);
        mapper.DeleteMapperById(5);
        sqlSession.close();
    }

         4、模糊查询 like

                 4.1编写interface接口

    //模糊查询like #{name} 
    public List<Brand>SelectMapperByLike(Map<String,Object> map);
    
    //模糊查询like ${name} 
    public List<Brand>SelectMapperByLikes(Map<String,Object> map);

                4.2编写xml文件

<!--  模糊查询like #{name}  -->
    <select id="SelectMapperByLike" resultMap="Brands" parameterType="map">
        select * from tb_brand where brand_name like "%"#{name}"%"
    </select>
<!--  模糊查询like ${name}  -->
    <select id="SelectMapperByLikes" resultMap="Brands" parameterType="map">
        select * from tb_brand where brand_name like "%${name}%"
    </select>

                4.3测试与结果

@org.junit.Test
    public void SelectMapperByLike(){
        SqlSession sqlSession = UtilsMybatis.getSqlSession();
        TestMybatis mapper = sqlSession.getMapper(TestMybatis.class);
        Map<String,Object> map=new HashMap<>();
        map.put("name","米");
        List<Brand> brands = mapper.SelectMapperByLike(map);
        for(Brand u:brands){
            System.out.println(u);
        }
        sqlSession.close();
    }
    @org.junit.Test
    public void SelectMapperByLikes(){
        SqlSession sqlSession = UtilsMybatis.getSqlSession();
        TestMybatis mapper = sqlSession.getMapper(TestMybatis.class);
        Map<String,Object> map=new HashMap<>();
        map.put("name","米");
        List<Brand> brands = mapper.SelectMapperByLike(map);
        for(Brand u:brands){
            System.out.println(u);
        }
        sqlSession.close();
    }

                两者区别:${}相当于JDBC中的字符拼接 存在sql注入问题

                                #{}相当于JDBC中的?占位符

        5、分页查询

                5.1编写interface接口

//分页查询limit
    public List<Brand>SelectMapperByLimit(Map<String,Object> map);

                5.2编写xml文件

<!--  分页查询limit  -->
    <select id="SelectMapperByLimit" parameterType="map" resultMap="Brands">
        SELECT * FROM tb_brand limit #{start},#{index}
    </select>

                5.3测试与结果

@org.junit.Test
    public void SelectMapperByLimit(){
        SqlSession sqlSession = UtilsMybatis.getSqlSession();
        TestMybatis mapper = sqlSession.getMapper(TestMybatis.class);
        Map<String,Object> map=new HashMap<>();
        map.put("start",0);
        map.put("index",1);
        List<Brand> brands = mapper.SelectMapperByLimit(map);
        for(Brand u:brands){
            System.out.println(u);
        }
        sqlSession.close();
    }

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值