Mybatis功能详细案例

完成品牌增删改查操作:

准备环境

数据库表tb_brand

#删除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),
	#状态
	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;

在这里插入图片描述

实体类Brand

public class Brand {
    private Integer id;

    private String brandName;

    private  String companyName;

    private  Integer ordered;

    private  String description;

    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 +
                '}';
    }
}

路径情况
在这里插入图片描述

测试用例
创建一个测试类

在这里插入图片描述

安装MyBatisX插件
简介
MybatisX是一款基于IDEA的快速开发插件,为效率而生
主要功能:
XML和接口方法 相互跳转
根据接口方法生成statement

安装
点击install 重启IDEA就可以
在这里插入图片描述

项目结构
在resources下创建一个与mapper包相同层次的目录结构,并在里面定义与mapper包下接口名相同的sql映射文件
在这里插入图片描述
将包内的映射器接口实现全部注册为映射器
在这里插入图片描述
避免出现打印出来的数据为null值情况 使用resultMap完成结果映射
在这里插入图片描述


查询

查询所有结果

编写接口方法:Mapper接口
在BrandMapper接口中创建,可以借助MybatisX自动生成statement

 List<Brand> selectAll();

编写SQL语句
Mybatis自助生成 我们只需编写SQL语句

<select id="selectAll" resultType="network.hylnetwork.pojo.Brand" >
        select * from tb_brand;
  </select>

因为数据库列名和Brand实例名不同,我们使用resultMap 只需把resultType替换成resultMap填写上resultMapid

 <select id="selectAll" resultMap="brandResultMap">
        select * from tb_brand;
  </select>

执行测试方法

    @Test
    public  void  testSelectAll() throws IOException {

        String resource = "mybatis-config.xml";
        InputStream inputStream = Resources.getResourceAsStream(resource);
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
        SqlSession sqlSession = sqlSessionFactory.openSession();
        BrandMapper mapper = sqlSession.getMapper(BrandMapper.class);
        List<Brand> brands = mapper.selectAll();
        System.out.println(brands);
        sqlSession.close();

    }

结果
在这里插入图片描述

提示:这里描述项目中遇到的问题:

例如:数据传输过程中数据不时出现丢失的情况,偶尔会丢失一部分数据
APP 中接收数据代码:

@Override
	public void run() {
		bytes = mmInStream.read(buffer);
		mHandler.obtainMessage(READ_DATA, bytes, -1, buffer).sendToTarget();
	}

查看详情

编写接口方法
在BrandMapper接口

  Brand selectId(int id);

编写SQL语句:SQL映射文件
在BrandMapper.xml
参数占位符
#{}会将其替换为?防止SQL注入
${}存在SQL注入

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

执行测试方法

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

结果
在这里插入图片描述


条件查询

多条件查询

编写接口方法
因为我们的数据都属于同一个类,参数使用Brand类型就可(有三种方法,使用@Param、使用类型接收、使用Map接收)

    List<Brand> selectByCondition(Brand brand);

编写SQL语句:SQL映射文件
//进行多条件查询 需求分析:我们有多重条件筛选查询的需求,比如我们要查询状态,公司名字和品牌名字
//用户可能不知道公司和品牌的全名 想要输入部分内容就可以进行查询 可以用模糊查询实现
//多条件查询这些条件的关系应该是同时成立才可以
//假设我们接收到了三个参数,我们需要对其中的需要进行模糊查询的参数进行处理 “% %”

<select id="selectByCondition" resultMap="brandResultMap">
        select * from tb_brand
        where
            status = #{status}
            and company_name like #{companyName}
            and brand_name like #{brandName}
    </select>

执行测试方法
假设用户提交的数据是 状态为1 两个关键词都输入了华为

    @Test
    public void  testSelectByConddition() throws IOException {
        //接收参数
        int status = 1;
        String companyName = "华为";
        String brandName = "华为";
        //因为模糊查询 我们要对接收的参数进行处理
        companyName = "%"+companyName+"%";
        brandName = "%"+brandName+"%";
        //封装对象
        Brand brand = new Brand();
        brand.setStatus(status);
        brand.setBrandName(brandName);
        brand.setCompanyName(companyName);
        String resource = "mybatis-config.xml";
        InputStream inputStream = Resources.getResourceAsStream(resource);
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
        SqlSession sqlSession = sqlSessionFactory.openSession();
        BrandMapper mapper = sqlSession.getMapper(BrandMapper.class);
        List<Brand> brands = mapper.selectByCondition(brand);
        System.out.println(brands);
    }

结果
在这里插入图片描述

多条件动态条件查询

SQL语句会随着用户的输入或外部条件的变化而变化,我们成为动态SQL

//比如有三个查询框 用户没有填写id只填写了公司品牌使用静态的查询就无法完成需求了

编写接口方法

 List<Brand> selectByCondition(Brand brand);

编写SQL语句:SQL映射文件
判断选择项是否为null或者’’

<select id="selectByCondition" resultMap="brandResultMap">
        select *
        from tb_brand
        <where>
            <if test="status != null">
                and  status = #{status}
            </if>
            <if test="companyName !=null and companyName !=''">
                and company_name like #{companyName}
        </if>
            <if test="brandName !=null and brandName !=''">
                and brand_name like #{brandName}
            </if>
        </where>
        </select>

执行测试方法
//用户只输入了id和公司名称的情况

  @Test
    public void  testSelectByConddition() throws IOException {
        //接收参数
        int status = 1;
        String companyName = "华为";
     //   String brandName = "华为";
        //因为模糊查询 我们要对接收的参数进行处理
        companyName = "%"+companyName+"%";
     //   brandName = "%"+brandName+"%";
        //封装对象
        Brand brand = new Brand();
        brand.setStatus(status);
      //  brand.setBrandName(brandName);
        brand.setCompanyName(companyName);
        String resource = "mybatis-config.xml";
        InputStream inputStream = Resources.getResourceAsStream(resource);
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
        SqlSession sqlSession = sqlSessionFactory.openSession();
        BrandMapper mapper = sqlSession.getMapper(BrandMapper.class);
        List<Brand> brands = mapper.selectByCondition(brand);
        System.out.println(brands);
    }

结果:一样可以查询到数据
在这里插入图片描述

在这里插入图片描述

单条件动态条件查询

//从多个条件中选择一个  例:一个下拉框用户有多种选择进行搜索
//choose(when,otherwise):选择,类似于Java中的switch语句

例图
在这里插入图片描述

编写接口方法

   List<Brand> selectByConditionSingle(Brand brand);

编写SQL语句:SQL映射文件

 <select id="selectByConditionSingle" resultMap="brandResultMap">
        select * from tb_brand
        where 
        <choose>
            <when test="status !=null">
                status = #{status}
            </when>
            <when test="companyName !=null and companyName !=''">
                company_name like #{companyName}
            </when>
            <when test="brandName !=null and brandName !=''">
                brand_name like #{brandName}
            </when>
            <otherwise>
                1 =1
            </otherwise>
        </choose>
    </select>

执行测试方法

添加:

正常添加

编写接口方法

    void  add(Brand brand);

编写SQL语句:SQL映射文件

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

执行测试方法

@Test
    public void add() throws IOException {
        //接收参数
        String companyName = "博导";
        String brandName = "bodao";
        String description = "手机中的战斗机";
        int ordered = 100;
        //封装对象
        Brand brand = new Brand();
        brand.setBrandName(brandName);
        brand.setCompanyName(companyName);
        brand.setOrdered(ordered);
        brand.setDescription(description);
        String resource = "mybatis-config.xml";
        InputStream inputStream = Resources.getResourceAsStream(resource);
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
        SqlSession sqlSession = sqlSessionFactory.openSession();
        //获取代理对象
        BrandMapper mapper = sqlSession.getMapper(BrandMapper.class);
        //执行方法
        mapper.add(brand);
//        Integer id = brand.getId();
//        System.out.println(id);
//mybatis中事务管理中 把自动提交关闭了 需要手动提交才能生效
        //事务提交
        sqlSession.commit();
        sqlSession.close();
    }

结果
添加成功
在这里插入图片描述

主键返回

//在数据添加成功后,需要获取插入数据库数据的主键的值
//因为用户在添加的时候id是自动生成的不需要用户输入,当有获得id需求的时候

只需要设置useGeneratedKeys和 keyProperty即可

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

使用Brand的getId方法就可以得到主键值了
例如:Handler 发送消息有两种方式,分别是 Handler.obtainMessage()Handler.sendMessage(),其中 obtainMessage 方式当数据量过大时,由于 MessageQuene 大小也有限,所以当 message 处理不及时时,会造成先传的数据被覆盖,进而导致数据丢失。


修改:

修改全部字段

编写接口方法

    void  update(Brand brand);

编写SQL语句:SQL映射文件

    <update id="update">
        update tb_brand
        set brand_name = #{brandName},
        company_name=#{companyName},
        ordered = #{ordered},
        description =#{description},
        status = #{status}
        where id = #{id};
    </update>

执行测试方法
将id=4的数据修改

   @Test
    public void update() throws IOException {
        //接收参数
        String companyName = "iphone";
        String brandName = "苹果13";
        String description = "土豪金";
        int ordered = 133;
        int status = 1;
        int id = 4;
        //因为模糊查询 我们要对接收的参数进行处理
        //封装对象
        Brand brand = new Brand();
//        brand.setStatus(status);
        brand.setBrandName(brandName);
        brand.setCompanyName(companyName);
        brand.setOrdered(ordered);
        brand.setDescription(description);
        brand.setStatus(status);
        brand.setId(id);
        String resource = "mybatis-config.xml";
        InputStream inputStream = Resources.getResourceAsStream(resource);
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
        SqlSession sqlSession = sqlSessionFactory.openSession();
//获取代理对象
        BrandMapper mapper = sqlSession.getMapper(BrandMapper.class);
        //执行方法
        mapper.update(brand);
//mybatis中事务管理中 把自动提交关闭了 需要手动提交才能生效
        //事务提交
        sqlSession.commit();
        sqlSession.close();
    }

结果
在这里插入图片描述

修改动态字段

//静态修改的方式如果用户只修改一部分数据,其他没有修改的数据会被修改成null值
//动态修改可以将用户没有修改的部分保持不变

编写接口方法

    void  update(Brand brand);

编写SQL语句:SQL映射文件

    <update id="update">
        update tb_brand
        <set>
        <if test="brandName !=null and brandName!=''">
            brand_name = #{brandName},
        </if>
        <if test="companyName!=null and companyName !=''">
            company_name=#{companyName},
        </if>
        <if test="ordered !=null">
            ordered = #{ordered},
        </if>
        <if test="description !=null and description != ''">
            description =#{description},
        </if>
        <if test="status !=null">
            status = #{status}
        </if>
        </set>
        where id = #{id};
    </update>

执行测试方法
在普通修改方法的基础上 只修改了companyName和 description和stqatus
在这里插入图片描述

可以看到除了我们修改的数据其他数据没有被改变
在这里插入图片描述

提示:这里填写该问题的具体解决方案:

例如:新建一个 Message 对象,并将读取到的数据存入 Message,然后 mHandler.obtainMessage(READ_DATA, bytes, -1, buffer).sendToTarget();换成 mHandler.sendMessage()

删除:

删除一个

编写接口方法

 void deleteById(int id);

编写SQL语句:SQL映射文件

  <delete id="deleteById">
        delete  from tb_brand where id =#{id}
    </delete>

执行测试方法
删除id为4的数据

    @Test
    public void deleteTest() throws IOException {
        String resource = "mybatis-config.xml";
        InputStream inputStream = Resources.getResourceAsStream(resource);
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
        SqlSession sqlSession = sqlSessionFactory.openSession();
//获取代理对象
        BrandMapper mapper = sqlSession.getMapper(BrandMapper.class);
        //执行方法
        mapper.deleteById(4);
//mybatis中事务管理中 把自动提交关闭了 需要手动提交才能生效
        //事务提交
        sqlSession.commit();
        sqlSession.close();
    }

结果:id4的数据被删除
在这里插入图片描述

批量删除

编写接口方法

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

编写SQL语句:SQL映射文件

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

执行测试方法

    @Test
    public void BatchDeleteTest() throws IOException {
        String resource = "mybatis-config.xml";
        InputStream inputStream = Resources.getResourceAsStream(resource);
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
        SqlSession sqlSession = sqlSessionFactory.openSession();
//获取代理对象
        BrandMapper mapper = sqlSession.getMapper(BrandMapper.class);
        //执行方法
        int[] nums = {5,6};
        mapper.deleteByIds(nums);
//mybatis中事务管理中 把自动提交关闭了 需要手动提交才能生效
        //事务提交
        sqlSession.commit();
        sqlSession.close();
    }

结果id为5,6的数据被删除
在这里插入图片描述

根据黑马程序复习和知识点总结 视频连接

  • 2
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
你好!这里是一个Spring Boot集成MyBatis的简单项目实例。首先,你需要在你的pom.xml文件中添加以下依赖: ```xml <dependencies> <!-- Spring Boot --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <!-- MyBatis --> <dependency> <groupId>org.mybatis.spring.boot</groupId> <artifactId>mybatis-spring-boot-starter</artifactId> <version>2.2.0</version> </dependency> <!-- MySQL Connector --> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>8.0.23</version> </dependency> </dependencies> ``` 接下来,创建一个数据库表和对应的实体类。假设我们要创建一个用户表,表名为`user`,包含`id`和`name`两个字段。创建一个名为`User`的Java类,包含与数据库表字段对应的属性和相应的getter/setter方法。 ```java public class User { private Long id; private String name; // 省略getter/setter方法 } ``` 然后,在`src/main/resources`目录下创建一个名为`application.properties`的文件,并配置数据库相关信息。 ```properties # 数据库连接配置 spring.datasource.url=jdbc:mysql://localhost:3306/mydatabase?useSSL=false&serverTimezone=UTC spring.datasource.username=root spring.datasource.password=your_password # MyBatis配置 mybatis.mapper-locations=classpath:mappers/*.xml mybatis.type-aliases-package=com.example.demo.model ``` 接着,在`src/main/java/com/example/demo`目录下创建一个名为`UserMapper`的接口,定义与数据库操作相关的方法。 ```java @Mapper public interface UserMapper { @Select("SELECT * FROM user") List<User> getAllUsers(); @Select("SELECT * FROM user WHERE id = #{id}") User getUserById(Long id); @Insert("INSERT INTO user(name) VALUES (#{name})") @Options(useGeneratedKeys = true, keyProperty = "id") void insertUser(User user); @Update("UPDATE user SET name = #{name} WHERE id = #{id}") void updateUser(User user); @Delete("DELETE FROM user WHERE id = #{id}") void deleteUser(Long id); } ``` 最后,在`src/main/java/com/example/demo`目录下创建一个名为`DemoApplication`的类,并添加`@SpringBootApplication`注解。 ```java @SpringBootApplication public class DemoApplication { public static void main(String[] args) { SpringApplication.run(DemoApplication.class, args); } } ``` 这就是一个简单的Spring Boot集成MyBatis的项目实例。你可以根据需要进行扩展和修改。希望对你有所帮助!

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值