SpringBoot集成MyBatis
什么是MyBatis
MyBatis是非常优秀的持久层的框架,它支持定制化SQL,存储过程以及针对SQL的高级映射。可以通过注解的方式
来实现针对SQL的增删改查的操作以及其他的SQL的操作。下面通过具体的案例实现一个简单的书籍管理系统的操作。
引入Maven依赖
在Maven工程的pom.xml的文件中引入Maven的依赖,具体如下:
<!--集成MyBatis-->
<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>
完善application.yaml
下来在resources下创建db文件夹,然后新增schema.sql的,里面主要是创建表的SQL脚本,以及同事完善配置文件
application.yaml,配置文件的信息具体如下:
spring:
devtools:
restart:
enabled: true
profiles:
active: dev
datasource:
driver-class-name: com.mysql.jdbc.Driver
url: jdbc:mysql://101.43.158.84:3306/book?useUnicode=true&characterEncoding=UTF-8&useSSL=false&serverTimezone=Asia/Shanghai
username: root
password: 123456
type: com.alibaba.druid.pool.DruidDataSource
schema: classpath:db/schema.sql
在schema.sql的SQL脚本具体为:
DROP TABLE IF EXISTS `books`;
CREATE TABLE `books` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`author` varchar(255) DEFAULT NULL,
`publish` varchar(255) DEFAULT NULL,
`count` int(11) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
实现对象建模
在model的包中创建Books类,定义详细的字段信息,完整的代码具体如下:
package com.example.dbplus.model;
import lombok.Data;
@Data
public class Books
{
private int id;
private String author;
private String publish;
private int count;
}
实体与数据表的映射
下面详细的实现实体与数据表的映射关系,也就是实现增删改查的业务逻辑和信息,完整的代码如下:
package com.example.dbplus.dao;
import com.example.dbplus.model.Books;
import org.apache.ibatis.annotations.*;
import java.util.List;
@Mapper
public interface BooksMapper
{
//查看具体某一本书籍信息
@Select("select * from books where id=#{id}")
Books bookID(@Param("id") int id);
//查看所有的书籍信息
@Select("select * from books")
List<Books> books();
//插入书籍信息
@Insert("insert into books(author,publish,count) values(#{author},#{publish},#{count})")
int add(Books books);
//删除某一本书籍信息
@Delete("delete from books where id=#{id}")
int delBookID(int id);
//修改书籍信息
@Update("update books set author=#{author},publish=#{publish},count=#{count} where id=#{id}")
int setBookID(Books books);
}
Controller层实现API
下来在Controller层来实现具体的业务逻辑,完整的代码具体如下:
package com.example.dbplus.controller;
import com.example.dbplus.dao.BooksMapper;
import com.example.dbplus.model.Books;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;
@RestController
@RequestMapping("/book")
public class BooksController
{
@Autowired
BooksMapper booksMapper;
@RequestMapping("/lists")
List<Books> books()
{
return booksMapper.books();
}
@RequestMapping("/list")
Books bookID(int id)
{
return booksMapper.bookID(id);
}
@RequestMapping("/add")
String add(Books books)
{
return booksMapper.addBook(books)==1?"添加书籍成功":"添加书籍失败";
}
@RequestMapping("/set")
String setBook(Books books)
{
return booksMapper.setBookID(books)==1?"修改书籍成功":"修改书籍失败";
}
@RequestMapping("/del")
String delBook(int id)
{
return booksMapper.delBookID(id)==1?"修改书籍成功":"修改书籍失败";
}
}
下来使用PostMan就可以调用了。但是展示的数据会比较多,所以要增加分页的特性,这样的目的是数据展示起来
更加的友好。
分页依赖
下来增加分页的依赖特性,具体的依赖如下:
<!--增加分页的特性-->
<dependency>
<groupId>com.github.pagehelper</groupId>
<artifactId>pagehelper</artifactId>
<version>4.1.6</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
编写分页配置类
下面开始编写分页的配置类,完整的代码如下:
package com.example.dbplus.config;
import com.github.pagehelper.PageHelper;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import java.util.Properties;
@Configuration
public class PageHelperConfig
{
@Bean
public PageHelper pageHelper()
{
PageHelper pageHelper=new PageHelper();
Properties properties=new Properties();
properties.setProperty("offsetAsPageNum","true");
properties.setProperty("rowBoundsWithCount","true");
properties.setProperty("reasonable","true");
pageHelper.setProperties(properties);
return pageHelper;
}
}
实现分页控制层
在配置层实现的基础上,下面详细的实现分页的控制层,完整的代码如下:
@RequestMapping("/listsize")
public Page<Books> getBooksList(Integer pageNum,Integer pageSize)
{
PageHelper.startPage(pageNum,pageSize);
Page<Books> booksList=booksMapper.getBooksList();
return booksList;
}
引入Druid
druid是非常优秀的监控SQL的平台,下来详细的介绍下怎么引入这部分。
引入Maven的依赖
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid-spring-boot-starter</artifactId>
<version>1.1.21</version>
</dependency>
增加配置层
引入druid,必须要编写配置层,配置层的代码具体如下:
package com.example.dbplus.config;
import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.support.http.StatViewServlet;
import com.alibaba.druid.support.http.WebStatFilter;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.boot.web.servlet.ServletRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import javax.sql.DataSource;
import java.util.HashMap;
import java.util.Map;
@Configuration
public class DruidConfig
{
@ConfigurationProperties(prefix = "spring.datasource")
@Bean
public DataSource druidDataSource()
{
return new DruidDataSource();
}
@Bean
public ServletRegistrationBean statViewServlet()
{
ServletRegistrationBean<StatViewServlet> bean=new ServletRegistrationBean<StatViewServlet>(new StatViewServlet(),"/druid/*");
/* druid后台需要有人来登录*/
Map<String,String> initParas=new HashMap<String,String>();
initParas.put("loginUsername","admin");
initParas.put("loginPassword","123456");
initParas.put("allow","");
initParas.put("resetEnable","flase");
bean.setInitParameters(initParas);
return bean;
}
@Bean
public FilterRegistrationBean webStatFilter()
{
FilterRegistrationBean bean=new FilterRegistrationBean();
bean.setFilter(new WebStatFilter());
bean.addUrlPatterns("/*");
Map<String,String> initParams=new HashMap<String,String>();
initParams.put("exclusions","*.js,*.css,/druid/*");
bean.setInitParameters(initParams);
return bean;
}
}
druid配置
下面增加druid的配置,所有的配置文件都是在application.yaml里面编写的,详细的配置具体如下:
#druid的配置信息
druid:
initial-size: 10
max-active: 100
mid-idle: 10
max-wait: 6000
filters: stat, wall
stat-view-servlet:
enabled: true
login-username: admin
login-password: 123456
启动后,在浏览器中访问http://localhost:8080/druid/login.html就会显示登录的界面,输入账户和密码,登录进去后的
主页页面为:

使用PostMan请求,就可以看到URL这部分的请求耗时,集体如下所示:

感谢您的阅读!

浙公网安备 33010602011771号