学习mybatis框架和ORM映射技术,实现Book类项目的三个接口功能
基于mybatis框架实现Book类项目 mybatis的作用
简化数据库操作
MyBatis允许开发者通过XML或注解的方式定义SQL语句,简化JDBC的繁琐操作,比如连接管理,语句创建和结果处理。
灵活的SQL映射
与ORM(对象关系映射)框架不同,MyBatis允许开发者直接编写SQL语句,提供了更大的灵活性和控制权,适合复杂的查询和性能调优。
对象映射
MyBatis能够将数据库查询结果映射到java对象,支持复杂的对象关系映射,使得数据处理更加便捷。
项目代码结构
项目引入mybatis 新建项目后打开pom.xml文件,引入mybatis依赖
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 <?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.4.2</version > <relativePath /> </parent > <groupId > com.example</groupId > <artifactId > testbook</artifactId > <version > 0.0.1-SNAPSHOT</version > <name > testbook</name > <description > Demo project for Spring Boot</description > <url /> <properties > <maven.compiler.source > 11</maven.compiler.source > <maven.compiler.target > 11</maven.compiler.target > </properties > <dependencies > <dependency > <groupId > org.springframework.boot</groupId > <artifactId > spring-boot-starter</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.3.2</version > </dependency > <dependency > <groupId > mysql</groupId > <artifactId > mysql-connector-java</artifactId > <version > 8.0.29</version > </dependency > <dependency > <groupId > com.google.code.gson</groupId > <artifactId > gson</artifactId > <version > 2.10</version > </dependency > <dependency > <groupId > org.apache.commons</groupId > <artifactId > commons-lang3</artifactId > <version > 3.4</version > </dependency > </dependencies > <build > <plugins > <plugin > <groupId > org.apache.maven.plugins</groupId > <artifactId > maven-compiler-plugin</artifactId > <version > 3.1</version > <configuration > <source > ${java.version}</source > <target > ${java.version}</target > <encoding > ${project.build.sourceEncoding}</encoding > </configuration > </plugin > <plugin > <groupId > org.springframework.boot</groupId > <artifactId > spring-boot-maven-plugin</artifactId > <version > 2.4.2</version > <configuration > <mainClass > com.example.testmysql.TestMysqlApplication</mainClass > </configuration > <executions > <execution > <id > repackage</id > <goals > <goal > repackage</goal > </goals > </execution > </executions > </plugin > </plugins > </build > <repositories > <repository > <id > public</id > <name > aliyun nexus</name > <url > https://maven.aliyun.com/repository/public</url > <releases > <enabled > true</enabled > </releases > </repository > </repositories > <pluginRepositories > <pluginRepository > <id > public</id > <name > aliyun nexus</name > <url > https://maven.aliyun.com/repository/public</url > <releases > <enabled > true</enabled > </releases > <snapshots > <enabled > false</enabled > </snapshots > </pluginRepository > </pluginRepositories > </project >
模块编写 Application启动器 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 package com.example.testbook;import org.mybatis.spring.annotation.MapperScan;import org.springframework.boot.SpringApplication;import org.springframework.boot.autoconfigure.SpringBootApplication;@MapperScan("com.example.testbook.dao") @SpringBootApplication public class TestBookApplication { public static void main (String[] args) { SpringApplication.run(TestBookApplication.class, args); } }
controller控制器 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 package com.example.testbook.controller;import com.example.testbook.entity.JSONObject;import com.example.testbook.entity.TBook;import com.example.testbook.service.BookService;import org.springframework.http.HttpStatus;import org.springframework.http.ResponseEntity;import org.springframework.web.bind.annotation.RequestBody;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.RestController;import javax.annotation.Resource;import java.util.List;@RestController public class BookController { @Resource private BookService BookService; @RequestMapping(value = "/createbook") public ResponseEntity<JSONObject> save (@RequestBody TBook book) { JSONObject jo = new JSONObject (); if (book.getBookname() == null ){ jo.setCode("-1" ); jo.setMsg("bookname不能为空" ); return new ResponseEntity <JSONObject>(jo, HttpStatus.OK); } if (book.getPrice() == null || "" .equals(book.getPrice())){ jo.setCode("-1" ); jo.setMsg("price不能为空" ); return new ResponseEntity <JSONObject>(jo, HttpStatus.OK); } if (book.getPublisher() == null || "" .equals(book.getPublisher())){ jo.setCode("-1" ); jo.setMsg("publisher不能为空" ); return new ResponseEntity <JSONObject>(jo, HttpStatus.OK); } TBook exist = BookService.queryBookByBookname(book.getBookname()); if (exist != null ){ jo.setCode("-1" ); jo.setMsg("bookname已存在,请更改" ); return new ResponseEntity <JSONObject>(jo, HttpStatus.OK); } book.setPrice(book.getPrice()); book.setPublisher(book.getPublisher()); book.setStatus(1 ); BookService.save(book); jo.setCode("1" ); jo.setMsg("新建书本信息成功" ); return new ResponseEntity <JSONObject>(jo, HttpStatus.OK); } @RequestMapping(value = "/querybook") public ResponseEntity<JSONObject> querybook (@RequestBody TBook book) { JSONObject jo = new JSONObject (); if (book.getBookname() == null || "" .equals(book.getBookname())){ jo.setCode("-1" ); jo.setMsg("bookname不能为空" ); return new ResponseEntity <JSONObject>(jo, HttpStatus.OK); } TBook exist = BookService.queryBookByBookname(book.getBookname()); if (exist == null ){ jo.setCode("1" ); jo.setMsg("书本已借出 " ); return new ResponseEntity <JSONObject>(jo, HttpStatus.OK); }else { jo.setCode("1" ); jo.setMsg("书本存在 " ); return new ResponseEntity <JSONObject>(jo, HttpStatus.OK); } } @RequestMapping(value = "/queryPublisherAllBook") public ResponseEntity<JSONObject> queryPublisherAllBook (@RequestBody TBook book) { JSONObject jo = new JSONObject (); List<TBook> books = BookService.queryPublisherAllBook(book.getPublisher()); jo.setCode("1" ); jo.setMsg("查询成功" ); jo.setO(books); return new ResponseEntity <JSONObject>(jo, HttpStatus.OK); } }
entity实体类代码 TBook类 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 package com.example.testbook.entity;public class TBook { private int id; private String bookname; private Double price; private String publisher; private int status; public int getId () { return id; } public void setId (int id) { this .id = id; } public String getBookname () { return bookname; } public void setBookname (String bookname) { this .bookname = bookname; } public Double getPrice () { return price; } public void setPrice (Double price) { this .price = price; } public String getPublisher () { return publisher; } public void setPublisher (String publisher) { this .publisher = publisher; } public int getStatus () { return status; } public void setStatus (int status) { this .status = status; } }
JSONObject类 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 package com.example.testbook.entity;import com.google.gson.Gson;public class JSONObject { private String code; private String msg; private Object o; @Override public String toString () { return new Gson ().toJson(this ); } public String getCode () { return code; } public void setCode (String code) { this .code = code; } public String getMsg () { return msg; } public void setMsg (String msg) { this .msg = msg; } public Object getO () { return o; } public void setO (Object o) { this .o = o; } }
dao接口 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 package com.example.testbook.dao;import com.example.testbook.entity.TBook;import org.springframework.stereotype.Repository;import java.util.List;@Repository public interface BookDao { public int save (TBook book) ; public TBook queryBookByBookname (String bookname) ; List<TBook> queryPublisherAllBook (String publisher) ; }
sevice服务接口 BookServiceImpl类(覆写对应接口方法)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 package com.example.testbook.service.impl;import com.example.testbook.dao.BookDao;import com.example.testbook.entity.TBook;import com.example.testbook.service.BookService;import org.springframework.stereotype.Service;import javax.annotation.Resource;import java.util.List;@Service public class BookServiceImpl implements BookService { @Resource private BookDao bookDao; @Override public int save (TBook book) { return bookDao.save(book); } @Override public TBook queryBookByBookname (String bookname) { return bookDao.queryBookByBookname(bookname); } @Override public List<TBook> queryPublisherAllBook (String publisher) { return bookDao.queryPublisherAllBook(publisher); } }
BookService接口
1 2 3 4 5 6 7 8 9 10 11 12 13 package com.example.testbook.service;import com.example.testbook.entity.TBook;import java.util.List;public interface BookService { public int save (TBook book) ; public TBook queryBookByBookname (String bookname) ; public List<TBook> queryPublisherAllBook (String publisher) ; }
配置文件 SQL映射配置 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 <?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.testbook.dao.BookDao" > <insert id ="save" parameterType ="com.example.testbook.entity.TBook" useGeneratedKeys ="true" keyProperty ="id" > insert into t_book ( `bookname`, `price`, `publisher`, `status` ) VALUES ( #{bookname}, #{price}, #{publisher}, #{status} ); </insert > <select id ="queryBookByBookname" parameterType ="string" resultType ="com.example.testbook.entity.TBook" > select * from t_book where bookname = #{bookname} and status = 1 </select > <select id ="queryPublisherAllBook" resultType ="com.example.testbook.entity.TBook" > select * from t_book where publisher = #{publisher} </select > </mapper >
application.properties 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 spring.application.name=testBook server.port=8087 ### mybatis mybatis.mapper-locations=classpath:/mybatis-mapper/*Mapper.xml mybatis.configuration.map-underscore-to-camel-case=true ### xxl-job, datasource spring.datasource.url=jdbc:mysql://localhost:3306/testmysql?useUnicode=true&useSSL=false&characterEncoding=UTF-8&autoReconnect=true&serverTimezone=Asia/Shanghai spring.datasource.username=root spring.datasource.password=root spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver ### datasource-pool spring.datasource.type=com.zaxxer.hikari.HikariDataSource spring.datasource.hikari.minimum-idle=10 spring.datasource.hikari.maximum-pool-size=30 spring.datasource.hikari.auto-commit=true spring.datasource.hikari.idle-timeout=30000 spring.datasource.hikari.pool-name=HikariCP spring.datasource.hikari.max-lifetime=900000 spring.datasource.hikari.connection-timeout=10000 spring.datasource.hikari.connection-test-query=SELECT 1 spring.datasource.hikari.validation-timeout=1000
数据库配置 具体要求如下
1 2 3 4 5 6 7 t_book表 字段: id bookname 书名 price 价格 publisher 出版社 status 状态0为借出,1为存在
打开Navicat,创建testmysql数据库后新建查询,写入以下代码
1 2 3 4 5 6 7 8 CREATE TABLE `t_book` (`id` int (11 ) NOT NULL AUTO_INCREMENT, `bookname` varchar (50 ) NOT NULL COMMENT '书名' , `price` int (50 ) NOT NULL COMMENT '价格' , `publisher` varchar (50 ) NOT NULL COMMENT '出版社' , `status` int (4 ) NOT NULL COMMENT '状态0为借出,1为存在' , PRIMARY KEY (`id`));
功能测试 新建书本 /createbook 1 2 3 4 5 { "bookname" : "sanguo" , "price" : 10 , "publisher" : "gongye" }
查询书籍是否存在 /querybook 1 2 3 { "bookname" : "sanguo" }
查询出版社全部书籍 /queryPublisherAllBook 1 2 3 { "publisher" : "gongye" }