spingboot实现常规增删改查

启动类

java 复制代码
@SpringBootApplication
@MapperScan(basePackages = "com.example.jzdoffice.demos.mapper")
public class DemoApplication {
    public static void main(String[] args) {
        SpringApplication.run(DemoApplication .class, args);
    }
}

UserMapper

java 复制代码
package com.example.jzdoffice.demos.mapper;


import com.example.jzdoffice.demos.domain.User;
import org.apache.ibatis.annotations.Param;

import java.util.List;

public interface UserMapper {
    // 插入数据
    int insertSelective(User user);

    // 删除数据
    int deleteById(@Param("id") Long id);

    // 修改数据 批量更新加foreach
    int updateById(@Param("updated") User updated, @Param("id") Long id);

    // 查询所有数据
    List<User> selectByAll(User user);

    // 查询一条数据
    User SelectById(@Param("id") Long id);


    // 批量插入数据
    int insertList(@Param("list") List<User> list);

    //通过list集合实现批量删除
    int deleteByIds(@Param("ids") List<Integer> ids);

}

userMapper.xml

java 复制代码
<?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.jzdoffice.demos.mapper.UserMapper">
    <sql id="Base_Column_List">
        id,
        `name`,
        `password`,
        create_time,
        update_time
    </sql>
    <resultMap id="BaseResultMap" type="com.example.jzdoffice.demos.domain.User">
        <result column="id" property="id"/>
        <result column="name" property="name"/>
        <result column="password" property="password"/>
        <result column="create_time" property="createTime"/>
        <result column="update_time" property="updateTime"/>
    </resultMap>
    <!--  插入数据 关键字冲突,记得在字段加`` -->
    <insert id="insertSelective">
        INSERT INTO tb_user
        <trim prefix="(" suffix=")" suffixOverrides=",">
            <if test="id != null">
                `id`,
            </if>
            <if test="name != null">
                `name`,
            </if>
            <if test="password != null">
                `password`,
            </if>
            <if test="createTime != null">
                `create_time`,
            </if>
            <if test="updateTime != null">
                `update_time`
            </if>
        </trim>
        VALUES
        <trim prefix="(" suffix=")" suffixOverrides=",">
            <if test="id != null">
                #{id},
            </if>
            <if test="name != null">
                #{name},
            </if>
            <if test="password != null">
                #{password},
            </if>
            <if test="createTime != null">
                #{createTime},
            </if>
            <if test="updateTime != null">
                #{updateTime}
            </if>
        </trim>
    </insert>
    <!-- 删除数据 -->
    <delete id="deleteById">
        delete
        from tb_user
        where id = #{id}
    </delete>
    <!-- 修改数据 -->
    <update id="updateById">
        update tb_user
        <set>
            <if test="updated.id != null">
                id = #{updated.id},
            </if>
            <if test="updated.name != null">
                name = #{updated.name},
            </if>
            <if test="updated.password != null">
                password = #{updated.password},
            </if>
            <if test="updated.createTime != null">
                create_time = #{updated.createTime},
            </if>
            <if test="updated.updateTime != null">
                update_time = #{updated.updateTime},
            </if>
        </set>
        where id = #{id}
    </update>
    <!-- 查询所有数据-更据传递参数 -->
    <select id="selectByAll" resultMap="BaseResultMap">
        select
        <include refid="Base_Column_List"/>
        from tb_user
        <where>
            <if test="id != null">
                and id = #{id}
            </if>
            <if test="name != null">
                and `name` = #{name}
            </if>
            <if test="password != null">
                and `password` = #{password}
            </if>
            <if test="createTime != null">
                and create_time = #{createTime}
            </if>
            <if test="updateTime != null">
                and update_time = #{updateTime}
            </if>
        </where>
    </select>

    <!-- 查询一条数据 -->
    <select id="SelectById" resultMap="BaseResultMap">
        select
        <include refid="Base_Column_List"/>
        from tb_user
        where id = #{id}
    </select>
    <!-- 批量插入数据 -->
    <insert id="insertList">
        INSERT INTO tb_user(id,
                            name,
                            password,
                            create_time,
                            update_time)VALUES
        <foreach collection="list" item="element" index="index" separator=",">
            (#{element.id},
             #{element.name},
             #{element.password},
             #{element.createTime},
             #{element.updateTime})
        </foreach>
    </insert>
    <!--  批量删除  -->
    <delete id="deleteByIds">
        delete
        from tb_user where id in
        <foreach collection="ids" open="(" close=")" separator="," item="id">
            #{id}
        </foreach>
    </delete>
</mapper>

Service

java 复制代码
package com.example.jzdoffice.demos.service;

import java.util.Date;

import com.example.jzdoffice.demos.domain.User;
import com.example.jzdoffice.demos.mapper.UserMapper;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class UserService {
    @Autowired
    private UserMapper userMapper;

    public int insert(User user){
        return userMapper.insertSelective(user);
    }

    public int delete(Long id){
        return userMapper.deleteById(id);
    }

    public int update(User user){
        return userMapper.updateById(user,user.getId());
    }

    public List<User> selectAll(User user){
        //开启分页查询,当执行查询时,插件进行相关的sql拦截进行分页操作,返回一个page对象
        Page<User> page = PageHelper.startPage(1, 2);
        userMapper.selectByAll(user);
        System.out.println(page);// 只需要上面这两部就有我们需要的数据了 返回数据需要在封装
        return userMapper.selectByAll(user);
    }
    public User getUser(Long id){
        return userMapper.SelectById(id);
    }
}

UserController

java 复制代码
package com.example.jzdoffice.demos.controller;

import com.example.jzdoffice.demos.domain.User;
import com.example.jzdoffice.demos.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService;

    //插入用户信息
    @RequestMapping(value = "/insert", method = RequestMethod.POST)
    public String insert(@RequestBody User user) {
        int insert = userService.insert(user);
        String resp = insert > 0 ? Result.ok(insert) : Result.no();
        return resp;
    }

    //通过id删除用户信息
    @RequestMapping(value = "/delete/{id}", method = RequestMethod.GET)
    public String delete(@PathVariable Long id) {
        int result = userService.delete(id);
        if (result >= 1) {
            return "删除成功!";
        } else {
            return "删除失败!";
        }
    }


    //更改用户信息
    @RequestMapping(value = "/update", method = RequestMethod.POST)
    public String update(@RequestBody User user) {
        int result = userService.update(user);
        String resp = result > 0 ? Result.ok(result) : Result.no();
        return resp;
    }


    //查询所有用户的信息
    @RequestMapping(value = "/selectAll")
    @ResponseBody   //理解为:单独作为响应体,这里不调用实体类的toString方法
    public String listUser() {
        List<User> result = userService.selectAll(null);
        return Result.ok(result) ;
    }

    //通过id得到用户信息
    @RequestMapping(value = "/getUser/{id}", method = RequestMethod.GET)
    public String getUser(@PathVariable Long id) {
        User result = userService.getUser(id);
        return Result.ok(result) ;
    }

}

Result-响应格式

java 复制代码
package com.example.jzdoffice.demos.controller;

import com.alibaba.fastjson.JSONObject;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;

public class Result {

    public static String response(String code, Object data, String msg) {
        HashMap<String, Object> map = new HashMap<>();
        map.put("code", code);
        map.put("msg", msg);
        map.put("data", data);
        return JSONObject.toJSONString(map);
    }

    public static String ok(Object data) {
        return response("200", data,"成功");
    }
    public static String ok(Object data, String msg) {
        return response("200", data, msg == null ? "成功" : msg);
    }
    public static String no() {
        return response("400", "","失败");
    }


}
相关推荐
HBryce24几秒前
缓存-基础概念
java·缓存
一只爱打拳的程序猿15 分钟前
【Spring】更加简单的将对象存入Spring中并使用
java·后端·spring
杨荧17 分钟前
【JAVA毕业设计】基于Vue和SpringBoot的服装商城系统学科竞赛管理系统
java·开发语言·vue.js·spring boot·spring cloud·java-ee·kafka
minDuck19 分钟前
ruoyi-vue集成tianai-captcha验证码
java·前端·vue.js
为将者,自当识天晓地。37 分钟前
c++多线程
java·开发语言
daqinzl1 小时前
java获取机器ip、mac
java·mac·ip
激流丶1 小时前
【Kafka 实战】如何解决Kafka Topic数量过多带来的性能问题?
java·大数据·kafka·topic
Themberfue1 小时前
Java多线程详解⑤(全程干货!!!)线程安全问题 || 锁 || synchronized
java·开发语言·线程·多线程·synchronized·
让学习成为一种生活方式1 小时前
R包下载太慢安装中止的解决策略-R语言003
java·数据库·r语言
晨曦_子画1 小时前
编程语言之战:AI 之后的 Kotlin 与 Java
android·java·开发语言·人工智能·kotlin