SpringBoot MyBatis 增删改查 demo

avatar 2020年12月22日22:59:08 0 963 views

晚上花了一个小时帮一个朋友写了一个作业,实现用户、商品、订单、订单详情的一个需求

  1. 查询id为1,3,5的用户信息,以json格式返回数据;
  2. 查询用户id为1的订单信息
  3. 查询单价大于3500的商品信息,以json格式返回数据
  4. 查询id为3的用户订单明细

实现以上需求,我发现还有很多新人不太会,给大家分享一下

表不是我建的,他们老师给的,如果不规范谅解

完整代码地址:https://github.com/saysky/SpringBoot_MyBatis_CURD

代码结构

核心代码

下面以 User 类为示例

1. pom.xml

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.1.6.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.example</groupId>
    <artifactId>SpringBoot_MyBatis_CURD</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>SpringBoot_MyBatis_CURD</name>
    <description>Demo project for Spring Boot</description>

    <properties>
        <java.version>1.8</java.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>

        <!--下面是mybatis和MySQL和spring整合必须的-->
        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>2.1.0</version>
        </dependency>

        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>8.0.11</version>
        </dependency>


    </dependencies>
    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>

 

2.application.properties

spring.datasource.url=jdbc:mysql://localhost:3306/springboot-shop?serverTimezone=Asia/Shanghai&characterEncoding=utf8&useSSL=false
spring.datasource.username=root
spring.datasource.password=123456
spring.datasource.driverClassName=com.mysql.cj.jdbc.Driver

mybatis.mapper-locations=classpath*:/mapper/*.xml
mybatis.type-aliases-package=com.example.entity

 

3.entity 包

User.java

package com.example.entity;

import java.io.Serializable;

/**
 * 用户实体类
 *
 * @author example
 * @since 2020-12-22 20:38:07
 */
public class User implements Serializable {
    private static final long serialVersionUID = 793367122288190673L;
    
    private Integer id;
    /**
    * 用户名称
    */
    private String username;
    /**
    * 生日
    */
    private Object birthday;
    /**
    * 性别
    */
    private String sex;
    /**
    * 地址
    */
    private String address;


    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public Object getBirthday() {
        return birthday;
    }

    public void setBirthday(Object birthday) {
        this.birthday = birthday;
    }

    public String getSex() {
        return sex;
    }

    public void setSex(String sex) {
        this.sex = sex;
    }

    public String getAddress() {
        return address;
    }

    public void setAddress(String address) {
        this.address = address;
    }

}

 

4.dao 包

UserDao.java

package com.example.dao;


import com.example.entity.User;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;

import java.util.List;

/**
 * 用户表数据库访问层
 *
 * @author example
 * @since 2020-12-22 20:38:07
 */
@Mapper
public interface UserDao {

    /**
     * 通过ID查询单条数据
     *
     * @param id 主键
     * @return 实例对象
     * @author example
     */
    User queryById(Integer id);

    /**
     * 通过ID查询多条数据
     *
     * @param ids 主键集合
     * @return 实例对象
     * @author example
     */
    List<User> queryByIds(List<Integer> ids);


    /**
     * 查询指定行数据
     *
     * @param offset 查询起始位置
     * @param limit  查询条数
     * @return 对象列表
     * @author 1813004427刘泉青
     */
    List<User> queryAllByLimit(@Param("offset") int offset, @Param("limit") int limit);


    /**
     * 通过实体作为筛选条件查询
     *
     * @param user 实例对象
     * @return 对象列表
     * @author 1813004427刘泉青
     */
    List<User> queryAll(User user);

    /**
     * 新增数据
     *
     * @param user 实例对象
     * @return 影响行数
     */
    int insert(User user);

    /**
     * 修改数据
     *
     * @param user 实例对象
     * @return 影响行数
     */
    int update(User user);

    /**
     * 通过主键删除数据
     *
     * @param id 主键
     * @return 影响行数
     */
    int deleteById(Integer id);

}

 

4. mapper xml 目录

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">
<mapper namespace="com.example.dao.UserDao">

    <resultMap type="com.example.entity.User" id="UserMap">
        <result property="id" column="id" jdbcType="INTEGER"/>
        <result property="username" column="username" jdbcType="VARCHAR"/>
        <result property="birthday" column="birthday" jdbcType="OTHER"/>
        <result property="sex" column="sex" jdbcType="VARCHAR"/>
        <result property="address" column="address" jdbcType="VARCHAR"/>
    </resultMap>

    <!--查询单个-->
    <select id="queryById" resultMap="UserMap">
        select
          id, username, birthday, sex, address
        from user
        where id = #{id}
    </select>

    <!--查询多个-->
    <select id="queryByIds" resultMap="UserMap">
        select
          id, username, birthday, sex, address
        from user
        <where>
            id IN (
                <foreach collection="list" item="id" separator=",">
                    #{id}
                </foreach>
            )
        </where>
    </select>


    <!--查询指定行数据-->
    <select id="queryAllByLimit" resultMap="UserMap">
        select
          id, username, birthday, sex, address
        from user
        limit #{offset}, #{limit}
    </select>

    <!--通过实体作为筛选条件查询-->
    <select id="queryAll" resultMap="UserMap">
        select
        id, username, birthday, sex, address
        from user
        <where>
            <if test="id != null">
                and id = #{id}
            </if>
            <if test="username != null and username != ''">
                and username = #{username}
            </if>
            <if test="birthday != null">
                and birthday = #{birthday}
            </if>
            <if test="sex != null and sex != ''">
                and sex = #{sex}
            </if>
            <if test="address != null and address != ''">
                and address = #{address}
            </if>
        </where>
    </select>

    <!--新增所有列-->
    <insert id="insert" keyProperty="id" useGeneratedKeys="true">
        insert into user(username, birthday, sex, address)
        values (#{username}, #{birthday}, #{sex}, #{address})
    </insert>

    <!--通过主键修改数据-->
    <update id="update">
        update user
        <set>
            <if test="username != null and username != ''">
                username = #{username},
            </if>
            <if test="birthday != null">
                birthday = #{birthday},
            </if>
            <if test="sex != null and sex != ''">
                sex = #{sex},
            </if>
            <if test="address != null and address != ''">
                address = #{address},
            </if>
        </set>
        where id = #{id}
    </update>

    <!--通过主键删除-->
    <delete id="deleteById">
        delete from user where id = #{id}
    </delete>

</mapper>

5. service 包

UserService.java

package com.example.service;

import com.example.entity.User;

import java.util.List;

/**
 * 用户表服务接口
 *
 * @author example
 * @since 2020-12-22 20:38:07
 */
public interface UserService {

    /**
     * 通过ID查询单条数据
     *
     * @param id 主键
     * @return 实例对象
     * @author example
     */
    User queryById(Integer id);


    /**
     * 通过ID查询多条数据
     *
     * @param ids 主键集合
     * @return 实例对象
     * @author example
     */
    List<User> queryByIds(List<Integer> ids);

}

6.service impl 包

UserServiceImpl.java

package com.example.service.impl;


import com.example.entity.User;
import com.example.dao.UserDao;
import com.example.service.UserService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

/**
 * 用户表服务实现类
 *
 * @author example
 * @since 2020-12-22 20:38:07
 */
@Service("userService")
public class UserServiceImpl implements UserService {
    @Resource
    private UserDao userDao;

    /**
     * 通过ID查询单条数据
     *
     * @param id 主键
     * @return 实例对象
     * @author example
     */
    @Override
    public User queryById(Integer id) {
        return this.userDao.queryById(id);
    }


    @Override
    public List<User> queryByIds(List<Integer> ids) {
        return this.userDao.queryByIds(ids);
    }

}

 

7 controller 包

UserController.java

package com.example.controller;


import com.example.entity.User;
import com.example.service.UserService;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;

/**
 * 用户表控制层
 *
 * @author example
 * @since 2020-12-22 20:38:07
 */
@Controller
@RequestMapping("/user")
public class UserController {
    /**
     * 服务对象
     */
    @Resource
    private UserService userService;

    /**
     * 根据id查询
     * 访问 http://localhost:8080/user/findById?id=1 进行测试
     *
     * @param id 主键
     * @return 单条数据
     */
    @GetMapping("/findById")
    @ResponseBody
    public User findById(@RequestParam("id") Integer id) {
        return this.userService.queryById(id);
    }

    /**
     * 根据用户ID集合查询
     * 访问 http://localhost:8080/user/findByIds?ids=1&ids=3&ids=5 进行测试
     *
     * @author example
     *
     * @param ids 主键
     * @return 单条数据
     */
    @GetMapping("/findByIds")
    @ResponseBody
    public List<User> findByIds(@RequestParam("ids") List<Integer> ids) {
        return this.userService.queryByIds(ids);
    }

}

 

  • 微信
  • 交流学习,有偿服务
  • weinxin
  • 博客/Java交流群
  • 资源分享,问题解决,技术交流。群号:590480292
  • weinxin
avatar

发表评论

avatar 登录者:匿名
可以匿名评论或者登录后台评论,评论回复后会有邮件通知

  

已通过评论:0   待审核评论数:0