上一篇文章,寫了如何搭建一個簡單的Spring boot項目,本篇是接着上一篇文章寫得:Spring boot入門:快速搭建Spring boot項目(一),主要是spring boot集成mybatis和pagehelpercss
關於mybatis和pagehelper的介紹,能夠自行博客,網上不少相似的博客,這裏,我直接上代碼和項目搭建教程。html
在配置文件application.yml中配置MySql數據庫鏈接池和Mybatis掃描包以及PageHelper分頁插件前端
mybatis:
mapper-locations: classpath:mapper/*.xml
type-aliases-package: com.tswc.edu.entity
mapper:
mappers:
- com.tswc.edu.util.MyMapper
not-empty: false
identity: MYSQL
#identity: SQLSERVER
pagehelper:
helperDialect: MYSQL
reasonable: true
supportMethodsArguments: true
params: count=countSql
spring:
datasource:
type: com.alibaba.druid.pool.DruidDataSource
driverClassName: com.mysql.jdbc.Driver
url: jdbc:mysql://127.0.0.1:3306/edu?useUnicode=true&characterEncoding=utf8
username: root
password: 123456
initialSize: 1
minIdle: 3
maxActive: 20
# 配置獲取鏈接等待超時的時間
maxWait: 60000
# 配置間隔多久才進行一次檢測,檢測須要關閉的空閒鏈接,單位是毫秒
timeBetweenEvictionRunsMillis: 60000
# 配置一個鏈接在池中最小生存的時間,單位是毫秒
minEvictableIdleTimeMillis: 30000
validationQuery: select 'x'
testWhileIdle: true
testOnBorrow: false
testOnReturn: false
# 打開PSCache,而且指定每一個鏈接上PSCache的大小
poolPreparedStatements: true
maxPoolPreparedStatementPerConnectionSize: 20
# 配置監控統計攔截的filters,去掉後監控界面sql沒法統計,'wall'用於防火牆
filters: stat,wall,slf4j
# 經過connectProperties屬性來打開mergeSql功能;慢SQL記錄
connectionProperties: druid.stat.mergeSql=true;druid.stat.slowSqlMillis=5000
# 合併多個DruidDataSource的監控數據
#useGlobalDataSourceStat: true
複製代碼
同時,須要在pom.xml中添加相應的jar包依賴,若是存在jar包沒法下載,能夠手動下載,而後放到相應的jar包文件夾中java
這裏面須要注意Spring boot和mybatis的jar包之間的版本,sping boot2+要求高版本,eg:spring boot2+不能識別pagehelper1.2如下的版本
<!--mybatis -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.6</version>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.4.4</version>
</dependency>
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>1.1.1</version>
</dependency>
<!--druid -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.0.28</version>
</dependency>
<!--mapper-->
<dependency>
<groupId>tk.mybatis</groupId>
<artifactId>mapper-spring-boot-starter</artifactId>
<version>2.1.0</version>
</dependency>
<!--pagehelper,Spring boot2.0+只能設備pagehelper1.2+-->
<dependency>
<groupId>com.github.pagehelper</groupId>
<artifactId>pagehelper-spring-boot-starter</artifactId>
<version>1.2.5</version>
</dependency>
複製代碼
(1).更新入口主文件,主要增長了一些註解,mysql
此處須要注意@MapperSca的引用,這裏有2個可引用的包,分別是tk.mybatis.spring.annotation.MapperScan和org.mybatis.spring.annotation.MapperScan;git
tk.mybatis.spring.annotation.MapperScan:爲mubatis帶的mapper掃描文件,org.mybatis.spring.annotation.MapperScan爲spring自帶的掃描文件,在低版本的mybatis上,2個包能夠隨意使用,可是Spring boot2+後,增長了一些特性(建議閱讀spring boot2+的底層代碼,加深理解),致使只能使用高版本的mtbatis,同時spring自帶的MapperScan也沒法使用,因此使用sping boot2+後,須要引用高版本的mybatis,同時這裏只能使用mybatis的MapperScan的掃描包;spring在後期更新中,應該也會使其可以用於boot中github
@ServletComponentScan
@MapperScan(basePackages = "com.tswc.edu.mapper")
@SpringBootApplication
public class EduApplication {
public static void main(String[] args) {
SpringApplication.run(EduApplication.class, args);
}
}
複製代碼
若是在項目正常,啓動,可是在使用mybatis時,報此類錯誤:web
後臺錯誤:沒法獲取實體類對應的表名!spring
2018-12-14 20:09:25.967 ERROR 29024 --- [nio-8085-exec-1] o.a.c.c.C.[.[.[/].[dispatcherServlet] : Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed; nested exception is tk.mybatis.mapper.MapperException: 沒法獲取實體類com.tswc.edu.entity.Index對應的表名!] with root caus 2
tk.mybatis.mapper.MapperException: 沒法獲取實體類com.tswc.edu.entity.Index對應的表名!
at tk.mybatis.mapper.mapperhelper.EntityHelper.getEntityTable(EntityHelper.java:69) ~[mapper-core-1.1.0.jar:na]
at tk.mybatis.mapper.entity.Example.<init>(Example.java:103) ~[mapper-core-1.1.0.jar:na]
at tk.mybatis.mapper.entity.Example.<init>(Example.java:88) ~[mapper-core-1.1.0.jar:na]
at tk.mybatis.mapper.entity.Example.<init>(Example.java:78) ~[mapper-core-1.1.0.jar:na]
at com.tswc.edu.service.IndexService.getList(IndexService.java:33) ~[classes/:na]
at com.tswc.edu.controller.IndexController.list(IndexController.java:35) ~[classes/:na]
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:1.8.0_151]
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) ~[na:1.8.0_151]
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:1.8.0_151]
at java.lang.reflect.Method.invoke(Method.java:498) ~[na:1.8.0_151]
at org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:189) ~[spring-web-5.1.3.RELEASE.jar:5.1.3.RELEASE]
at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:138) ~[spring-web-5.1.3.RELEASE.jar:5.1.3.RELEASE]
at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:102) ~[spring-webmvc-5.1.3.RELEASE.jar:5.1.3.RELEASE]
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:895) ~[spring-webmvc-5.1.3.RELEASE.jar:5.1.3.RELEASE]
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:800) ~[spring-webmvc-5.1.3.RELEASE.jar:5.1.3.RELEASE]
at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:87) ~[spring-webmvc-5.1.3.RELEASE.jar:5.1.3.RELEASE]
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:1038) ~[spring-webmvc-5.1.3.RELEASE.jar:5.1.3.RELEASE]
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:942) ~[spring-webmvc-5.1.3.RELEASE.jar:5.1.3.RELEASE]
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:1005) ~[spring-webmvc-5.1.3.RELEASE.jar:5.1.3.RELEASE]
at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:897) ~[spring-webmvc-5.1.3.RELEASE.jar:5.1.3.RELEASE]
at javax.servlet.http.HttpServlet.service(HttpServlet.java:634) ~[tomcat-embed-core-9.0.13.jar:9.0.13]
at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:882) ~[spring-webmvc-5.1.3.RELEASE.jar:5.1.3.RELEASE]
at javax.servlet.http.HttpServlet.service(HttpServlet.java:741) ~[tomcat-embed-core-9.0.13.jar:9.0.13]
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:231) ~[tomcat-embed-core-9.0.13.jar:9.0.13]
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-9.0.13.jar:9.0.13]
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53) ~[tomcat-embed-websocket-9.0.13.jar:9.0.13]
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) ~[tomcat-embed-core-9.0.13.jar:9.0.13]
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-9.0.13.jar:9.0.13]
at org.springframework.web.filter.RequestContextFilter.doFilterInternal(RequestContextFilter.java:99) ~[spring-web-5.1.3.RELEASE.jar:5.1.3.RELEASE]
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) ~[spring-web-5.1.3.RELEASE.jar:5.1.3.RELEASE]
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) ~[tomcat-embed-core-9.0.13.jar:9.0.13]
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-9.0.13.jar:9.0.13]
at org.springframework.web.filter.FormContentFilter.doFilterInternal(FormContentFilter.java:92) ~[spring-web-5.1.3.RELEASE.jar:5.1.3.RELEASE]
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) ~[spring-web-5.1.3.RELEASE.jar:5.1.3.RELEASE]
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) ~[tomcat-embed-core-9.0.13.jar:9.0.13]
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-9.0.13.jar:9.0.13]
at org.springframework.web.filter.HiddenHttpMethodFilter.doFilterInternal(HiddenHttpMethodFilter.java:93) ~[spring-web-5.1.3.RELEASE.jar:5.1.3.RELEASE]
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) ~[spring-web-5.1.3.RELEASE.jar:5.1.3.RELEASE]
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) ~[tomcat-embed-core-9.0.13.jar:9.0.13]
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-9.0.13.jar:9.0.13]
at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:200) ~[spring-web-5.1.3.RELEASE.jar:5.1.3.RELEASE]
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) ~[spring-web-5.1.3.RELEASE.jar:5.1.3.RELEASE]
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) ~[tomcat-embed-core-9.0.13.jar:9.0.13]
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-9.0.13.jar:9.0.13]
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:199) ~[tomcat-embed-core-9.0.13.jar:9.0.13]
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:96) [tomcat-embed-core-9.0.13.jar:9.0.13]
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:490) [tomcat-embed-core-9.0.13.jar:9.0.13]
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:139) [tomcat-embed-core-9.0.13.jar:9.0.13]
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:92) [tomcat-embed-core-9.0.13.jar:9.0.13]
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:74) [tomcat-embed-core-9.0.13.jar:9.0.13]
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:343) [tomcat-embed-core-9.0.13.jar:9.0.13]
at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:408) [tomcat-embed-core-9.0.13.jar:9.0.13]
at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:66) [tomcat-embed-core-9.0.13.jar:9.0.13]
at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:791) [tomcat-embed-core-9.0.13.jar:9.0.13]
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1417) [tomcat-embed-core-9.0.13.jar:9.0.13]
at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49) [tomcat-embed-core-9.0.13.jar:9.0.13]
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149) [na:1.8.0_151]
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624) [na:1.8.0_151]
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61) [tomcat-embed-core-9.0.13.jar:9.0.13]
at java.lang.Thread.run(Thread.java:748) [na:1.8.0_151]
複製代碼
前端錯誤是500sql
Whitelabel Error Page
This application has no explicit mapping for /error, so you are seeing this as a fallback.
Fri Dec 14 20:09:25 CST 2018
There was an unexpected error (type=Internal Server Error, status=500).
???????com.tswc.edu.entity.Index?????!
複製代碼
那麼,就是Mapper掃描包使用有誤
(2).通用接口mapper:此接口不能被掃描到,不然會報錯,能夠在application.yml中,排除此包的掃描
public interface MyMapper<T> extends Mapper<T> {
//TODO
//FIXME 特別注意,該接口不能被掃描到,不然會出錯
}
複製代碼
(3).後臺代碼,控制村層>服務層>接口
@Controller
public class IndexController {
@Autowired
private IndexService indexService;
@RequestMapping(value = "/index")
public void list(ModelMap modelMap) {
List<Index> list = indexService.getList();
modelMap.put("list", list);
}
}
複製代碼
@Service
public class IndexService {
@Autowired
private IndexMapper indexMapper;
public List<Index> getList() {
Example example = new Example(Index.class);
example.setTableName("index_test");
Criteria criteria = example.createCriteria();
criteria.andEqualTo("age", 20);
return indexMapper.selectByExample(example);
}
}
複製代碼
public interface IndexMapper extends MyMapper<Index> {
}
複製代碼
@Table(name = "index_test")
public class Index implements Serializable, IDynamicTableName {
private static final long serialVersionUID = -8709793124943394842L;
@Transient
private String dynamicTableName;
private String name;
private Integer age;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
@Override
public String getDynamicTableName() {
return null;
}
}
複製代碼
最後一個類爲實體類,建議在創建實體類的時候,統一加上@Table的註解,方便後期Mybatis的使用,同時也提升了代碼的規範性。固然,若是咱們使用Mybatis的代碼生成器,那麼均會自動加上註解(代碼生成器在後期的博客中會講到)
(4).前端ftl代碼
<!DOCTYPE html>
<html>
<head lang="en">
<title>Spring Boot Demo - FreeMarker</title>
<link href="/css/index.css" rel="stylesheet" />
</head>
<body>
<table>
<#list list as user>
<tr>
<td>第${user_index+1}個用戶</td>
<td>用戶名:${user.name}</td>
<td>年 齡: ${user.age}</td>
</tr>
</#list>
</table>
</body>
</html>
複製代碼
(5).添加mybatis的空配置文件,因爲spring boot中,數據庫是經過配置文件的形式,因此此文件是空的,可是沒有此文件,mybatis就沒法經過;固然,也能夠經過在此文件做用配置數據庫鏈接池的方式鏈接數據(已過期)
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD SQL MAP Config 3.1//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
<settings>
<setting name="callSettersOnNulls" value="true"/>
</settings>
</configuration>
複製代碼
(6).數據庫以下:添加了幾條測試數據:
(7).啓動項目,並訪問http://localhost:8085/index,結果以下:
最終,項目代碼的機構,以下: