IDEA SpringBoot整合Mybatis和Druid数据源实现增删改查操作

1.新建一个maven项目project

注意:也可以在线创建一个springboot项目,这样比较方便

项目名称: springboot-druid-mybatis
在这里插入图片描述

在这里插入图片描述

2.添加依赖的pom:

<?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 http://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>org.example</groupId>
    <artifactId>springboot-druid-mybatis</artifactId>
    <version>1.0-SNAPSHOT</version>

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

    <dependencies>
        <!--mysql驱动-->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <!--对应自己电脑安装的mysql版本-->
            <version>8.0.22</version>
        </dependency>
        <!--druid-spring-boot连接池-->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid-spring-boot-starter</artifactId>
            <version>1.1.17</version>
        </dependency>
        <!--mybatis-spring-boot-->
        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>2.1.4</version>
        </dependency>
        <!--spring-boot-starter-web核心模块-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
            <version>2.5.0</version>
        </dependency>
        <!--lombok-->
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>1.18.22</version>
        </dependency>
    </dependencies>

</project>

3.编写application.yml文件:

在这里插入图片描述

文件名字:application.yml
内容如下:

server:
  port: 8080

spring:
  datasource:
    driver-class-name:  com.mysql.cj.jdbc.Driver
    url: jdbc:mysql://127.0.0.1:3306/test?characterEncoding=utf8&useSSL=false&serverTimezone=UTC&rewriteBatchedStatements=true
    username: root
    password: root
    type: com.alibaba.druid.pool.DruidDataSource

mybatis:
  mapper-locations: classpath:mapper/*.xml #sql映射文件的位置
  configuration:
    map-underscore-to-camel-case: true #驼峰命名开启
  type-aliases-package: com.example.entity #实体类所在的包,自动扫描并映射实体类
 
logging:  #为了打印sql语句
  level:
    root: debug

4.写主启动类:

com.example.SpringbootMybatisMain:
在主启动类上家注解@MapperScan(“com.example.entity”)和@SpringBootApplication

package com.example;

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

@MapperScan("com.example.mapper")//扫描mapper接口所在的包
@SpringBootApplication
public class SpringbootMybatisMain {
    public static void main(String[] args) {
        SpringApplication.run(SpringbootMybatisMain.class,args);
    }
}

5.数据库准备:

在这里插入图片描述
数据库test,表t_book.

然后可以插入2条数据备用。
在这里插入图片描述

6.实体类:

entity.Book:

package com.example.entity;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

@Data
@AllArgsConstructor
@NoArgsConstructor
public class Book {
    private int id;
    private String bookName;
    private String bookAuthor;
    public Book(String bookName,String bookAuthor){
        this.bookName = bookName;
        this.bookAuthor = bookAuthor;
    }
}

7.mapper接口:

mapper.BookMapper:

package com.example.mapper;

import com.example.entity.Book;
import org.apache.ibatis.annotations.Mapper;

@Mapper//指定这是一个操作数据库的mapper
@Repository //dao层组件注解
public interface BookMapper {
    //新增图书的接口
    public int addBook(Book book);
    //删除图书的接口,根据id删除
    public int delBook(int id);
    //修改图书
    public int updateBook(Book book);
    //根据id查找
    public Book selectBook(int id);
    //动态条件查询
    public List<Book> getBooksByConditionIf(Book book);
}

8.sql映射文件:

目录结构:

在这里插入图片描述
sql语句:(带动态查询等)

<?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">
<!--namespace对应mapper接口所在的位置-->
<mapper namespace="com.example.mapper.BookMapper">
    <!--resultMap自定义结果映射规则-->
    <resultMap id="BaseresultMap" type="com.example.entity.Book">
        <id column="id" property="id" jdbcType="INTEGER"></id>
        <result column="book_name" property="bookName" jdbcType="VARCHAR"></result>
        <result column="book_author" property="bookAuthor" jdbcType="VARCHAR"></result>
    </resultMap>
    <!--定义经常重用到的sql片段,方便后面使用includ标签引用-->
    <sql id="BaseColumn">id,book_name,book_author</sql>
    <sql id="InsertBaseColumn">book_name,book_author</sql>

    <!--对应mapper接口中的方法public int addBook(Book book);useGeneratedKeys和keyProperty用于获取自增主键;-->
    <insert id="addBook" parameterType="com.example.entity.Book" useGeneratedKeys="true" keyProperty="id">
        insert into t_book (<include refid="InsertBaseColumn"></include>)
        values (#{bookName},#{bookAuthor})
    </insert>

    <!-- public int delBook(int id);-->
    <delete id="delBook" parameterType="integer">
        delete from t_book where id = #{id}
    </delete>

    <!--public int updateBook(Book book);带动态sql,set标签为了去掉多余的逗号;useGeneratedKeys和keyProperty用于获取自增主键;-->
    <update id="updateBook" parameterType="com.example.entity.Book" useGeneratedKeys="true" keyProperty="id">
        update t_book
        <set>
            <if test="bookName!=null and bookName!='' ">book_name = #{bookName},</if>
            <if test="bookAuthor!=null and bookAuthor!='' ">book_author=#{bookAuthor}</if>
        </set>
        where id = #{id}
    </update>

    <!--public Book selectBook(int id);根据id 查询-->
    <select id="selectBook" resultMap="BaseresultMap">
        select <include refid="BaseColumn"></include>
         from t_book where id = #{id}
    </select>

    <!--public List<Book> getBooksByConditionIf(Book book);拼接动态sql,进行多条件查询-->
    <select id="getBooksByConditionIf" parameterType="com.example.entity.Book" resultMap="BaseresultMap" >
        <!--include refid="BaseColumn" 用来引用sql片段 -->
        select <include refid="BaseColumn"></include> from t_book
        <where>
            <if test="id!=null and id!='' "> id = #{id}</if>
            <if test="bookName!=null and bookName!='' ">
                <bind name="bookName" value=" '%' + bookName + '%' "/>
                and book_name like #{bookName};
            </if>
            <if test="bookAuthor!=null and bookAuthor!='' ">
                <!--bind绑定变量,不为空的时候才去绑定-->
                <bind name="bookAuthor" value=" '%'+bookAuthor+'%' "/>
                and book_author like #{bookAuthor};
            </if>
        </where>
    </select>

</mapper>

9.service层:

service.BookService接口:

package com.example.service;
import com.example.entity.Book;
import java.util.List;

public interface BookService {
    //新增图书的接口
    public int addBook(Book book);
    //删除图书的接口,根据id删除
    public int delBook(int id);
    //修改图书
    public int updateBook(Book book);
    //根据id查找
    public Book selectBook(int id);
    //动态条件查询
    public List<Book> getBooksByConditionIf(Book book);
}

service的实现类:impl.BookServiceImpl

package com.example.service.impl;

import com.example.entity.Book;
import com.example.mapper.BookMapper;
import com.example.service.BookService;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import java.util.List;
@Service
public class BookServiceImpl implements BookService {
    //注入mapper
    @Resource
    private BookMapper bookMapper;
    @Override
    public int addBook(Book book) {
        int i = bookMapper.addBook(book);
        return i;
    }

    @Override
    public int delBook(int id) {
        return bookMapper.delBook(id);
    }

    @Override
    public int updateBook(Book book) {
        return bookMapper.updateBook(book);
    }

    @Override
    public Book selectBook(int id) {
        return bookMapper.selectBook(id);
    }

    @Override
    public List<Book> getBooksByConditionIf(Book book) {
        List<Book> booksByConditionIf = bookMapper.getBooksByConditionIf(book);
        return booksByConditionIf;
    }
}

10.controller层:

controller.BookController:

package com.example.controller;

import com.example.entity.Book;
import com.example.service.BookService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

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


@RestController
@Slf4j
public class BookController {
    @Resource
    private BookService bookService;
    //增方法
    @RequestMapping(value = "/addBook",method = RequestMethod.POST)
    public String addBook( Book book){
        int i = bookService.addBook(book);
        if(i >= 1){
            return "增加成功";
        }else{
            return "增加失败";
        }
    }

    //删方法
    @RequestMapping(value = "/delBook",method = RequestMethod.GET)
    public String delBook( Integer id){
        int i = bookService.delBook(id);
        if(i >= 1){
            return "删除成功";
        }else{
            return "删除失败";
        }
    }

    //改方法
    @RequestMapping(value = "/updateBook",method = RequestMethod.POST)
    public String updateBook( Book book){
        int i = bookService.updateBook(book);
        if(i >= 1){
            return "修改成功";
        }else{
            return "修改失败";
        }
    }

    //查方法
    @RequestMapping(value = "/selectBook",method = RequestMethod.GET)
    public Book selectBook( Integer id){
        Book book = bookService.selectBook(id);
        return book;
    }
    //getBooksByConditionIf查方法
    @RequestMapping(value = "/getBooksByConditionIf",method = RequestMethod.POST)
    public List<Book> getBooksByConditionIf(Book book){
        List<Book> booksByConditionIf = bookService.getBooksByConditionIf(book);
        return booksByConditionIf;
    }
}

测试:使用postman测试:

数据库表:
在这里插入图片描述

增加测试:

在这里插入图片描述

删除测试:
在这里插入图片描述

修改测试:

在这里插入图片描述
查找测试:

在这里插入图片描述

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
项目描述 在上家公司自己集成的一套系统,用了两个多月的时间完成的:Springboot+Mybatis-plus+ SpringMvc+Shiro+Redis企业级开发系统 Springboot作为容器,使用mybatis作为持久层框架 使用官方推荐的thymeleaf做为模板引擎,shiro作为安全框架,主流技术 几乎零XML,极简配置 两套UI实现(bootstrap+layer ui),可以自由切换 报表后端采用技术: SpringBoot整合SSM(Spring+Mybatis-plus+ SpringMvc),spring security 全注解式的权限管理和JWT方式禁用Session,采用redis存储token及权限信息 报表前端采用B ootstrap框架,结合Jquery Ajax,整合前端Layer.js(提供弹窗)+Bootstrap-table(数据列表展示)+ Bootstrap-Export(各种报表导出SQL,Excel,pdf等)框架,整合Echars,各类图表的展示(折线图,饼图,直方图等),使用了layui的弹出层、菜单、文件上传、富文本编辑、日历、选项卡、数据表格等 Oracle关系型数据库以及非关系型数据库(Redis),Oracle 性能调优(PL/SQL语言,SQL查询优化,存储过程等),用Redis做中间缓存,缓存数据 实现异步处理,定时任务,整合Quartz Job以及Spring Task 邮件管理功能, 整合spring-boot-starter-mail发送邮件等, 数据源:druid 用户管理,菜单管理,角色管理,代码生成 运行环境 jdk8+oracle+redis+IntelliJ IDEA+maven 项目技术(必填) Springboot+Mybatis-plus+ SpringMvc+Shiro+Redis 数据库文件 压缩包内 jar包文件 maven搭建 Springboot+Mybatis-plus+ SpringMvc+Shiro+Redis企业级报表后台管理系统 http://localhost:/8080/login admin admin Springboot+Mybatis-plus+ SpringMvc+Shiro+Redis企业级报表后台管理系统Springboot+Mybatis-plus+ SpringMvc+Shiro+Redis企业级报表后台管理系统Springboot+Mybatis-plus+ SpringMvc+Shiro+Redis企业级报表后台管理系统Springboot+Mybatis-plus+ SpringMvc+Shiro+Redis企业级报表后台管理系统Springboot+Mybatis-plus+ SpringMvc+Shiro+Redis企业级报表后台管理系统
好的,以下是使用SpringBoot整合mybatis实现简单增删改查操作的代码示例: 1. 首先在pom.xml中添加依赖: ```xml <dependency> <groupId>org.mybatis.spring.boot</groupId> <artifactId>mybatis-spring-boot-starter</artifactId> <version>2.1.4</version> </dependency> ``` 2. 在application.properties中配置数据库相关信息: ```properties # 数据库配置 spring.datasource.url=jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=UTF-8&serverTimezone=Asia/Shanghai spring.datasource.username=root spring.datasource.password=root spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver # Mybatis配置 mybatis.mapper-locations=classpath*:mapper/*.xml mybatis.type-aliases-package=com.example.demo.entity ``` 3. 创建实体类和Mapper接口: ```java // User实体类 public class User { private Long id; private String name; private Integer age; // getter和setter方法省略 } ``` ```java // UserMapper接口 public interface UserMapper { User selectById(Long id); List<User> selectAll(); void insert(User user); void update(User user); void delete(Long id); } ``` 4. 在resources/mapper目录下创建UserMapper.xml文件,定义SQL语句: ```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.demo.mapper.UserMapper"> <resultMap id="BaseResultMap" type="com.example.demo.entity.User"> <id column="id" property="id" jdbcType="BIGINT" /> <result column="name" property="name" jdbcType="VARCHAR" /> <result column="age" property="age" jdbcType="INTEGER" /> </resultMap> <select id="selectById" resultMap="BaseResultMap"> SELECT id, name, age FROM user WHERE id = #{id} </select> <select id="selectAll" resultMap="BaseResultMap"> SELECT id, name, age FROM user </select> <insert id="insert"> INSERT INTO user (name, age) VALUES (#{name}, #{age}) </insert> <update id="update"> UPDATE user SET name = #{name}, age = #{age} WHERE id = #{id} </update> <delete id="delete"> DELETE FROM user WHERE id = #{id} </delete> </mapper> ``` 5. 在Service中调用Mapper接口: ```java @Service public class UserService { @Autowired private UserMapper userMapper; public User getUserById(Long id) { return userMapper.selectById(id); } public List<User> getAllUser() { return userMapper.selectAll(); } public void addUser(User user) { userMapper.insert(user); } public void updateUser(User user) { userMapper.update(user); } public void deleteUser(Long id) { userMapper.delete(id); } } ``` 最后,启动应用程序即可进行增删改查操作

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值