Recently springboot and mybatis have been applied in the project, and some pits have been encountered in the process of integration. Here, they are sorted out for future reference and review.
The running environment of the project is: eclispe+jdk1.8+maven
Build Spring Boot Environment
Firstly, the maven project is established, and the dependency is added to the generated pom file. The code is as follows:
<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> <!--jPaginate--> <dependency> <groupId>com.github.pagehelper</groupId> <artifactId>pagehelper-spring-boot-starter</artifactId> <version>1.2.1</version> </dependency> <!-- alibaba Of druid Database connection pool --> <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 Automatic Generation Code Plug-in --> <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>
After configuring the dependencies, maven install, the pits to be noticed at this time:
Pit 1: Start maven install to report errors:
[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
The reason for the error is that there is no boot class
Solution: Write the startup class Main.java to run normally!
@SpringBootApplication public class Main { public static void main(String[] args) { SpringApplication.run(Main.class, args); } }
Pit 2: Start maven install to report errors:
[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
The reason for the error: The java environment of the project does not match the computer environment. For example, my new project runs in J2SE-1.5. The error was reported after I changed it to jre1.8.
Solution:
Right-click project -- build path -- Configure build path -- Libraries -- double-click Jre System Libraries as shown in the following figure:
Select the drop-down box at Alternate JRE such as 2, only jre, click Install JREs at 3, then go through add - Standard VM - next - Directory, select the jdk location of the machine and click finish.
In the install JREs location, change jdk by default, as shown in the figure below, and save.
Once again, the maven install project is normal. As follows:
[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] ------------------------------------------------------------------------
New file in src/main/resources: application.yml, as follows:
server: port: 8080 spring: datasource: name: test url: jdbc:mysql://localhost:3306/test username: root password: 123456 driver-class-name: com.mysql.jdbc.Driver ## The configuration node is a standalone node mybatis: mapper-locations: classpath:mapper/*.xml #pagehelper paging plug-in pagehelper: helperDialect: mysql reasonable: true supportMethodsArguments: true params: count=countSql
So far, the springboot environment has been built!
Reverse Engineering Application
First of all, it should be noted that there is a location in the pom file to configure the reverse engineering XML file: src/main/resources/generator/generatorConfig.xml
Therefore, under src/main/resources, create a new generator folder and create a generator Config.xml file. The code is as follows:
<?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> <!-- Database Driver:Select the database driver package on your local hard disk--> <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"/> <!-- Whether to remove automatically generated comments true: Yes, false:no --> <property name="suppressAllComments" value="true"/> </commentGenerator> <!--Database Links URL,User name, password --> <jdbcConnection driverClass="com.mysql.jdbc.Driver" connectionURL="jdbc:mysql://localhost/test" userId="root" password="123456"> </jdbcConnection> <javaTypeResolver> <property name="forceBigDecimals" value="false"/> </javaTypeResolver> <!-- generate pojo Class location--> <javaModelGenerator targetPackage="com.luis.entity" targetProject="src/main/java"> <property name="enableSubPackages" value="true"/> <property name="trimStrings" value="true"/> </javaModelGenerator> <!-- Generate the package name and location of the mapping file--> <sqlMapGenerator targetPackage="mapper" targetProject="src/main/resources"> <!-- enableSubPackages Whether to let schema Suffixes for packages--> <property name="enableSubPackages" value="false"/> </sqlMapGenerator> <!-- generate mapper Location of interface--> <javaClientGenerator type="XMLMAPPER" targetPackage="com.luis.mapper" targetProject="src/main/java"> <!-- enableSubPackages Whether to let schema Suffixes for packages--> <property name="enableSubPackages" value="false"/> </javaClientGenerator> <!-- Specify database tables --> <table schema="" tableName="user"></table> </context> </generatorConfiguration>
Change the configuration file according to the personal environment, such as database password, package name, corresponding database table
The database tables used are as follows:
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');
When the configuration is complete, right-click on the project and select run as - Maven build - to fill in the following two places respectively:
Goals: mybatis-generator:generate -e
Profiles: generatorConfig.xml
As shown in the following figure:
As shown below, the code generation is successful and the project can be refreshed.
[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] ------------------------------------------------------------------------
It should be noted that the code generated by reverse engineering will not be overwritten, so it can not be generated repeatedly.
There is also a small pit here. After the code of reverse engineering is generated, the start-up project will report the following error:
*************************** 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.
Solution:
1. Note the generated mapper interface file: @Mapper can be solved. But each mapper file needs to be pre-added, which is cumbersome, so there is a second kind of solution.
2. Add @MapperScan({"com.luis.mapper"} before starting the class, where com.luis.mapper is the location of the mapper file.
Reference: http://412887952-qqq-com.iteye.com/blog/2392672
Paging application
Reverse engineering has generated entity classes, mapper interfaces and * mapper.xml files for the dao layer, so / only the service layer and web layer are written.
First, write the interface in UserService, the code is as follows:
public interface UserService { User selectByName(String name); List<User> findAllUser(int pageNum, int pageSize); }
Implemented in the UserService Impl file, the code is as follows:
@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 Start page number * pageSize Number of data bars displayed per page */ @Override public List<User> findAllUser(int pageNum, int pageSize) { //Paging by passing parameters to the method PageHelper.startPage(pageNum, pageSize); UserExample example = new UserExample(); List<User> list = userMapper.selectByExample(example); return list; } }
Finally, the query results are received at the controller layer. The UserController code is as follows:
@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); //Getting Paging Information 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; } }
test
Previously, the possible errors have been summarized in the process of project writing. Finally, the function of the project has been tested, and the data will be transmitted to the browser by adding @RestController annotation.
Test mybatis and spring boot, browser input http://localhost:8080/test, browser output:
{"id":1,"name":"wanger","age":22}
Paging test, browser input http://localhost:8080/list, browser output:
[{"id":1,"name":"wanger","age":22},{"id":2,"name":"zhangsan","age":18}]
eclipse output:
total:4 pages:2 pageSize:2
The project is completed. See the code for details. github
This article refers to:
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