创建springboot工程
springboot整合Mybatis
1、创建springboot工程
创建Spring Initializr
Java版本:Java 8
springboot版本:2.5.8
勾选:
Spring Web
MySQL Driver
MyBatis Framework
2、pom.xml
- 修改mysql版本
原:
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
修改:
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.38</version>
</dependency>
- 添加pagehelper分页依赖
<dependency>
<groupId>com.github.pagehelper</groupId>
<artifactId>pagehelper-spring-boot-starter</artifactId>
<version>1.4.1</version>
</dependency>
3、application.yml
修改application.properties后缀为yml(shift+f6重命名)
- 配置引入数据库的相关配置
spring:
datasource:
driver-class-name: com.mysql.jdbc.Driver
url: jdbc:mysql://localhost:3306/user?serverTimezone=Asia/Shanghai
username: root
password: 123456
- 配置引入mybatis的相关配置
mybatis:
mapper-locations: cn/test/mapper/*Mapper.xml
- 配置引入分页的相关配置
pagehelper:
helper-dialect: mysql
reasonable: false
全部:
spring:
datasource:
driver-class-name: com.mysql.jdbc.Driver
url: jdbc:mysql://localhost:3306/db0115?serverTimezone=Asia/Shanghai
username: root
password: 123456
mybatis:
configuration:
log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
mapper-locations: mapper\*Mapper.xml
pagehelper:
helper-dialect: mysql
reasonable: true
server:
port: 8092
4、logback.xml
在resources目录下,添加logback.xml
<?xml version="1.0" encoding="UTF-8"?>
<configuration debug="false">
<!--定义日志文件的存储地址 勿在 LogBack 的配置中使用相对路径-->
<property name="LOG_HOME" value="consumner/consumelog" />
<!-- 控制台输出 -->
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
<encoder class="ch.qos.logback.classic.encoder.PatternLayoutEncoder">
<!--格式化输出:%d表示日期,%thread表示线程名,%-5level:级别从左显示5个字符宽度%msg:日志消息,%n是换行符-->
<pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{50} - %msg%n</pattern>
</encoder>
</appender>
<!-- 按照每天生成日志文件 -->
<appender name="FILE" class="ch.qos.logback.core.rolling.RollingFileAppender">
<rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
<!--日志文件输出的文件名-->
<FileNamePattern>${LOG_HOME}/%d{yyyy-MM-dd}.log</FileNamePattern>
<!--日志文件保留天数-->
<MaxHistory>30</MaxHistory>
</rollingPolicy>
<encoder class="ch.qos.logback.classic.encoder.PatternLayoutEncoder">
<!--格式化输出:%d表示日期,%thread表示线程名,%-5level:级别从左显示5个字符宽度%msg:日志消息,%n是换行符-->
<pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{50} - %msg%n</pattern>
</encoder>
<!--日志文件最大的大小-->
<triggeringPolicy class="ch.qos.logback.core.rolling.SizeBasedTriggeringPolicy">
<MaxFileSize>10MB</MaxFileSize>
</triggeringPolicy>
</appender>
<!-- show parameters for hibernate sql 专为 Hibernate 定制 -->
<logger name="org.hibernate.type.descriptor.sql.BasicBinder" level="TRACE" />
<logger name="org.hibernate.type.descriptor.sql.BasicExtractor" level="DEBUG" />
<logger name="org.hibernate.SQL" level="DEBUG" />
<logger name="org.hibernate.engine.QueryParameters" level="DEBUG" />
<logger name="org.hibernate.engine.query.HQLQueryPlan" level="DEBUG" />
<!--myibatis log configure-->
<logger name="com.apache.ibatis" level="TRACE"/>
<logger name="java.sql.Connection" level="DEBUG"/>
<logger name="java.sql.Statement" level="DEBUG"/>
<logger name="java.sql.PreparedStatement" level="DEBUG"/>
<!-- 日志输出级别 -->
<root level="INFO">
<appender-ref ref="STDOUT" />
<appender-ref ref="FILE" />
</root>
<!--日志异步到数据库 -->
<!--<appender name="DB" class="ch.qos.logback.classic.db.DBAppender">-->
<!--<!–日志异步到数据库 –>-->
<!--<connectionSource class="ch.qos.logback.core.db.DriverManagerConnectionSource">-->
<!--<!–连接池 –>-->
<!--<dataSource class="com.mchange.v2.c3p0.ComboPooledDataSource">-->
<!--<driverClass>com.mysql.jdbc.Driver</driverClass>-->
<!--<url>jdbc:mysql://127.0.0.1:3306/databaseName</url>-->
<!--<user>root</user>-->
<!--<password>root</password>-->
<!--</dataSource>-->
<!--</connectionSource>-->
<!--</appender>-->
</configuration>
5、创建包
java:
entity
mapper
service
controller
resources:
cn\test\mapper
6、创建实体类
实体类序列化
package cn.test.entity;
import java.io.Serializable;
public class Book implements Serializable {
private Integer id;
private String bookName;
private String publish;
private String addDate;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getBookName() {
return bookName;
}
public void setBookName(String bookName) {
this.bookName = bookName;
}
public String getPublish() {
return publish;
}
public void setPublish(String publish) {
this.publish = publish;
}
public String getAddDate() {
return addDate;
}
public void setAddDate(String addDate) {
this.addDate = addDate;
}
}
7、创建mapper接口
@Mapper:将mapper接口交给spring管理
package cn.test.mapper;
import cn.test.entity.Book;
import org.apache.ibatis.annotations.Mapper;
import java.util.List;
@Mapper
public interface BookMapper {
//添加一本书
public Integer addBook(Book book);
//删除一本书
public Integer delBook(Integer id);
//更新一本书
public Integer updateBook(Book book);
//查看一本书
public Book findBook(Integer id);
//查看所有书,模糊查询
public List<Book> findAllBook(String bookName);
}
8、创建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="cn.test.mapper.BookMapper">
<insert id="addBook" parameterType="cn.test.entity.Book">
insert into t_book (bookName,publish,addDate)
values (#{bookName},#{publish},#{addDate})
</insert>
<delete id="delBook" parameterType="int">
delete from t_book where id = #{id}
</delete>
<update id="updateBook" parameterType="cn.test.entity.Book">
update t_book set bookName = #{bookName},publish = #{publish},addDate = #{addDate}
where id = #{id}
</update>
<select id="findBook" parameterType="int" resultType="cn.test.entity.Book">
select * from t_book where id = #{id}
</select>
<select id="findAllBook" parameterType="java.lang.String" resultType="cn.test.entity.Book">
select * from t_book where 1 = 1
and bookName like concat('%',#{bookName},'%')
</select>
</mapper>
9、创建service接口
package cn.test.service;
import cn.test.entity.Book;
import com.github.pagehelper.PageInfo;
public interface BookService {
//添加一本书
public Integer addBook(Book book);
//删除一本书
public Integer delBook(Integer id);
//更新一本书
public Integer updateBook(Book book);
//查看一本书
public Book findBook(Integer id);
//查看所有书,模糊查询+分页
public PageInfo<Book> findAllBook(Integer pageNo,String bookName);
}
10、创建service实现类
@Service:将service交给spring管理
@Transactional:开启事务
package cn.test.service;
import cn.test.entity.Book;
import cn.test.mapper.BookMapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import javax.annotation.Resource;
@Service
@Transactional
public class BookServiceImpl implements BookService {
@Resource
private BookMapper bookMapper;
@Override
public Integer addBook(Book book) {
return bookMapper.addBook(book);
}
@Override
public Integer delBook(Integer id) {
return bookMapper.delBook(id);
}
@Override
public Integer updateBook(Book book) {
return bookMapper.updateBook(book);
}
@Override
public Book findBook(Integer id) {
return bookMapper.findBook(id);
}
@Override
public PageInfo<Book> findAllBook(Integer pageNo, String bookName) {
PageHelper.startPage(pageNo,5);
return new PageInfo<>(bookMapper.findAllBook(bookName));
}
}
11、创建controller
@RestController:将controller交给spring管理
@CrossOrigin:支持跨域
@RequestBody:主要用来接收前端传递给后端的json字符串中的数据的(请求体中的数据的)
package cn.test.controller;
import cn.test.entity.Book;
import cn.test.service.BookService;
import com.github.pagehelper.PageInfo;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.Date;
@RestController
@CrossOrigin
public class BookController {
@Resource
private BookService bookService;
//添加一本书
@RequestMapping("/addBook")
public String addBook(@RequestBody Book book){
String addDate = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());
book.setAddDate(addDate);
bookService.addBook(book);
return "ok";
}
//删除一本书
@RequestMapping("/delBook")
public String delBook(Integer id){
bookService.delBook(id);
return "ok";
}
//更新一本书
@RequestMapping("/updateBook")
public String updateBook(@RequestBody Book book){
bookService.updateBook(book);
return "ok";
}
//查看一本书
@RequestMapping("/findBook")
public Book findBook(Integer id){
Book book = bookService.findBook(id);
return book;
}
//查看所有书,模糊查询+分页
@RequestMapping("/findAllBook")
public PageInfo<Book> findAllBook(@RequestParam(defaultValue = "1") Integer pageNo,@RequestParam(defaultValue = "") String bookName){
PageInfo<Book> list = bookService.findAllBook(pageNo, bookName);
return list;
}
}
12、创建loback.xml日志
<?xml version="1.0" encoding="UTF-8"?>
<configuration debug="false">
<!--定义日志文件的存储地址 勿在 LogBack 的配置中使用相对路径-->
<property name="LOG_HOME" value="consumner/consumelog" />
<!-- 控制台输出 -->
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
<encoder class="ch.qos.logback.classic.encoder.PatternLayoutEncoder">
<!--格式化输出:%d表示日期,%thread表示线程名,%-5level:级别从左显示5个字符宽度%msg:日志消息,%n是换行符-->
<pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{50} - %msg%n</pattern>
</encoder>
</appender>
<!-- 按照每天生成日志文件 -->
<appender name="FILE" class="ch.qos.logback.core.rolling.RollingFileAppender">
<rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
<!--日志文件输出的文件名-->
<FileNamePattern>${LOG_HOME}/%d{yyyy-MM-dd}.log</FileNamePattern>
<!--日志文件保留天数-->
<MaxHistory>30</MaxHistory>
</rollingPolicy>
<encoder class="ch.qos.logback.classic.encoder.PatternLayoutEncoder">
<!--格式化输出:%d表示日期,%thread表示线程名,%-5level:级别从左显示5个字符宽度%msg:日志消息,%n是换行符-->
<pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{50} - %msg%n</pattern>
</encoder>
<!--日志文件最大的大小-->
<triggeringPolicy class="ch.qos.logback.core.rolling.SizeBasedTriggeringPolicy">
<MaxFileSize>10MB</MaxFileSize>
</triggeringPolicy>
</appender>
<!-- show parameters for hibernate sql 专为 Hibernate 定制 -->
<logger name="org.hibernate.type.descriptor.sql.BasicBinder" level="TRACE" />
<logger name="org.hibernate.type.descriptor.sql.BasicExtractor" level="DEBUG" />
<logger name="org.hibernate.SQL" level="DEBUG" />
<logger name="org.hibernate.engine.QueryParameters" level="DEBUG" />
<logger name="org.hibernate.engine.query.HQLQueryPlan" level="DEBUG" />
<!--myibatis log configure-->
<logger name="com.apache.ibatis" level="TRACE"/>
<logger name="java.sql.Connection" level="DEBUG"/>
<logger name="java.sql.Statement" level="DEBUG"/>
<logger name="java.sql.PreparedStatement" level="DEBUG"/>
<!-- 日志输出级别 -->
<root level="INFO">
<appender-ref ref="STDOUT" />
<appender-ref ref="FILE" />
</root>
<!--日志异步到数据库 -->
<!--<appender name="DB" class="ch.qos.logback.classic.db.DBAppender">-->
<!--<!–日志异步到数据库 –>-->
<!--<connectionSource class="ch.qos.logback.core.db.DriverManagerConnectionSource">-->
<!--<!–连接池 –>-->
<!--<dataSource class="com.mchange.v2.c3p0.ComboPooledDataSource">-->
<!--<driverClass>com.mysql.jdbc.Driver</driverClass>-->
<!--<url>jdbc:mysql://127.0.0.1:3306/databaseName</url>-->
<!--<user>root</user>-->
<!--<password>root</password>-->
<!--</dataSource>-->
<!--</connectionSource>-->
<!--</appender>-->
</configuration>
13、postman接口测试
14、打包并运行测试
选中工程target目录
点击右侧maven下Lifecycle中的package,双击将项目打成jar包
找到target目录下刚刚生成的jar包,右键show in explorer在资源管理器中显示
复制当前文件夹路径
启动cmd,进入jar包所在目录:cd D:\G\IdeaProjects\springboot0101\target
使用java -jar 包名.jar运行:java -jar springboot0101-0.0.1-SNAPSHOT.jar
运行成功!