最近在項目中應用到springboot與mybatis,在進行整合過程中遇到一些坑,在此將其整理出來,便於以後查閱與複習。 項目運行環境為:eclispe+jdk1.8+maven 搭建Spring Boot環境 === 首先建立maven project,在生成的pom文件中加入依賴,代碼如下: ...
最近在項目中應用到springboot與mybatis,在進行整合過程中遇到一些坑,在此將其整理出來,便於以後查閱與複習。
項目運行環境為:eclispe+jdk1.8+maven
搭建Spring Boot環境
首先建立maven project,在生成的pom文件中加入依賴,代碼如下:
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.5.2.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
</dependency>
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>1.3.0</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
<!--分頁插件-->
<dependency>
<groupId>com.github.pagehelper</groupId>
<artifactId>pagehelper-spring-boot-starter</artifactId>
<version>1.2.1</version>
</dependency>
<!-- alibaba的druid資料庫連接池 -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.0.29</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
<!-- mybatis generator 自動生成代碼插件 -->
<plugin>
<groupId>org.mybatis.generator</groupId>
<artifactId>mybatis-generator-maven-plugin</artifactId>
<version>1.3.2</version>
<configuration>
<configurationFile>${basedir}/src/main/resources/generator/generatorConfig.xml</configurationFile>
<overwrite>true</overwrite>
<verbose>true</verbose>
</configuration>
</plugin>
</plugins>
</build>
配置好依賴後進行maven install,此時註意的坑:
坑一:啟動maven install報錯:
[ERROR] Failed to execute goal org.springframework.boot:spring-boot-maven-plugin:1.5.2.RELEASE:repackage (default) on project springboot-mybatis: Execution default of goal org.springframework.boot:spring-boot-maven-plugin:1.5.2.RELEASE:repackage failed: Unable to find main class -> [Help 1]
[ERROR]
[ERROR] To see the full stack trace of the errors, re-run Maven with the -e switch.
[ERROR] Re-run Maven using the -X switch to enable full debug logging.
[ERROR]
[ERROR] For more information about the errors and possible solutions, please read the following articles:
[ERROR] [Help 1] http://cwiki.apache.org/confluence/display/MAVEN/PluginExecutionException
報錯原因是沒有啟動類
解決方法:編寫啟動類Main.java正常運行!
@SpringBootApplication
public class Main {
public static void main(String[] args) {
SpringApplication.run(Main.class, args);
}
}
坑二:啟動maven install報錯:
[ERROR] Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.1:compile (default-compile) on project springboot-mybatis: Compilation failure
[ERROR] No compiler is provided in this environment. Perhaps you are running on a JRE rather than a JDK?
[ERROR] -> [Help 1]
[ERROR]
[ERROR] To see the full stack trace of the errors, re-run Maven with the -e switch.
[ERROR] Re-run Maven using the -X switch to enable full debug logging.
[ERROR]
[ERROR] For more information about the errors and possible solutions, please read the following articles:
[ERROR] [Help 1] http://cwiki.apache.org/confluence/display/MAVEN/MojoFailureException
報錯原因:項目的java環境與電腦環境不符合,例如我的新建項目運行環境為J2SE-1.5,報錯是在我將其改為jre1.8之後
解決方案:
右鍵項目——build path——Configure build path——Libraries——雙擊Jre System Libraries如下圖所示:
選擇Alternate JRE 如2處的下拉框只有jre,點擊3處的Install JREs,依次經過add——Standard VM——next——Directory,選擇本機的jdk位置點擊finish
在install JREs位置將預設勾選更改jdk,如下圖所示,並保存。
再次maven install項目正常。如下所示:
[INFO] BUILD SUCCESS
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 3.351 s
[INFO] Finished at: 2018-09-05T21:20:48+08:00
[INFO] Final Memory: 23M/181M
[INFO] ------------------------------------------------------------------------
在src/main/resources新建文件:application.yml,內容如下所示:
server:
port: 8080
spring:
datasource:
name: test
url: jdbc:mysql://localhost:3306/test
username: root
password: 123456
driver-class-name: com.mysql.jdbc.Driver
## 該配置節點為獨立的節點
mybatis:
mapper-locations: classpath:mapper/*.xml
#pagehelper分頁插件
pagehelper:
helperDialect: mysql
reasonable: true
supportMethodsArguments: true
params: count=countSql
至此springboot環境搭建完畢!
逆向工程應用
首先應該註意到在pom文件中有配置逆向工程xml文件的位置:src/main/resources/generator/generatorConfig.xml
因而在src/main/resources下新建generator文件夾,並建立generatorConfig.xml文件,代碼如下:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE generatorConfiguration PUBLIC "-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN" "http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd">
<generatorConfiguration>
<!-- 資料庫驅動:選擇你的本地硬碟上面的資料庫驅動包-->
<classPathEntry location="E:\plugins\maven\repo\mysql\mysql-connector-java\5.1.41\mysql-connector-java-5.1.41.jar"/>
<context id="DB2Tables" targetRuntime="MyBatis3">
<commentGenerator>
<property name="suppressDate" value="true"/>
<!-- 是否去除自動生成的註釋 true:是 : false:否 -->
<property name="suppressAllComments" value="true"/>
</commentGenerator>
<!--資料庫鏈接URL,用戶名、密碼 -->
<jdbcConnection driverClass="com.mysql.jdbc.Driver" connectionURL="jdbc:mysql://localhost/test" userId="root" password="123456">
</jdbcConnection>
<javaTypeResolver>
<property name="forceBigDecimals" value="false"/>
</javaTypeResolver>
<!-- 生成pojo類的位置-->
<javaModelGenerator targetPackage="com.luis.entity" targetProject="src/main/java">
<property name="enableSubPackages" value="true"/>
<property name="trimStrings" value="true"/>
</javaModelGenerator>
<!-- 生成映射文件的包名和位置-->
<sqlMapGenerator targetPackage="mapper" targetProject="src/main/resources">
<!-- enableSubPackages 是否讓schema作為包的尾碼-->
<property name="enableSubPackages" value="false"/>
</sqlMapGenerator>
<!-- 生成mapper介面的位置-->
<javaClientGenerator type="XMLMAPPER" targetPackage="com.luis.mapper" targetProject="src/main/java">
<!-- enableSubPackages 是否讓schema作為包的尾碼-->
<property name="enableSubPackages" value="false"/>
</javaClientGenerator>
<!-- 指定資料庫表 -->
<table schema="" tableName="user"></table>
</context>
</generatorConfiguration>
根據個人環境將配置文件中的配置進行更改,如資料庫密碼,包名,對應資料庫表
所用的資料庫表如下:
DROP TABLE IF EXISTS `user`;
CREATE TABLE `user` (
`id` bigint(20) NOT NULL,
`name` varchar(255) NOT NULL,
`age` int(4) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
INSERT INTO `user` VALUES ('1', 'wanger', '22');
INSERT INTO `user` VALUES ('2', 'zhangsan', '18');
INSERT INTO `user` VALUES ('3', 'lisi', '23');
INSERT INTO `user` VALUES ('4', 'wangwu', '21');
配置完成後,右鍵項目,選擇run as——Maven build——在下麵兩處分別填入:
Goals: mybatis-generator:generate -e
Profiles: generatorConfig.xml
如下圖所示:
出現如下所示,代碼生成成功,刷新項目即可。
[INFO] Generating Example class for table user
[INFO] Generating Record class for table user
[INFO] Generating Mapper Interface for table user
[INFO] Generating SQL Map for table user
[INFO] Saving file UserMapper.xml
[INFO] Saving file UserExample.java
[INFO] Saving file User.java
[INFO] Saving file UserMapper.java
[INFO] ------------------------------------------------------------------------
[INFO] BUILD SUCCESS
[INFO] ------------------------------------------------------------------------
需要註意的是:逆向工程生成的代碼不會覆蓋,因而不能重覆多次生成。
此處也有個小坑,逆向工程的代碼生成後,啟動項目會報如下錯誤:
***************************
APPLICATION FAILED TO START
***************************
Description:
Field userMapper in com.luis.service.impl.UserServiceImpl required a bean of type 'com.luis.mapper.UserMapper' that could not be found.
Action:
Consider defining a bean of type 'com.luis.mapper.UserMapper' in your configuration.
解決方案:
1、給生成的mapper介面文件前加註解:@Mapper 即可解決。但需要給每一個mapper文件前加,繁瑣,因而有第二種類解決辦法
2、在啟動類前加@MapperScan({"com.luis.mapper"}),其中com.luis.mapper為mapper文件的所在位置。
參考自:http://412887952-qq-com.iteye.com/blog/2392672
分頁應用
逆向工程已經生成了entity類,及dao層的mapper介面與*mapper.xml文件,因而/只用編寫service層與web層。
首先在UserService中編寫介面,代碼如下:
public interface UserService {
User selectByName(String name);
List<User> findAllUser(int pageNum, int pageSize);
}
在UserServiceImpl文件進行實現,代碼如下所示:
@Service
public class UserServiceImpl implements UserService {
@Autowired
private UserMapper userMapper;
@Override
public User selectByName(String name) {
UserExample example = new UserExample();
Criteria criteria = example.createCriteria();
criteria.andNameEqualTo(name);
List<User> users = userMapper.selectByExample(example);
if (users != null && users.size() > 0) {
return users.get(0);
}
return null;
}
/**
* pageNum 開始頁數
* pageSize 每頁顯示的數據條數
*/
@Override
public List<User> findAllUser(int pageNum, int pageSize) {
//將參數傳給方法實現分頁
PageHelper.startPage(pageNum, pageSize);
UserExample example = new UserExample();
List<User> list = userMapper.selectByExample(example);
return list;
}
}
最後在controller層對查詢結果進行接收,UserController代碼如下:
@Controller
@RestController
public class UserController {
@Autowired
private UserService userService;
@RequestMapping("/test")
public User querUserByName() {
User user = userService.selectByName("luis");
System.out.println(user.toString());
return user;
}
@RequestMapping("/list")
public List<User> querUser() {
List<User> list = userService.findAllUser(1, 2);
//獲取分頁信息
PageInfo<User> pageInfo = new PageInfo<>(list);
System.out.println("total:" + pageInfo.getTotal());
System.out.println("pages:" + pageInfo.getPages());
System.out.println("pageSize:" + pageInfo.getPageSize());
return list;
}
}
測試
此前在項目編寫過程中已經對可能出現的錯誤進行了總結,最後,對項目的功能進行測試,通過加@RestController註解將數據傳輸到瀏覽器中。
測試mybatis與springboot,瀏覽器輸入http://localhost:8080/test,瀏覽器輸出:
{"id":1,"name":"wanger","age":22}
分頁測試,瀏覽器輸入http://localhost:8080/list,瀏覽器輸出:
[{"id":1,"name":"wanger","age":22},{"id":2,"name":"zhangsan","age":18}]
eclipse輸出:
total:4
pages:2
pageSize:2
項目搭建完畢,具體代碼參見github
本文參考了:
http://412887952-qq-com.iteye.com/blog/2392672
https://blog.csdn.net/rico_rico/article/details/79408474
https://blog.csdn.net/winter_chen001/article/details/77249029