我的编程空间,编程开发者的网络收藏夹
学习永远不晚

springboot 使用mybatis查询的示例代码

短信预约 -IT技能 免费直播动态提醒
省份

北京

  • 北京
  • 上海
  • 天津
  • 重庆
  • 河北
  • 山东
  • 辽宁
  • 黑龙江
  • 吉林
  • 甘肃
  • 青海
  • 河南
  • 江苏
  • 湖北
  • 湖南
  • 江西
  • 浙江
  • 广东
  • 云南
  • 福建
  • 海南
  • 山西
  • 四川
  • 陕西
  • 贵州
  • 安徽
  • 广西
  • 内蒙
  • 西藏
  • 新疆
  • 宁夏
  • 兵团
手机号立即预约

请填写图片验证码后获取短信验证码

看不清楚,换张图片

免费获取短信验证码

springboot 使用mybatis查询的示例代码

示例1

项目结构

代码controller中 UserController.java

package com.example.demo1110.controller;

import com.example.demo1110.entity.User;
import com.example.demo1110.service.UserService;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/user")
@CrossOrigin //解决跨域名获取
public class UserController {
    @Autowired
    private UserService userService;

    @GetMapping("/all")
    public List<User> getListUser(){
        return userService.listUser();
    }

    @GetMapping("/getId/id={id}")
    private User getId(@PathVariable("id") Integer id){
        return userService.queryById(id);
    }

    @PostMapping("/EditUser")
    private Map<String,Object> editUser(@RequestBody User user){
        System.out.println(user);
        HashMap<String,Object> map = new HashMap<>();
        try {
            userService.editUser(user);
            map.put("success",true);
            map.put("msg","修改员工成功");
        }catch (Exception e){
            e.printStackTrace();
            map.put("success",false);
            map.put("msg","修改员工失败");
        }
        return map;
    }

    @GetMapping("/getName")
    public List<User> getName(@Param("name") String name){
        return userService.queryByName(name);
    }

    @PostMapping("/addUser")
    public Map<String,Object> addUser(@RequestBody User user){
        HashMap<String,Object> map = new HashMap<>();
        try {
            userService.addUser(user);
            map.put("success",true);
            map.put("msg","添加员工成功");
        }catch (Exception e){
            e.printStackTrace();
            map.put("success",false);
            map.put("msg","添加用户失败");
        }
        return map;
    }

    @GetMapping("/deletUser/{id}")
    public  Map<String,Object> deletUser(@PathVariable("id") Integer id){
        System.out.println(id);
        HashMap<String,Object> map = new HashMap<>();
        try {
            userService.deleteUserById(id);
            map.put("success",true);
            map.put("msg","删除员工成功");
        }catch (Exception e){
            e.printStackTrace();
            map.put("success",false);
            map.put("msg","删除用户失败");
        }
        return map;
    }
}

entity中 User.java

package com.example.demo1110.entity;
import lombok.Data;
@Data
public class User {
    private int id;
    private String name;
    private int age;
    private String city;
}

mapper中 UserDao.java

package com.example.demo1110.mapper;
import com.example.demo1110.entity.User;
import org.apache.ibatis.annotations.Mapper;
import org.springframework.stereotype.Repository;
import java.util.List;
@Mapper
@Repository
public interface UserDao {
    //查询所有记录
    public List<User> listUser();
    //按id查询
    public User queryById(Integer id);
    //按姓名模糊查询
    public List<User> queryByName(String name);

    //保存用户
    public int addUser(User user);
    //根据员工id删除
    public int deleteUserById(Integer id);
    //修改员工信息
    public int editUser(User user);
}

service中 UserService.java

package com.example.demo1110.service;

import com.example.demo1110.entity.User;

import java.util.List;

public interface UserService {
    //查询所有记录
    public List<User> listUser();
    //按id查询
    public User queryById(Integer id);
    //按姓名模糊查询
    public List<User> queryByName(String name);

    //保存用户
    public boolean addUser(User user);

    //根据员工id删除
    public boolean deleteUserById(Integer id);

    //修改员工信息
    public boolean editUser(User user);
}

service impl中 UserServiceImpl.java

package com.example.demo1110.service.impl;

import com.example.demo1110.entity.User;
import com.example.demo1110.mapper.UserDao;
import com.example.demo1110.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class UserServiceImpl implements UserService {
    @Autowired
    private UserDao userDao;

    @Override
    public List<User> listUser() {
        return userDao.listUser();
    }

    @Override
    public User queryById(Integer id) {
        return userDao.queryById(id);
    }

    @Override
    public List<User> queryByName(String name) {
        return userDao.queryByName(name);
    }

    @Override
    public boolean addUser(User user) {
        int i = userDao.addUser(user);
        if(i > 0){
            return true;
        }else {
            return false;
        }
    }

    @Override
    public boolean deleteUserById(Integer id) {
        int i = userDao.deleteUserById(id);
        if(i > 0){
            return true;
        }else {
            return false;
        }
    }

    @Override
    public boolean editUser(User user) {
        int i = userDao.editUser(user);
        if(i > 0){
            return true;
        }else {
            return false;
        }
    }
    
}

主java文件 Demo1110Application.java

package com.example.demo1110;

import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@MapperScan("com.example.demo1110.mapper")
@SpringBootApplication
public class Demo1110Application {

    public static void main(String[] args) {
        SpringApplication.run(Demo1110Application.class, args);
    }

}

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.demo1110.mapper.UserDao">
    <select id="listUser" resultType="com.example.demo1110.entity.User">
        select * from user
    </select>

    <select id="queryById" parameterType="int" resultType="com.example.demo1110.entity.User">
        select * from user
        where id = #{id}
    </select>

    <select id="queryByName" parameterType="String" resultType="com.example.demo1110.entity.User">
        select * from user
        where username = #{name}
    </select>

    <insert id="addUser" parameterType="com.example.demo1110.entity.User">
        insert  into user values (#{id},#{username},#{age},#{city})
    </insert>

    <delete id="deleteEmployeeById" parameterType="int">
        delete from user where id = #{id}
    </delete>

    <update id="editEmployee" parameterType="com.example.demo1110.entity.User">
        update user
        set username = #{name},age = #{age},city = #{city}
        where id = #{id}
    </update>
</mapper>

application.yml

spring:
  datasource:
    url: jdbc:mysql://127.0.0.1:3306/mybatisdemo?characterEncoding=utf-8&useSSL=false
    username: root
    password: root
    driver-class-name: com.mysql.cj.jdbc.Driver
mybatis:
  mapper-locations: classpath*:mapper/查询所有记录
    public List<User> listUser();
    //按id查询
    public User queryById(Integer id);
    //按姓名模糊查询
    public List<User> queryByName(String name);

    //保存用户
    public int addUser(User user);
    //根据员工id删除
    public int deleteUserById(Integer id);
    //修改员工信息
    public int editUser(User user);*/
    
    List<User> findAllUser();


    
    User findUser(Integer id);


    
    void insertUser(User user);


    
    void deleteUser(Integer id);


    
    void updateUser(User user);
    

    void deleteUserByList(Integer[] ids);
}

service -> UserService.java

package com.example.demo1110.service;
import com.example.demo1110.entity.User;
import java.util.List;
public interface UserService {
    
    
    List<User> findAll();
    
    User findUserById(Integer id);
    
    void  insertUser(User user);
    
    void updateUser(User user);
    
    void deleteUser(Integer id);
    void deleteUserByList(Integer[] ids);
}

service impl ->UserServiceImpl.java

package com.example.demo1110.service.impl;
import com.example.demo1110.entity.User;
import com.example.demo1110.mapper.UserMapper;
import com.example.demo1110.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
@Service
public class UserServiceImpl implements UserService {
    
    @Autowired
    private UserMapper userMapper;
    @Override
    public User findUserById(Integer id) {
        return userMapper.findUser(id);
    }
    @Override
    public List<User> findAll() {
        return userMapper.findAllUser();
    }
    @Override
    public void insertUser(User user) {
        userMapper.insertUser(user);
    }
    @Override
    public void updateUser(User user) {
        userMapper.updateUser(user);
    }
    @Override
    public void deleteUser(Integer id) {
        userMapper.deleteUser(id);
    }
    @Override
    public void deleteUserByList(Integer[] ids) {
        userMapper.deleteUserByList(ids);
    }
}

controller ->UserController.java

package com.example.demo1110.controller;

import com.example.demo1110.entity.User;
import com.example.demo1110.service.UserService;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/user")
@CrossOrigin //解决跨域名获取
public class UserController {
    
    @Autowired
    private UserService userService;

    @GetMapping("/{id}")
    public User findUserByid(@PathVariable("id") Integer id){
        return userService.findUserById(id);
    }

    @GetMapping("/findAll")
    public List<User> findAll(){
        return userService.findAll();
    }

    @PostMapping("/add")
    // // post转实体对象   只能用raw   application/json格式传参   key-value跟实体对应 controller用@RequestBody
    public void insertUser(@RequestBody  User user){
        userService.insertUser(user);
    }

    @PutMapping("/update")
    public void updateUser(@RequestBody  User user){
        userService.updateUser(user);
    }

    @DeleteMapping("/delete/{id}")
    public void deleteUser(@PathVariable("id") Integer id){
        userService.deleteUser(id);
    }

    @DeleteMapping("/deleteBatch")
    public void deleteBatch(@RequestBody Integer[] ids){
        userService.deleteUserByList(ids);
    }
}

controller ->IndexController.java

package com.example.demo1110.controller;

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController

public class IndexController {
    @RequestMapping ("/")
    String home () {
        return "hello world!!";
    }
}

resources mapper -> 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.demo1110.mapper.UserMapper">
    <select id="listUser" resultType="com.example.demo1110.entity.User">
        select * from user
    </select>

    <select id="queryById" parameterType="int" resultType="com.example.demo1110.entity.User">
        select * from user
        where id = #{id}
    </select>

    <select id="queryByName" parameterType="String" resultType="com.example.demo1110.entity.User">
        select * from user
        where username = #{name}
    </select>

    <insert id="addUser" parameterType="com.example.demo1110.entity.User">
        insert  into user values (#{id},#{username},#{age},#{city})
    </insert>

    <delete id="deleteEmployeeById" parameterType="int">
        delete from user where id = #{id}
    </delete>

    <update id="editEmployee" parameterType="com.example.demo1110.entity.User">
        update user
        set username = #{name},age = #{age},city = #{city}
        where id = #{id}
    </update>
</mapper>-->
<mapper namespace="com.example.demo1110.mapper.UserMapper">
    <resultMap id="user" type="com.example.demo1110.entity.User">
        <id column="id" property="id"/>
        <result column="age" property="age"/>
        <result column="name" property="name"/>
    </resultMap>
    <select id="findUser" parameterType="int" resultMap="user">
        select * from user
        <where>
            <if test="_parameter!=null">
                and id = #{id}
            </if>
        </where>
    </select>

    <select id="findAllUser" resultMap="user">
        select * from user
    </select>

    <sql id="key">
        <trim suffixOverrides=",">
            <if test="id!=null">
                id,</if>
            <if test="name!=null">
                name,
            </if>

            <if test="age!=null">
                age,
            </if>
        </trim>
    </sql>
    <sql id="value">
        <trim suffixOverrides=",">
            <if test="id!=null">
                #{id},
            </if>
            <if test="name!=null">
                #{name},
            </if>
            <if test="age!=null">
                #{age},
            </if>
        </trim>
    </sql>

    <insert id="insertUser" parameterType="user">
        insert into user(<include refid="key"/>) values (<include refid="value"/>)
    </insert>

    <update id="updateUser" parameterType="user">
        UPDATE user
        <trim prefix="set" suffixOverrides=",">
            <if test="age!=null">age=#{age},</if>
            <if test="name!=null and name !=''">name=#{name},</if>
        </trim>
        WHERE id=#{id}

    </update>
    <delete id="deleteUser" parameterType="Integer">
        delete  from user where id = #{id}
    </delete>

    <delete id="deleteUserByList">
        delete  from user where id in
        <foreach collection="array" open="(" close=")" separator="," item="id">
            #{id}
        </foreach>
    </delete>

</mapper>

测试运行项目

http://127.0.0.1:8080/user/findAll

返回数据

[{"id":1,"name":"小明","age":18,"city":"深圳"},{"id":2,"name":"小明1","age":18,"city":"深圳"}]

源代码

链接: https://pan.baidu.com/s/11CVG6FyWrm67HR_ONVnVYw

提取码: tdfr

到此这篇关于springboot 使用mybatis查询的文章就介绍到这了,更多相关springboot  mybatis查询内容请搜索编程网以前的文章或继续浏览下面的相关文章希望大家以后多多支持编程网!

免责声明:

① 本站未注明“稿件来源”的信息均来自网络整理。其文字、图片和音视频稿件的所属权归原作者所有。本站收集整理出于非商业性的教育和科研之目的,并不意味着本站赞同其观点或证实其内容的真实性。仅作为临时的测试数据,供内部测试之用。本站并未授权任何人以任何方式主动获取本站任何信息。

② 本站未注明“稿件来源”的临时测试数据将在测试完成后最终做删除处理。有问题或投稿请发送至: 邮箱/279061341@qq.com QQ/279061341

springboot 使用mybatis查询的示例代码

下载Word文档到电脑,方便收藏和打印~

下载Word文档

猜你喜欢

java使用es查询的示例代码

众所周知,elasticsearch简称es,它是基于基于Lucene的搜索服务器。它提供了一个分布式多用户能力的全文搜索引擎,基于RESTful web接口。Elasticsearch是用Java开发的,并作为Apache许可条款下的开放
2023-05-30

mybatis-plus查询源码的示例分析

这篇文章主要介绍mybatis-plus查询源码的示例分析,文中介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们一定要看完!配置详情pom.xmldependency> com.baomidou
2023-06-29

Mybatis查询记录条数的实例代码

这几天在学SSM框架,今天在SSM框架中根据某个条件查询MySQL数据库中的记录条数,碰到一些问题,记录一下User.xml