springboot 使用mybatis查询的示例代码

示例1

项目结构

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 getListUser(){
        return userService.listUser();
    }

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

    @PostMapping("/EditUser")
    private Map editUser(@RequestBody User user){
        System.out.println(user);
        HashMap 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 getName(@Param("name") String name){
        return userService.queryByName(name);
    }

    @PostMapping("/addUser")
    public Map addUser(@RequestBody User user){
        HashMap 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 deletUser(@PathVariable("id") Integer id){
        System.out.println(id);
        HashMap 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 listUser();
    //按id查询
    public User queryById(Integer id);
    //按姓名模糊查询
    public List 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 listUser();
    //按id查询
    public User queryById(Integer id);
    //按姓名模糊查询
    public List 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 listUser() {
        return userDao.listUser();
    }

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

    @Override
    public List 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




    

    

    

    
        insert  into user values (#{id},#{username},#{age},#{city})
    

    
        delete from user where id = #{id}
    

    
        update user
        set username = #{name},age = #{age},city = #{city}
        where id = #{id}
    

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/*Mapper.xml
  type-aliases-package: com.example.demo1110.entity

数据SQL

SET FOREIGN_KEY_CHECKS=0;

-- ----------------------------
-- Table structure for user
-- ----------------------------
DROP TABLE IF EXISTS `user`;
CREATE TABLE `user` (
  `id` bigint(20) NOT NULL AUTO_INCREMENT,
  `name` varchar(255) NOT NULL,
  `age` int(6) NOT NULL,
  `city` varchar(255) NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8;

-- ----------------------------
-- Records of user
-- ----------------------------
INSERT INTO `user` VALUES ('1', '小明', '18', '深圳');
INSERT INTO `user` VALUES ('2', '小明1', '18', '深圳');

pom.xml



    4.0.0
    
        org.springframework.boot
        spring-boot-starter-parent
        2.5.6
         
    
    com.example
    demo1110
    1.0.0
    demo1110
    Demo project for Spring Boot
    
        1.8
    
    
        
            org.springframework.boot
            spring-boot-starter-web
        
        
            org.mybatis.spring.boot
            mybatis-spring-boot-starter
            2.2.0
        

        
            mysql
            mysql-connector-java
            runtime
        
        
            com.alibaba
            druid
            1.0.9
        
        
            org.springframework.boot
            spring-boot-starter-test
            test
        
        
            org.projectlombok
            lombok
        
    

    
        
            
                org.springframework.boot
                spring-boot-maven-plugin
            
        
    

示例2

项目结构

springboot 使用mybatis查询的示例代码_第2张图片

数据sql

SET FOREIGN_KEY_CHECKS=0;

-- ----------------------------
-- Table structure for user
-- ----------------------------
DROP TABLE IF EXISTS `user`;
CREATE TABLE `user` (
  `id` bigint(20) NOT NULL AUTO_INCREMENT,
  `name` varchar(255) NOT NULL,
  `age` int(6) NOT NULL,
  `city` varchar(255) NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8;

-- ----------------------------
-- Records of user
-- ----------------------------
INSERT INTO `user` VALUES ('1', '小明', '18', '深圳');
INSERT INTO `user` VALUES ('2', '小明1', '18', '深圳');

pom.xml



    4.0.0
    
        org.springframework.boot
        spring-boot-starter-parent
        2.5.6
         
    
    com.example
    demo1110
    1.0.0
    demo1110
    Demo project for Spring Boot
    
        1.8
    
    
        
            org.springframework.boot
            spring-boot-starter-web
        
        
            org.mybatis.spring.boot
            mybatis-spring-boot-starter
            2.2.0
        

        
            mysql
            mysql-connector-java
            runtime
        
        
            com.alibaba
            druid
            1.0.9
        
        
            org.springframework.boot
            spring-boot-starter-test
            test
        
        
            org.projectlombok
            lombok
        
    

    
        
            
                org.springframework.boot
                spring-boot-maven-plugin
            
        
    

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/*Mapper.xml
  type-aliases-package: com.example.demo1110.entity
#打印sql语句
##
#logging.level.com.example.demo1110.mapper=DEBUG
logging:
  level:
    com.example.demo1110.mapper: debug

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);
    }

}

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;

    public User(Integer id, String name, Integer age) {
        this.id = id;
        this.name = name;
        this.age = age;
    }
    public User(){

    }

    @Override
    public String toString() {
        return "User{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", age=" + age +
                ", city=" + city +
                '}';
    }
}

mapper -> UserMapper.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 UserMapper {
    /*//查询所有记录
    public List listUser();
    //按id查询
    public User queryById(Integer id);
    //按姓名模糊查询
    public List queryByName(String name);

    //保存用户
    public int addUser(User user);
    //根据员工id删除
    public int deleteUserById(Integer id);
    //修改员工信息
    public int editUser(User user);*/
    /**
     * 查询全部s
     * @return
     */
    List findAllUser();


    /**
     * 根据id查询
     * @param id
     * @return
     */
    User findUser(Integer id);


    /**
     * 新增
     * @param user
     */
    void insertUser(User user);


    /**
     * 根据id删除
     * @param id
     */
    void deleteUser(Integer id);


    /**
     * 更新
     * @param user
     */
    void updateUser(User user);
    /**
     * 批量删除
     * @param ids
     */

    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 {
    /*//查询所有记录
    public List listUser();
    //按id查询
    public User queryById(Integer id);
    //按姓名模糊查询
    public List queryByName(String name);
    //保存用户
    public boolean addUser(User user);
    //根据员工id删除
    public boolean deleteUserById(Integer id);
    //修改员工信息
    public boolean editUser(User user);*/
    /**
     * 查询全部
     * @return
     */
    List findAll();
    /**
     * 根据id查询
     * @param id
     * @return
     */
    User findUserById(Integer id);
    /**
     * 新增
     * @param user
     */
    void  insertUser(User user);
    /**
     * 更新
     * @param user
     */
    void updateUser(User user);
    /**
     * 删除单个用户
     * @param id
     */
    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 userDao;
    @Override
    public List listUser() {
        return userDao.listUser();
    }
    @Override
    public User queryById(Integer id) {
        return userDao.queryById(id);
    }
    @Override
    public List 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;
        }
    }*/
    @Autowired
    private UserMapper userMapper;
    @Override
    public User findUserById(Integer id) {
        return userMapper.findUser(id);
    }
    @Override
    public List 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("/all")
    public List getListUser(){
        return userService.listUser();
    }

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

    @PostMapping("/EditUser")
    private Map editUser(@RequestBody User user){
        System.out.println(user);
        HashMap 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 getName(@Param("name") String name){
        return userService.queryByName(name);
    }

    @PostMapping("/addUser")
    public Map addUser(@RequestBody User user){
        HashMap 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 deletUser(@PathVariable("id") Integer id){
        System.out.println(id);
        HashMap 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;
    }*/
    @Autowired
    private UserService userService;

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

    @GetMapping("/findAll")
    public List 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





    
        
        
        
    
    

    

    
        
            
                id,
            
                name,
            

            
                age,
            
        
    
    
        
            
                #{id},
            
            
                #{name},
            
            
                #{age},
            
        
    

    
        insert into user() values ()
    

    
        UPDATE user
        
            age=#{age},
            name=#{name},
        
        WHERE id=#{id}

    
    
        delete  from user where id = #{id}
    

    
        delete  from user where id in
        
            #{id}
        
    

测试运行项目

springboot 使用mybatis查询的示例代码_第3张图片

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查询内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

你可能感兴趣的:(springboot 使用mybatis查询的示例代码)