NIIT实训(春季 git + Maven + Springboot + MyBatis + Vue)第三次

文章介绍了MyBatis中使用Map传递参数进行查询,如何进行模糊查询,以及resultMap、where标签、update和trim标签的灵活运用。还提到了根据数组查询、批量插入和代码复用的方法,展示了如何提高开发效率和SQL语句的灵活性。
摘要由CSDN通过智能技术生成

DAY7

使用map传递参数

   <select id="selectUserByMap" resultType="User">

           select * from tb_user where username=#{username}
            and password=#{password}
            and phone=#{phone}
            and email=#{email}
    </select>

mapper文件
    User selectUserByMap(Map ma);

    @Test
    public void testSelectUserByMap(){
        Map map = new HashMap<>();
        map.put("username", "123");
        map.put("password", "123");
        map.put("phone", "123");
        map.put("email","123");
        User user = userMapper.selectUserByMap(map);
        System.out.println("多个简单类型,testSelectUserByUsernamePassword = "
                + user);
    }

$ 和

    <select id="selectByField" resultType="com.example.demomybatis.pojo.User">

        select *
        from tb_user
        where ${colName} = #{colVal}

    </select>

   User selectByField(String colName, String colVal);

    @Test
    public void testSelectByField(){
    
		//防止SQL注入
        String colName = "1=1 or username";
        String colName = "username";
        String colVal = "123";
        //User user = userMapper.selectByField(colName, colVal);
        List<User> users = userMapper.selectByFieldForList(colName, colVal);
    }

模糊查询:

 where username like concat('%', #{username}, '%')

DAY8

resultMap

<!--    resultMap:开发人员自定义返回列与Java实体对象属性的映射-->
<!--    1、指定java实体对象类型,通过type属性进行指定;可以类完全限定名称或别名-->
<!--    2、可以映射数据库表列名与实体类属性名;-->
<!--    3-一对一映射、一对多映射-->
<!--    id属性: Mapper 映射文件中的唯一标识,-->
<!--    <id>元素:建立主键的映射关系-->
<!--    <result>元素:非主键的映射-->

    <resultMap id="BaseUserResultMap" type="User">
        <!-- 列与实体类属性名的映射 -->
        <id column="id" property="id"></id>
        <result column="username" property="username"></result>
        <result column="password" property="password"></result>
        <result column="phone" property="phone"></result>
        <result column="email" property="email"></result>
        <result column="age" property="age"></result>
        <result column="gmt_create" property="gmtCreate"></result>
        <result column="login_time" property="loginTime"></result>
    </resultMap>

    <select id="selectByUserForResultMap" resultMap="BaseUserResultMap">

        SELECT
          `id`,
          `username`,
          `password`,
          `age`,
          `phone`,
          `email`,
          `gmt_create`,
          `login_time`
        from tb_user
        where username=#{username}
    </select>

    @Test
    public void testSelectByUserForResultMap(){
        User paramUser = new User( ) ;
        paramUser.setUsername( "123");

        User user = userMapper.selectByUserForResultMap(paramUser);
        System.out.println("练习使用 resultMap, user= " + user);

        user = userMapper.selectByUser(paramUser);
        System.out.println("练习使用 resultType, user= " + user);
    }

where的使用

他会自己判断后面有没有语句。并且判断是否添加and

 <select id="selectUserByUsernamePasswordForWhere" resultType="com.example.demomybatis.pojo.User">

        select * from tb_user
        <where>

            <if test="username != null">
                and username = #{username}
            </if>

            <if test="password != null">
                and password=#{password}
            </if>

        </where>

    @Test
    public void testSelectUserByUsernamePasswordForWhere(){
        String userName = "123";
        String password = "123";
       // List<User> users = userMapper.selectUserByUsernamePasswordForWhere(userName, password);
        //select * from tb_user where username=? and password=?
       // List<User> users = userMapper.selectUserByUsernamePasswordForWhere(null, password);
        //select * from tb_user WHERE password=?
        //List<User> users = userMapper.selectUserByUsernamePasswordForWhere(userName, null);
        //select * from tb_user WHERE username = ?
        List<User> users = userMapper.selectUserByUsernamePasswordForWhere(null, null);
       // select * from tb_user
        System.out.println(users);
    }

update

  • 自动在要修改的第一个字段之前添加SET关键字
  • 去掉最后一个要修改字段后的连接符( , )。
<update id="updateUser" parameterType="User">

        update `tb_user`
        <set>
            `username` = #{username},
            <if test="password!=null">
                password=#{password}
            </if>
        </set>
        where `id` = #{id}

    </update>

trim

mybatis的trim标签一般用于去除sql语句中多余的and关键字,逗号,或者给sql语句前拼接 “where“、“set“以及“values(“ 等前缀,或者添加“)“等后缀,可用于选择性插入、更新、删除或者条件查询等操作。

    <select id="selectUserByUsernamePasswordForTrim" resultType="com.example.demomybatis.pojo.User">

        select * from tb_user
        <trim prefix="where" prefixOverrides="and|or">
            <if test="username!=null">
                and username=#{username}
            </if>
            <if test="password!=null">
                and password=#{password}
            </if>
        </trim>

    </select>


    <update id="updateUserForTrim" parameterType="User">

        update `tb_user`
        <trim prefix="SET" suffixOverrides=",">
            `username`=#{username},
            <if test="password!=null">
                password=#{password}
            </if>
        </trim>
        where `id`=#{id}
    </update>

根据数组查询

<!--根绝数组查询多个用户记录-->
    <select id="selectByIds" resultType="com.example.demomybatis.pojo.User">

        select * from tb_user where id
        <foreach collection="ids"  item="id" open="in(" separator="," close=")">
            #{id}
        </foreach>

    </select>

批量插入:

 <insert id="batchInsert">
        insert into `tb_user`
         (`username`,
             `password`,
             `age`,
             `phone`,
             `email`,
             `gmt_create`,
             `login_time`)
        VALUES
        <foreach collection="list" item="user" open="(" separator="),(" close=")">
            #{user.username}, #{user.password}, #{user.age}, #{user.phone}, 'eamil', null,null
        </foreach>


    </insert>

代码复用


    <!--公共代码部分-->
    <sql id="selectUserAll">
        select `id`, `username`,`password`,`age`,`phone`,`email`,`gmt_create`,`login_time` from tb_user
    </sql>


引用:
   <select id="selectListByCondition" resultType="com.example.demomybatis.pojo.User">

        <include refid="selectUserAll"></include>
        where username like concat('%', #{username}, '%')

    </select>

DAY10

缓存

加快访问速度

DAY11

项目结构:
在这里插入图片描述
Controller

package cn.niit.hospital.controller;

import cn.niit.hospital.entity.domain.User;
import cn.niit.hospital.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.annotations.Delete;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;

/**
 * @Description: 用户控制器
 * @Author: tang_meng
 * @CreateTime: 2023/3/16 16:23
 */
@RestController
@Slf4j
public class UserController {



    @Autowired
    private UserService userService;


    /**
     * @Description: 接口一, 根据某个id查询用户
     * @Author: tang_meng
     * @CreateTime: 2023/3/20 8:39
     * @param: id
     * @return: cn.niit.hospital.entity.domain.User
     **/
    @RequestMapping("/user/{id}")
    public User getById(@PathVariable("id") Long id){
        User user = userService.getUserById(id);
        return user;
    }

    /**
     * @Description: 接口二: 查询用户列表接口
     * @Author: tang_meng
     * @CreateTime: 2023/3/20 8:42
     * @param: 封装着查询(多个)条件的用户对象
     * @return: java.util.List<cn.niit.hospital.entity.domain.User>
     **/
    @GetMapping("/user")
    public List<User> list(User user){
        log.info("接受得到的参数 {}  "+user);
        List<User> users = userService.getListByUser(user);
        return users;
    }

    /**
     * @Description: 接口三: 新增接口
     * @Author: tang_meng
     * @CreateTime: 2023/3/20 8:44
     * @return: java.lang.String
     **/
    @PostMapping("/user")
    public Integer add(@RequestBody User user){
        log.info("接收到的参数: {} "+user);
        int rows = userService.addUser(user);
        return rows;
    }

    /**
     * @Description: 接口四: 更新接口
     * @Author: tang_meng
     * @CreateTime: 2023/3/20 8:45
     * @param: user
     * @return: java.lang.String
     **/
    @PutMapping("/user")
    public String update(User user){
        log.info("接收到的参数: {} "+user);
        int rows = userService.updateUser(user);
        if(rows == 1)
            return "更新成功";
        else return "更新失败!";
    }

   // @RequestMapping(value = "/user/{id}", method = RequestMethod.DELETE)
    @DeleteMapping("/user/{id}") //和上面等价,推荐这个
    public String delete(@PathVariable("id") Long id){
        int rows = userService.deleteUser(id);
        return "ol";
    }


}

UserServiceImpl

package cn.niit.hospital.service.impl;

import cn.niit.hospital.entity.domain.User;
import cn.niit.hospital.mapper.UserMapper;
import cn.niit.hospital.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @Description: 用户服务实现类
 * @Author: tang_meng
 * @CreateTime: 2023/3/17 9:08
 */
@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;

    /**
     * @Description: 查询用户根据ID
     * @Author: tang_meng
     * @CreateTime: 2023/3/17 9:22
     * @param: id
     * @return: cn.niit.hospital.entity.domain.User
     **/
    @Override
    public User getUserById(Long id) {
        return userMapper.getUserById(id);
    }

    /**
     * @Description: 根据封装条件查看用户列表
     * @Author: tang_meng
     * @CreateTime: 2023/3/20 9:36
     * @param: user
     * @return: java.util.List<cn.niit.hospital.entity.domain.User>
     **/
    @Override
    public List<User> getListByUser(User user) {
        return userMapper.selectListByUser(user);
    }

    /**
     * @Description: 添加用户
     * @Author: tang_meng
     * @CreateTime: 2023/3/20 10:55
     * @param: user
     * @return: int
     **/
    @Override
    public int addUser(User user) {
        user.setStatus(0);
        user.setDelFlag(0);
        user.setCreateUserId(0L);
        user.setCreateUserName("系统管理员");
        return userMapper.insertUser(user);
    }

    @Override
    public int updateUser(User user) {
        user.setCreateUserId(0L);
        user.setCreateUserName("系统管理员");
        return userMapper.updateUser(user);
    }

    @Override
    public int deleteUser(Long id) {
       // return userMapper.deleteUserById(id); 物理删除
        User user=new User();
        user.setId(id);
        user.setDelFlag(1);
        user.setUpdateUserId(1L);
        user.setUpdateUserName("超级系统管理员");
        return userMapper.deleteByUser(user);   //逻辑删除

    }

}

UserMapper.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 将 XxxMapper.java 接口类与 XxxMapper.xml 做映射 -->
<mapper namespace="cn.niit.hospital.mapper.UserMapper">

    <sql id="selectAllSQL">

SELECT
          `id`,
          `phone`,
          `id_card`,
          `user_name`,
          `password`,
          `birthday`,
          `sex`,
          `status`,
          `del_flag`,
          `create_user_id`,
          `create_user_name`,
          `gmt_create`,
          `update_user_id`,
          `update_user_name`,
          `gmt_update`

    </sql>
    <insert id="insertUser">
        INSERT INTO `tb_userone`
            (`phone`,
             `id_card`,
             `user_name`,
             `password`,
             `birthday`,
             `sex`,
             `status`,
             `del_flag`,
             `create_user_id`,
             `create_user_name`,
             `gmt_create`)
        VALUES (#{phone},
                #{idCard},
                #{userName},
                #{password},
                #{birthday},
                #{sex},
                #{status},
                #{delFlag},
                #{createUserId},
                #{createUserName},
                now() );
    </insert>
    <update id="updateUser">
        update `tb_userone`
        set `phone` = #{phone},
         `id_card` = #{idCard},
         `user_name` = #{userName},
         `password` = #{password},
         `birthday` = #{birthday},
         `sex` = #{sex},
         `update_user_id` = #{updateUserId},
         `update_user_name` = #{updateUserName},
         `gmt_update` = now()
        where `id` = #{id}

    </update>
    <delete id="deleteUserById">
        delete from `tb_userone` where `id`=#{id}
    </delete>


    <update id="deleteByUser">
    update `tb_userone`
    set `del_flag` = #{delFlag},
    `update_user_id` = #{updateUserId},
    `update_user_name` = #{updateUserName},
    `gmt_update` = now()
    where `id` = #{id}
    </update>

    <select id="selectListByUser" resultType="cn.niit.hospital.entity.domain.User">

        <include refid="selectAllSQL"></include>
        from tb_userone
        <where>
            <if test="phone!=null and phone !=''">
            and phone = #{phone}
            </if>
            <if test="userName!=null and userName!=''">
                and user_name like '%' #{userName} '%'
            </if>

        </where>

    </select>





    <select id="getUserById" resultType="cn.niit.hospital.entity.domain.User">

        select * from tb_user where id = #{id}

    </select>

</mapper>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值