springboot+mybatis实现图书信息的增删改查(详解&初学者练手)

用postman测试过的接口如下:

以下是完整代码:

0.建立数据库和表结构

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.5.1</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.example</groupId>
    <artifactId>tushuGL</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>tushuGL</name>
    <description>Demo project for Spring Boot</description>
    <properties>
        <java.version>1.8</java.version>
    </properties>
    <dependencies>
        <!--thymeleaf-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-thymeleaf</artifactId>
        </dependency>
        <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>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-jdbc</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>1.2.76</version>
        </dependency>
        <dependency>
            <groupId>log4j</groupId>
            <artifactId>log4j</artifactId>
            <version>1.2.12</version>
        </dependency>
    </dependencies>

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

            <!-- mybatis generator 自动生成代码插件 -->
            <plugin>
                <groupId>org.mybatis.generator</groupId>
                <artifactId>mybatis-generator-maven-plugin</artifactId>
                <version>1.4.0</version>
                <configuration>
                    <configurationFile>src/main/resources/generator/generator-config.xml</configurationFile>
                    <overwrite>true</overwrite>
                    <verbose>true</verbose>
                </configuration>
                <dependencies>
                    <dependency>
                        <groupId>mysql</groupId>
                        <artifactId>mysql-connector-java</artifactId>
                        <version>8.0.22</version>
                    </dependency>
                </dependencies>
            </plugin>
        </plugins>
    </build>

</project>

2.Mapper接口

package com.example.tushugl.mapper;
import com.example.tushugl.domain.Book;
import java.util.List;
public interface BookMapper {
    //显示所有图书
    List<Book> finAll();

    //根据id进行查询图书
    Book findById(int bookId);

    //根据书名查找图书
    List<Book>findByName(String bookName);

    //添加书籍
    int insertBook(Book book);

    //修改书籍信息
    int updateBook(Book book);

    //删除书籍信息
    int deleteBook(int bookId);


}

3.Mapper映射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.tushugl.mapper.BookMapper">
    <resultMap id="BaseResultMap" type="com.example.tushugl.domain.Book">
        <id column="id" jdbcType="BIGINT" property="bookId"/>
        <result column="bookName" jdbcType="VARCHAR" property="bookName"/>
        <result column="author" jdbcType="VARCHAR" property="author"/>
        <result column="publisher" jdbcType="VARCHAR" property="publisher"/>
        <result column="descri" jdbcType="VARCHAR" property="descri"/>
    </resultMap>

    <select id="finAll" resultMap="BaseResultMap">
        select *from book;
    </select>

    <select id="findById" parameterType="java.lang.Integer" resultMap="BaseResultMap">
        select * from book where id=#{bookId};
    </select>

    <select id="findByName" parameterType="java.lang.String" resultMap="BaseResultMap">
        select * from book where bookName like concat('%',#{bookName},'%');
    </select>

    <insert id="insertBook" parameterType="com.example.tushugl.domain.Book">
        insert into book(bookName,author,publisher,descri)values(#{bookName},#{author},#{publisher},#{descri});
    </insert>

    <update id="updateBook" parameterType="com.example.tushugl.domain.Book">
        update book <set>
        <if test="bookName!=null">
            bookName=#{bookName,jdbcType=VARCHAR},
        </if>
        <if test="author!=null">
            author=#{author,jdbcType=VARCHAR},
        </if>
            <if test="publisher!=null">
                publisher=#{publisher,jdbcType=VARCHAR},
            </if>
            <if test="descri!=null">
                descri=#{descri,jdbcType=VARCHAR},
            </if>
    </set>
            where id=#{bookId,jdbcType=INTEGER}
    </update>

    <delete id="deleteBook" parameterType="java.lang.Integer">
        delete  from book where id=#{bookId};
    </delete>
</mapper>

4.service层

package com.example.tushugl.service;

import com.example.tushugl.domain.Book;
import com.example.tushugl.mapper.BookMapper;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import java.util.List;

@Service
public class BookService {
   @Resource
    private BookMapper bookMapper;
    //查询所有的图书
    public List<Book> list(){
        List<Book> bookList = bookMapper.finAll();
        return bookList;
    }
    public Book findById(int bookId){
        Book byId = bookMapper.findById(bookId);
        return byId;
    }

    public List<Book> findByName(String bookName){
        List<Book> byName = bookMapper.findByName(bookName);
        return byName;
    }
    public int insertBook(Book book){
        int insertBook = bookMapper.insertBook(book);
        return insertBook;
    }
    public  int updateBook(Book book){
        int updateBook = bookMapper.updateBook(book);
        return updateBook;
    }
    public  Integer deleteBook(Integer bookId){
        int deleteBook = bookMapper.deleteBook(bookId);
        return deleteBook;
    }
}

5.domain层

package com.example.tushugl.domain;

public class Book {
    private Integer bookId;
    private String bookName;
    private String author;
    private String publisher;
    public String descri;
    public Integer getBookId() {
        return bookId;
    }

    public void setBookId(Integer bookId) {
        this.bookId = bookId;
    }

    public String getBookName() {
        return bookName;
    }

    public void setBookName(String bookName) {
        this.bookName = bookName;
    }

    public String getAuthor() {
        return author;
    }

    public void setAuthor(String author) {
        this.author = author;
    }

    public String getPublisher() {
        return publisher;
    }

    public void setPublisher(String publisher) {
        this.publisher = publisher;
    }

    public String getDescri() {
        return descri;
    }

    public void setDescri(String descri) {
        this.descri = descri;
    }

    @Override
    public String toString() {
        return "Book{" +
                "bookId=" + bookId +
                ", bookName='" + bookName + '\'' +
                ", author='" + author + '\'' +
                ", publisher='" + publisher + '\'' +
                ", descri='" + descri + '\'' +
                '}';
    }
}

6.Controller层

package com.example.tushugl.controller;

import com.example.tushugl.domain.Book;
import com.example.tushugl.service.BookService;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

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

@RestController
@RequestMapping("/book")
public class BookController {
    @Resource
   private  BookService bookService;

    //通过id查询图书
    @RequestMapping("/findById")
    public Book findById(int id){
        Book byId = bookService.findById(id);
        return byId;
    }
    //通过bookName查询图书
    @RequestMapping("/findByName")
    public List<Book> findByName(String name){
        List<Book> byName = bookService.findByName(name);
        return byName;
    }
    //查询全部图书
    @RequestMapping("/findAll")
    public List<Book> findAll(){
        List<Book> list = bookService.list();
        return list;
    }
    //新增数据
    @RequestMapping("/insert")
    public Integer insertBook(Book book){
        int insertBook = bookService.insertBook(book);
        if (insertBook>0){
            System.out.println("新增成功!");
        }
        return insertBook;
    }
    //更改数据
    @RequestMapping("/updateBook")
    public Integer updateBook(Book book){
        int updateBook = bookService.updateBook(book);
        if (updateBook>0){
            System.out.println("新增成功");
        }
        return updateBook;
    }
    //删除数据
    @RequestMapping("delete")
    public Integer deleteBook(Integer id){
        Integer integer = bookService.deleteBook(id);
        if (integer>0){
            System.out.println("删除成功!");
        }
        return integer;
    }


}

7.启动类

package com.example.tushugl.config;

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

@ComponentScan("com.example")
@MapperScan("com.example.tushugl.mapper")
@SpringBootApplication
public class TushuGlApplication {
    public static void main(String[] args) {
        SpringApplication.run(TushuGlApplication.class, args);
    }

}

8.mybaits自动生成类(本项目不用,只是作为以后的参考)

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE generatorConfiguration
        PUBLIC "-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN"
        "http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd">

<generatorConfiguration>
    <context id="Mysql" targetRuntime="MyBatis3" defaultModelType="flat">

        <!-- 自动检查关键字,为关键字增加反引号 -->
        <property name="autoDelimitKeywords" value="true"/>
        <property name="beginningDelimiter" value="`"/>
        <property name="endingDelimiter" value="`"/>

        <!--覆盖生成XML文件-->
        <plugin type="org.mybatis.generator.plugins.UnmergeableXmlMappersPlugin" />
        <!-- 生成的实体类添加toString()方法 -->
        <plugin type="org.mybatis.generator.plugins.ToStringPlugin"/>

        <!-- 不生成注释 -->
        <commentGenerator>
            <property name="suppressAllComments" value="true"/>
        </commentGenerator>

        <jdbcConnection driverClass="com.mysql.cj.jdbc.Driver"
                        connectionURL="jdbc:mysql://localhost:3306/tushum?serverTimezone=Asia/Shanghai"
                        userId="root"
                        password="root">
        </jdbcConnection>

        <!-- domain类的位置 -->
        <javaModelGenerator targetProject="src\main\java"
                            targetPackage="com.example.tushugl.domain"/>

        <!-- mapper xml的位置 -->
        <sqlMapGenerator targetProject="src\main\resources"
                         targetPackage="mapper"/>

        <!-- mapper类的位置 -->
        <javaClientGenerator targetProject="src\main\java"
                             targetPackage="com.example.tushugl.mapper"
                             type="XMLMAPPER"/>

<!--        都是改动这个部分,上面的部分配置好了就不需要动了,每建立一个表就增加一个<table>就可以了
            还有就是  生成后的表就不要再生成了-->
        <table tableName="book" domainObjectName="Book"/>
<!--        <table tableName="ebook" domainObjectName="Ebook"/>-->
<!--        <table tableName="ebook"/>-->
<!--        <table tableName="category"/>-->
<!--        <table tableName="doc"/>-->
<!--        <table tableName="content"/>-->
<!--        <table tableName="user"/>-->
<!--        <table tableName="ebook_snapshot"/>-->
    </context>
</generatorConfiguration>

9.配置文件

server.port=8080
#增加数据源
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.password=zhanghao
spring.datasource.username=mima 
spring.datasource.url=jdbc:mysql://localhost:3306/tushum?serverTimezone=UTC&useUnicode=true&characterEncoding=utf-8&autoReconnect=true&useSSL=true
#spring.thymeleaf.prefix=classpath:/templates/
#mapper.mappers=tk.mybatis.mapper.common.Mapper
#mapper.not-empty=true
#spring.thymeleaf.cache=false
#配置后mybatis所有的Mapper.xml所在的路径
mybatis.mapper-locations=classpath:/mapper/**/*.xml
##设置可以访问html页面
spring.thymeleaf.prefix=classpath:/templates/

  • 2
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

阳光不锈@

如果有帮助的话,打赏一下吧

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值