java

关注公众号 jb51net

关闭
首页 > 软件编程 > java > springboot  mybatis查询

springboot 使用mybatis查询的示例代码

作者:子岚天羽卿怜水

这篇文章主要介绍了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/*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

<?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.5.6</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.example</groupId>
    <artifactId>demo1110</artifactId>
    <version>1.0.0</version>
    <name>demo1110</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.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>2.2.0</version>
        </dependency>

        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <scope>runtime</scope>
        </dependency>
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid</artifactId>
            <version>1.0.9</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
        </dependency>
    </dependencies>

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

</project>

示例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

<?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.5.6</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.example</groupId>
    <artifactId>demo1110</artifactId>
    <version>1.0.0</version>
    <name>demo1110</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.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>2.2.0</version>
        </dependency>

        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <scope>runtime</scope>
        </dependency>
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid</artifactId>
            <version>1.0.9</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
        </dependency>
    </dependencies>

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

</project>

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<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);*/
    /**
     * 查询全部s
     * @return
     */
    List<User> 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<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);*/
    /**
     * 查询全部
     * @return
     */
    List<User> 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<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;
        }
    }*/
    @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("/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;
    }*/
    @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查询内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

您可能感兴趣的文章:
阅读全文