您的位置:首页 > 编程语言 > Java开发

[置顶] WEB开发----spring boot与mybatis整合

2017-08-30 17:53 876 查看
上一篇已经完成了spring boot项目的搭建Spring Boot项目快速搭建 ,接下来这篇要跟mybatis来进行整合

1. mybatis访问数据库

1.1 首先对pom.xml文件进行修改,加入必要的jar包支持

<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>
<groupId>test-spring-boot</groupId>
<artifactId>test-springboot-web</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>war</packaging>
<!-- spring boot -->
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.4.0.RELEASE</version>
</parent>

<dependencies>
<!-- spring boot web支持:mvc,aop... -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!-- 对jsp的支持 -->
<dependency>
<groupId>org.apache.tomcat.embed</groupId>
<artifactId>tomcat-embed-jasper</artifactId>
</dependency>
<!-- mysql驱动 -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>6.0.6</version>
</dependency>
<!-- mybatis-spring-boot驱动 -->
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>1.1.1</version>
</dependency>
<!--热部署-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>com.github.pagehelper</groupId>
<artifactId>pagehelper</artifactId>
<version>4.1.0</version>
</dependency>
</dependencies>

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


1.2 在application.properties文件中完成对数据库的配置信息,本文采用的mysql数据库

#修改服务器端口号
server.port=8081
#返回的前缀   目录对应src/main/webapp下
spring.mvc.view.prefix: /
#返回的后缀
spring.mvc.view.suffix: .jsp
#mysql连接
spring.datasource.url = jdbc:mysql://localhost:3306/testsql?useUnicode=true&characterEncoding=UTF-8&serverTimezone=UTC&useSSL=false
spring.datasource.username = root
spring.datasource.password = 123456
spring.datasource.driverClassName = com.mysql.jdbc.Driver
spring.datasource.max-active=20
spring.datasource.max-idle=8
spring.datasource.min-idle=8

#-- 数据库是Oracle的设定格式 --
#jdbc.driverClassName=[驱动名称]
#jdbc.url=jdbc:oracle:thin:@[数据库地址或IP]:[端口]:[实例名]
#jdbc.username=[用户名]
#jdbc.password=[密码]
#【示例】
#jdbc.driverClassName=oracle.jdbc.driver.OracleDriver
#jdbc.url=jdbc:oracle:thin:@xxx.xxx.xxx.xxx:1521:functionsampledb
#jdbc.username=xxxxx
#jdbc.password=xxxxx

#-- 数据库是PostgreSQL的设定格式 --
#jdbc.driverClassName=[驱动名称]
#jdbc.url=jdbc:postgresql://[数据库地址或IP]:[端口号]/[数据库名称]
#jdbc.username=[用户名]
#jdbc.password=[密码]
#【示例】
#jdbc.driverClassName=org.postgresql.Driver
#jdbc.url=jdbc:postgresql://localhost:5432/functionsampledb
#jdbc.username=postgres
#jdbc.password=sa


1.3 然后新增接口RootMapper,实体Root,及Service层代码文件

RootMapper接口

package com.dao;

import java.util.List;

import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;

import com.pojo.Root;

@Mapper
public interface RootMapper {
int deleteByPrimaryKey(Integer rootId);

int insert(Root record);

int insertSelective(Root record);

@Select("select root_id as rootId,root_pid as rootPid,root_name as rootName from root where root_id = #{rootId}")
Root selectByPrimaryKey(@Param("rootId") Integer rootId);

int updateByPrimaryKeySelective(Root record);

int updateByPrimaryKey(Root record);

}


Root实体类

package com.pojo;

public class Root {
private Integer rootId;

private Integer rootPid;

private String rootName;

public Integer getRootId() {
return rootId;
}

public void setRootId(Integer rootId) {
this.rootId = rootId;
}

public Integer getRootPid() {
return rootPid;
}

public void setRootPid(Integer rootPid) {
this.rootPid = rootPid;
}

public String getRootName() {
return rootName;
}

public void setRootName(String rootName) {
this.rootName = rootName == null ? null : rootName.trim();
}

@Override
public String toString() {
return "Root [rootId=" + rootId + ", rootPid=" + rootPid + ", rootName=" + rootName + "]";
}

}


Service接口:

public interface RootService {
/**
* 通过id主键查询数据
* @return
*/
public Root selectByPrimaryKey(Integer id);
}


serviceImpl实现:

@Service("rootService")
public class RootServiceImpl implements RootService {

@Autowired
private RootMapper rootMapper;

@Override
public Root selectByPrimaryKey(Integer id) {
// TODO Auto-generated method stub
return this.rootMapper.selectByPrimaryKey(id);
}
}


1.4 Controller层完成与前台的交互

@Controller
@RequestMapping("/root")
public class RootController {

private static Logger logger = Logger.getLogger(RootController.class);

@Autowired
private RootService rootservice = null;

@GetMapping(value = "/rootId/{id}")
@ResponseBody
public String rootById(@PathVariable("id") String id ) {
logger.info("通过id进行Root查询,id是:" + id);
Root root = rootservice.selectByPrimaryKey(Integer.parseInt(id));
if (root == null) {
return "no data!";
} else {
System.out.println(root.getRootName());
return root.getRootName();
}
}
}


1.5 前台index.jsp页面,放于src/main/webapp下面

交互采用了ajax异步请求,需要引入jquery.js支持,将它放在src/main/resource下的static/js下面

<%@ page language="java" contentType="text/html; charset=utf-8"
pageEncoding="utf-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>

<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<script type="text/javascript" src="${pageContext.request.contextPath}/js/jquery-3.2.1.js"></script>
<title>index页面</title>
</head>
<body>
id:<
125e1
input type="text" id="txtId"><span id="contentSpan"></span><br/>
<input type="button" value="查询" id="searchBtn"><input type="button" value="查询所有" id="searchAllBtn">

<script type="text/javascript">
$(function() {
$("#searchBtn").click(function() {
var id = $("#txtId").val();
$.get("${pageContext.request.contextPath}/root/rootId/"+id,"", function (data) {
$("#contentSpan").text(data.toString());
})
})
});
</script>
</body>
</html>


最终目录结构:



运行App.class文件,在浏览器输入地址
http://127.0.0.1:8081/index.jsp
测试效果:



1.6 这样的话,访问数据库的sql语句是写在接口dao方法上面的,与平常写在***Mapper.xml还不一样,然后需要继续修改文件,把sql语句写到xml文件中

在src/main/resource文件夹下面添加一个config文件夹,在里面添加一个application.yml文件:进行mapper文件夹下面的xml扫描

mybatis:
mapperLocations: classpath:mapper/*.xml




如果使用多个数据源DataSource的话,需要继续配置,Spring Boot配置多个DataSource

2. 数据信息分页PageHelper

2.1 添加数据分页查询–PageHelper

最后我们添加一个mybatis-config.xml配置文件,里面包含数据分页插件

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE configuration
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">

<configuration>
<properties>
<property name="dialect" value="mysql" />
</properties>
<settings>
<!-- 这个配置使全局的映射器启用或禁用缓存。系统默认值是true,设置只是为了展示出来 -->
<setting name="cacheEnabled" value="true" />
<!-- 全局启用或禁用延迟加载。当禁用时,所有关联对象都会即时加载。 系统默认值是true,设置只是为了展示出来 -->
<setting name="lazyLoadingEnabled" value="true" />
<!-- 允许或不允许多种结果集从一个单独的语句中返回(需要适合的驱动)。 系统默认值是true,设置只是为了展示出来 -->
<setting name="multipleResultSetsEnabled" value="true" />
<!--使用列标签代替列名。不同的驱动在这方便表现不同。参考驱动文档或充分测试两种方法来决定所使用的驱动。 系统默认值是true,设置只是为了展示出来 -->
<setting name="useColumnLabel" value="true" />
<!--允许 JDBC 支持生成的键。需要适合的驱动。如果设置为 true 则这个设置强制生成的键被使用,尽管一些驱动拒绝兼容但仍然有效(比如
Derby)。 系统默认值是false,设置只是为了展示出来 -->
<setting name="useGeneratedKeys" value="false" />
<!--配置默认的执行器。SIMPLE 执行器没有什么特别之处。REUSE 执行器重用预处理语句。BATCH 执行器重用语句和批量更新 系统默认值是SIMPLE,设置只是为了展示出来 -->
<setting name="defaultExecutorType" value="SIMPLE" />
<!--设置超时时间,它决定驱动等待一个数据库响应的时间。 系统默认值是null,设置只是为了展示出来 -->
<setting name="defaultStatementTimeout" value="25000" />
</settings>
<plugins>
<plugin interceptor="com.github.pagehelper.PageHelper">
<!-- 设置数据库类型 Oracle,Mysql,MariaDB,SQLite,Hsqldb,PostgreSQL六种数据库-->
<property name="dialect" value="mysql" />
<property name="offsetAsPageNum" value="true" />
<property name="rowBoundsWithCount" value="true" />
<property name="pageSizeZero" value="true" />
<property name="reasonable" value="true" />
</plugin>
</plugins>
</configuration>


在application.yml文件添加对mybatis-config.xml的扫描:

mybatis:
mapperLocations: classpath:mapper/*Mapper.xml
configLocation: classpath:/mybatis-config.xml


pom.xml添加PageHelper的jar(pom.xml文件已经有了)

<!-- pagehelper分页插件 -->
<dependency>
<groupId>com.github.pagehelper</groupId>
<artifactId>pagehelper</artifactId>
<version>4.1.0</version>
</dependency>


这样就已经设置好了PageHelper分页工具了

2.2 分页插件测试

在dao接口层添加一个全部查询的方法(为了方便,直接在方法上面添加注解执行sql):

@Select("select root_id as rootId,root_pid as rootPid,root_name as rootName from root ")
List<Root> selectAll();


在Service层进行dao层方法的调用,无需业务逻辑,就不贴代码了

最后在Controller层添加测试方法:

@GetMapping(value = "/rootAll")
@ResponseBody
public void rootAll(Model model) {
logger.info("查询所有的root数据" );
PageHelper.startPage(1, 3, "root_name");
List<Root> roots = rootservice.selectAll();
//方法一
Page<Root> rootPage = (Page<Root>)roots;
if (rootPage == null) {
System.out.println("no data!");
} else {
//输出总的数量
System.out.println(rootPage.getTotal());
for(Root r:rootPage){
System.out.println(r.getRootName());
}
}
/*      方法二
PageInfo<Root> pages = new PageInfo<Root>(roots);
if (pages.getList() == null) {
System.out.println("no data!");
} else {
System.out.println(pages.getTotal());
for(Root r:pages.getList()){
System.out.println(r.getRootName());
}
}*/
}


在页面访问该方法就可以获取到分页的数据了,也可以通过字段排序查询,并且直接获取到表中总的数据

2.3 分页查询功能

首先该项目没有使用其他前段框架,数据使用table来表格来显示,使用jstl对后台获取的集合数据进行遍历,所以先修改pom.xml文件添加jstl支持

jstl标签的使用需要在jsp页面添加支持
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>


该功能要实现首页,下一页上一页,末页,每页显示几条数据等功能.

<!-- jstl -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>


然后创建一个页面,用于显示数据信息的页面:

<%@ page language="java" contentType="text/html; charset=utf-8"
pageEncoding="utf-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
<style type="text/css">
</style>
</head>
<body>
<table style="border:1px #ccc solid;width:600px">
<thead style="background:#ddd">
<tr>
<td>RootID</td>
<td>RootName</td>
<td>RootPID</td>
</tr>
</thead>
<tbody>
<c:forEach var="r" items="${rootPage }">
<tr class="trCls">
<td>${r.rootId }</td>
<td>${r.rootName }</td>
<td>${r.rootPid }</td>
</tr>
</c:forEach>
</tbody>
</table>

<input id="first" type="button" value="首页" />
<input id="back" type="button" value="上一页" />
<input id="next" type="button" value="下一页" />
<input id="end" type="button" value="末页"  />
<label>nowPage:<span style="color:red" id="nowPage">${pageNum }</span></label>/
<label>sumPage:<span style="color:red" id="sumPage">${pages }</span></label>
<label>total:<b>${total }</b></label>

<script type="text/javascript">
$(function(){
$("tbody>tr:even").css("background","#faffff");
$("tbody>tr:odd").css("background","#fffaff");

//首页
$("#first").click(function() {
var pageSize = $("#pageSize").val();
$("#rootListBody").load("${pageContext.request.contextPath}/root/rootAll",
{"pageNum":"1","pageSize":pageSize,"orderBy":""});
});
//末页
$("#end").click(function() {
var end = $("#sumPage").text();
var pageSize = $("#pageSize").val();
$("#rootListBody").load("${pageContext.request.contextPath}/root/rootAll",
{"pageNum":end,"pageSize":pageSize,"orderBy":""});
});
//上一页
$("#back").click(function() {
var pageNum = parseInt($("#nowPage").text())-1;
var pageSize = $("#pageSize").val();
$("#rootListBody").load("${pageContext.request.contextPath}/root/rootAll",
{"pageNum":pageNum,"pageSize":pageSize,"orderBy":""});
});
//下一页
$("#next").click(function() {
var pageNum = parseInt($("#nowPage").text())+1;
var pageSize = $("#pageSize").val();
$("#rootListBody").load("${pageContext.request.contextPath}/root/rootAll",
{"pageNum":pageNum,"pageSize":pageSize,"orderBy":""});
});
})
</script>
</style>
</body>
</html>


上面的页面是用来引用的,类似于一个gird,需要在index.jsp中显示,

修改index.jsp页面

<%@ page language="java" contentType="text/html; charset=utf-8"
pageEncoding="utf-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>

<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<script type="text/javascript" src="${pageContext.request.contextPath}/js/jquery-3.2.1.js"></script>
<title>index页面</title>
</head>
<body>
id:<input type="text" id="txtId"><span id="contentSpan"></span><br/>
<input type="button" value="search" id="searchBtn"><input type="button" value="searchAll" id="searchAllBtn">
<label id="pageSizeLabel" style="display:none;margin-left:350px">每页数据:</label>
<select id="pageSize" style="display:none">
<option>3</option>
<option>5</option>
<option>10</option>
<option>20</option>
</select>
<div id="rootListBody">
</div>
<script type="text/javascript">
$(function() {
//通过id查询名字
$("#searchBtn").click(function() {
var id = $("#txtId").val();
$.get("${pageContext.request.contextPath}/root/rootId/"+id,"", function (data) {
$("#contentSpan").text(data.toString());
})
});
//查询所有,有分页
$("#searchAllBtn").click(function() {
$("#pageSizeLabel,#pageSize").show();
$("#rootListBody").load("${pageContext.request.contextPath}/root/rootAll",
{"pageNum":"","pageSize":"3","orderBy":""});

});
//分页下拉框
$("#pageSize").change(function(){
var pageSize = $("#pageSize").val();
var pageNum = $("#nowPage").text();
$("#rootListBody").load("${pageContext.request.contextPath}/root/rootAll",
{"pageNum":pageNum,"pageSize":pageSize,"orderBy":""});
})

});
</script>
</body>
</html>


最后修改Controller层的分页查询方法:

@PostMapping(value = "/rootAll")
public String rootAll(Model model,HttpServletRequest request) {
Integer pageNum = request.getParameter("pageNum") != "" ? Integer.parseInt(request.getParameter("pageNum")) : 1;
Integer pageSize = request.getParameter("pageSize") != "" ? Integer.parseInt(request.getParameter("pageSize")) : 3;
String orderBy = request.getParameter("orderBy") != "" ? request.getParameter("orderBy") : null;

logger.info("查询所有的root数据:第"+pageNum+"页,每页"+pageSize+"条,排序字段:"+orderBy);

PageHelper.startPage(pageNum, pageSize);
if(orderBy != null && !orderBy.equals(""))
PageHelper.orderBy("orderBy");
List<Root> roots = rootservice.selectAll();
Page<Root> rootPage = (Page<Root>)roots;
if (rootPage !=null) {
model.addAttribute("rootPage", rootPage);
model.addAttribute("total", rootPage.getTotal());
model.addAttribute("pageNum", rootPage.getPageNum());
model.addAttribute("pages", rootPage.getPages());
}
return "/page-list-root";
/*      PageInfo<Root> pages = new PageInfo<Root>(roots);
if (pages.getList() == null) {
System.out.println("no data!");
} else {
System.out.println(pages.getTotal());
for(Root r:pages.getList()){
System.out.println(r.getRootName());
}
}*/
}


最终实现效果

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: