14 springboot 整合mybaits(中)

环境的搭建参考上一篇

1mybatis的增删改查,模糊查询,聚合函数

1.1编写:

1.1.1编写dao层

package com.example.mybaits.dao;

import com.example.mybaits.domain.Category;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;

import java.util.List;

//@Mapper
public interface CategoryMapper {

    @Select("select * from mall_category where id =#{id}")
    Category findOne(@Param("id") Integer id);

    Category queryByid(Integer id);

    void save(Category category);

    int updateCategory(Category category);

    void deleteCategoryById(Integer id);

    List<Category> findByName(String categoryName);

    int count();
}

1.1.1xml

<?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.example.mybaits.dao.CategoryMapper">

    <!--
    parameterType 属性: 代表参数的类型,因为我们要传入的是一个类的对象,所以类型就写类的全名称。
    sql 语句中使用#{}字符:
    它代表占位符,相当于原来 jdbc 部分所学的?,都是用于执行语句时替换实际的数据。
    具体的数据是由#{}里面的内容决定的。 #{}中内容的写法:
    由于我们保存方法的参数是 一个 User 对象,此处要写 User 对象中的属性名称。
    它用的是 ognl 表达式。 ognl 表达式:
    它是 apache 提供的一种表达式语言,全称是:
    Object Graphic Navigation Language 对象图导航语言

    它是按照一定的语法格式来获取数据的。 语法格式就是使用 #{对象.对象}的方式
    #{user.username}它会先去找 user 对象,然后在 user 对象中找到 username 属性,并调用 getUsername()方法把值取出来。但是我们在 parameterType 属性上指定了实体类名称,所以可以省略 user. 而直接写 username。
    -->
    <select id="queryByid" resultType="com.example.mybaits.domain.Category">

        select * from mall_category where id = #{id}
    </select>


    <insert id="save" parameterType="com.example.mybaits.domain.Category">

        insert into mall_category(parent_id,name,status,sort_order)
        values(#{parentId},#{name},#{status},#{sortOrder})

    </insert>


    <update id="updateCategoryById" parameterType="com.example.mybaits.domain.Category">
      update mall_category set parent_id=#{parentId},name=#{name},status=#{status},
         sort_order=#{sortOrder} where id=#{id}



    </update>

    <delete id="deleteCategoryById" parameterType="Integer">

        delete from mall_category where id = #{id}
    </delete>



    <!--
    我们在配置文件中没有加入%来作为模糊查询的条件,所以在传入字符串实参时,就需要给定模糊查询的标 识%。配置文件中的#{username}也只是一个占位符,所以 SQL 语句显示为“?”。
    List<Category> list = categoryMapper.findByName("%a%");
    -->
    <select id="findByName" parameterType="String" resultType="com.example.mybaits.domain.Category">

        select * from mall_category where name like #{name}
    </select>


    <!--不叫resultType="int"  会报错-->
    <select id="count" resultType="int">

        select count(*) from mall_category
    </select>

</mapper>

1.1.2验证

package com.example.mybaits.dao;



import com.example.mybaits.domain.Category;
import com.google.gson.Gson;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import org.junit.runner.RunWith;

import java.util.List;


@RunWith(SpringRunner.class)
@SpringBootTest
public class CategoryMapperTest {

    @Autowired
    private CategoryMapper categoryMapper;

    @Test
    public void findOne() {
        Gson gson = new Gson();
        Category one = categoryMapper.findOne(100001);
        System.out.print(gson.toJson(one));

    }

    @Test
    public void queryByid() {
        Gson gson = new Gson();
        Category one = categoryMapper.queryByid(100001);
        System.out.print(gson.toJson(one));

    }

    @Test
    public void save() {
        Gson gson = new Gson();
       Category category=new Category();
       category.setParentId(0);
       category.setName("aa");
       category.setStatus(true);
       category.setSortOrder(1);
       categoryMapper.save(category);


    }

    @Test
    public void update() {
        Gson gson = new Gson();
        Category category=new Category();
        category.setId(100031);
        category.setParentId(1);
        category.setName("aab");
        category.setStatus(true);
        category.setSortOrder(1);
        categoryMapper.updateCategory(category);


    }


    @Test
    public void delete() {

        categoryMapper.deleteCategoryById(100031);

    }

    //模糊查询

    @Test
    public void findByName() {
        Gson gson = new Gson();
        List<Category> list = categoryMapper.findByName("%a%");
        for (Category category:list) {
              System.out.print(gson.toJson(category));
        }


    }

    //使用聚合函数
    @Test
    public void count() {
        int count = categoryMapper.count();
        System.out.print(count);


    }

}

1.2 新增用户后,同时还要返回当前新增用户的 id 值

新增用户后,同时还要返回当前新增用户的 id 值,因为 id 是由数据库的自动增长来实现的,所以就相 当于我们要在新增后将自动增长 auto_increment 的值返回。

<insert id="saveUser" parameterType="USER">
 <!-- 配置保存时获取插入的 id -->
<selectKey keyColumn="id" keyProperty="id" resultType="int"> select last_insert_id();
</selectKey>
insert into user(username,birthday,sex,address) values(#{username},#{birthday},#{sex},#{address})
</insert >
  
 

1.3#{}和${}的区别

#{}表示一个占位符号
通过#{}可以实现 preparedStatement 向占位符中设置值,自动进行 java 类型和 jdbc 类型转换,
#{}可以有效防止 sql 注入。 #{}可以接收简单类型值或 pojo 属性值。 如果 parameterType 传输单个简单类 型值,#{}括号中可以是 value 或其它名称。
表 示 拼 接 s q l 串 通 过 {}表示拼接 sql 串 通过 sql{}可以将parameterType 传入的内容拼接在sql中且不进行jdbc类型转换, 可 以 接 收 简 单 类 型 值 或 p o j o 属 性 值 , 如 果 p a r a m e t e r T y p e 传 输 单 个 简 单 类 型 值 , {}可以接收简 单类型值或 pojo 属性值,如果 parameterType 传输单个简单类型值, pojoparameterType{}括号中只能是 value。

2Mybatis 的参数深入

2.1parameterType 配置参数

开发中通过 pojo 传递查询条件 ,查询条件是综合的查询条件,不仅包括用户查询条件还包括其它的查 询条件(比如将用户购买商品信息也作为查询条件),这时可以使用包装对象传递输入参数。
Pojo 类中包含 pojo。
需求:根据用户名查询用户信息,查询条件放到 QueryVo 的 category 属性中。

2.1.1封装对象QueryVo

package com.example.mybaits.domain;

import java.io.Serializable;

public class QueryVo implements Serializable {

    private  Category category;

    public QueryVo(Category category) {

        this.category = category;
    }

    public QueryVo() {
    }

    public Category getCategory() {
        return category;
    }

    public void setCategory(Category category) {
        this.category = category;
    }
}

2.1.2dao层

Category findByQueryVo(QueryVo queryVo);

2.1.2xml

 <select id="findByQueryVo"  parameterType="com.example.mybaits.domain.QueryVo" resultType="com.example.mybaits.domain.Category">

         select * from mall_category where name like #{category.name}
</select>

2.1.3测试

 @Test
    public void findByQueryVo() {
        QueryVo vo=new QueryVo();
        Category category=new Category();
        category.setName("%a%");
        vo.setCategory(category);
        Category byQueryVo = categoryMapper.findByQueryVo(vo);
    }

2.2resultType 配置结果类型

resultMap 标签可以建立查询的列名和实体类的属性名称不一致时建立对应关系。从而实现封装。
在 select 标签中使用 resultMap 属性指定引用即可。同时 resultMap 可以实现将查询结果映射为复杂类
型的 pojo,比如在查询结果映射对象中包括 pojo 和 list 实现一对一查询和一对多查

<!-- 建立 User 实体和数据库表的对应关系
type 属性:指定实体类的全限定类名
id 属性:给定一个唯一标识,是给查询 select 标签引用用的。 

id 标签:用于指定主键字段
result 标签:用于指定非主键字段
column 属性:用于指定数据库列名
property 属性:用于指定实体类属性名称

-->
<resultMap type="com.itheima.domain.User" id="userMap"> <id column="id" property="userId"/>
<result column="username" property="userName"/>
<result column="sex" property="userSex"/>
<result column="address" property="userAddress"/>
<result column="birthday" property="userBirthday"/> </resultMap>
<select id="findAll" resultMap="userMap">
 select * from user
</select>

3 动态sql

数据库表:

CREATE TABLE `user` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `username` varchar(32) NOT NULL COMMENT '用户名称',
  `birthday` datetime DEFAULT NULL COMMENT '生日',
  `sex` char(1) DEFAULT NULL COMMENT '性别',
  `address` varchar(256) DEFAULT NULL COMMENT '地址',
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=49 DEFAULT CHARSET=utf8

3.1if标签

我们根据实体类的不同取值,使用不同的 SQL 语句来进行查询。比如在 id 如果不为空时可以根据 id 查询, 如果 username 不同空时还要加入用户名作为条件。这种情况在我们的多条件组合查询中经常会碰到。

注意:标签的 test 属性中写的是对象的属性名,如果是包装类的对象要使用 OGNL 表达式的写法。 另外要注意 where 1=1 的作用~!

<select id="findUserByCondition" resultMap="userMap" parameterType="user">
        select * from user where 1=1
        <if test="userName != null">
          and username = #{userName}
        </if>
        <if test="userSex != null and username != ''">
            and sex = #{userSex}
        </if>
    </select>

3.2 where标签

为了简化上面where 1=1的条件拼装,我们可以采用标签来简化开发。

  <select id="findUserByCondition" resultMap="userMap" parameterType="com.example.mybaits.domain.User">
        select * from user
        <where>
            <if test="userName != null and username != ''">
                and username = #{userName}
            </if>
            <if test="userSex != null and userSex != ''">
                and sex = #{userSex}
            </if>
        </where>
    </select>

3.2 foreach标签

传入多个 id 查询用户信息,用下边两个 sql 实现:
SELECT * FROM USERS WHERE username LIKE ‘%张%’ AND (id =10 OR id =89 OR id=16) SELECT * FROM USERS WHERE username LIKE ‘%张%’ AND id IN (10,89,16)
这样我们在进行范围查询时,就要将一个集合中的值,作为参数动态添加进来。 这样我们将如何进行参数的传递?

   <!-- 根据queryvo中的Id集合实现查询用户列表 -->
    <select id="findUserInIds" resultMap="userMap" parameterType="com.example.mybaits.domain.QueryUserVo">
        <include refid="defaultUser"></include>
        <where>
            <if test="ids != null and ids.size()>0">
                <foreach collection="ids" open="and id in (" close=")" item="uid" separator=",">
                    #{uid}
                </foreach>
            </if>
        </where>
    </select>

标签用于遍历集合,它的属性:
collection:代表要遍历的集合元素,注意编写时不要写#{}
open:代表语句的开始部分
close:代表结束部分
item:代表遍历集合的每个元素,生成的变量名
sperator:代表分隔符

4 上述代码已上传

https://download.csdn.net/download/Insist___/12143832

Spring Boot 是一个快速开发框架,MyBatis 是一款优秀的基于 Java 的持久层框架。在 Spring Boot 使用 MyBatis 可以极大地提高开发效率和运行效率。 具体步骤如下: 1. 引入 MyBatis 和 MyBatis-SpringBoot-Starter 依赖。 2. 配置数据源和 MyBatis。 3. 编写实体类和映射文件。 4. 编写 DAO 层接口和 SQL 语句。 5. 在 Service 层调用 DAO 层接口。 6. 在 Controller 层调用 Service 层方法,返回结果给前端。 示例代码: 1. 引入依赖: ``` <dependency> <groupId>org.mybatis.spring.boot</groupId> <artifactId>mybatis-spring-boot-starter</artifactId> <version>2.2.0</version> </dependency> ``` 2. 配置数据源和 MyBatis: ``` spring.datasource.driver-class-name=com.mysql.jdbc.Driver spring.datasource.url=jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf-8&serverTimezone=UTC spring.datasource.username=root spring.datasource.password=root mybatis.mapper-locations=classpath:mapper/*.xml ``` 3. 编写实体类和映射文件: 实体类: ``` public class User { private Long id; private String name; private Integer age; // 省略 getter 和 setter 方法 } ``` 映射文件: ``` <?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.example.demo.dao.UserMapper"> <resultMap id="BaseResultMap" type="com.example.demo.entity.User"> <id column="id" property="id" /> <result column="name" property="name" /> <result column="age" property="age" /> </resultMap> <select id="selectByPrimaryKey" resultMap="BaseResultMap" parameterType="java.lang.Long"> select * from user where id = #{id} </select> </mapper> ``` 4. 编写 DAO 层接口和 SQL 语句: ``` public interface UserMapper { User selectByPrimaryKey(Long id); } ``` 5. 在 Service 层调用 DAO 层接口: ``` @Service public class UserServiceImpl implements UserService { @Autowired private UserMapper userMapper; @Override public User getUserById(Long id) { return userMapper.selectByPrimaryKey(id); } } ``` 6. 在 Controller 层调用 Service 层方法,返回结果给前端: ``` @RestController public class UserController { @Autowired private UserService userService; @GetMapping(value = "/user/{id}") public User getUserById(@PathVariable Long id) { return userService.getUserById(id); } } ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值