In the last article< SpringBook Advanced Tutorial (60) Build multiple modules under the intellij idea project (Part 1) > In this article, we have introduced how to divide multiple modules after creating a project in intellij idea, and today we will give you a brief overview of the breakdown of the detailed work among the modules. If you don't consider subdividing multiple modules, take a look at this article< Introduction to Spring Boot (1) Explain intellij idea Building Spring Boot>.
v Design Database
CREATE TABLE `useraccount` ( `id` int(10) unsigned NOT NULL AUTO_INCREMENT, `username` varchar(255) NOT NULL, `age` int(10) NOT NULL, `phone` bigint NOT NULL, `email` varchar(255) NOT NULL, `account` varchar(100) NOT NULL UNIQUE, `pwd` varchar(255) NOT NULL, PRIMARY KEY (`id`) )ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8; insert into `useraccount` values(1,'Zhao(dev)',23,158,'qq@qq.com','test001','test001'); insert into `useraccount` values(2,'money(dev)',27,136,'126@126.com','test002','test002'); insert into `useraccount` values(3,'Grandchildren(dev)',31,159,'163@163.com','test003','test003'); insert into `useraccount` values(4,'plum(dev)',35,130,'sina@sina.com','test004','test004'); select * from `useraccount`;
v Introduces mybatis
1.0 Add mybatis plug-in
Add mybatis plug-in to pom.xml of learn-persist.
<build> <plugins> <plugin> <groupId>org.mybatis.generator</groupId> <artifactId>mybatis-generator-maven-plugin</artifactId> <version>${mybatis-generator.version}</version> <dependencies> <dependency> <groupId> mysql</groupId> <artifactId> mysql-connector-java</artifactId> <version>${mysql.version}</version> </dependency> <dependency> <groupId>org.mybatis.generator</groupId> <artifactId>mybatis-generator-core</artifactId> <version>${mybatis-generator.version}</version> </dependency> </dependencies> <configuration> <!-- Auto-generated configuration --> <configurationFile>src/main/resources/mybatis-config/mybatis-generator.xml</configurationFile> <!--Allow moving generated files --> <verbose>true</verbose> <!-- Coverage or not --> <overwrite>false</overwrite> </configuration> </plugin> </plugins> </build>
As shown above, under resources of learn-persist, create mapper and mybatis-config file directories respectively, and add jdbc.properties and mybatis-generator.xml files.
1.1 jdbc.properties
jdbc.driverClassName=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/mytest?useSSL=false
jdbc.username=toutou
jdbc.password=demo123456
1.2 mybatis-generator.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> <properties resource="mybatis-config/jdbc.properties"/> <context id="DB2Tables" targetRuntime="MyBatis3"> <commentGenerator> <property name="suppressDate" value="true"/> <property name="suppressAllComments" value="true"/> </commentGenerator> <!--Database Link Address Account Password--> <jdbcConnection driverClass="com.mysql.jdbc.Driver" connectionURL="${jdbc.url}" userId="${jdbc.username}" password="${jdbc.password}"> </jdbcConnection> <javaTypeResolver> <property name="forceBigDecimals" value="false"/> </javaTypeResolver> <javaModelGenerator targetPackage="learn.model.po" targetProject="../learn-model/src/main/java/"> <property name="enableSubPackages" value="false" /> <property name="trimStrings" value="true" /> </javaModelGenerator> <sqlMapGenerator targetPackage="mapper" targetProject="../learn-persist/src/main/resources"> <property name="enableSubPackages" value="false" /> </sqlMapGenerator> <javaClientGenerator targetPackage="learn.persist" targetProject="../learn-persist/src/main/java/" type="XMLMAPPER"> <property name="enableSubPackages" value="false" /> </javaClientGenerator> <!--Generate corresponding tables and class names--> <table tableName="useraccount" domainObjectName="UserAccount" enableCountByExample="false" enableUpdateByExample="false" enableDeleteByExample="false" enableSelectByExample="false" selectByExampleQueryId="false"></table> </context> </generatorConfiguration>
More information about mybatis-generator.xml can be seen Here.
Unified Configuration of Version 1.3 Number
In order to facilitate subsequent management, the version numbers of all plug-ins are unified in the pom.xml of the project (hello learning). The pom.xml of each sub-module (such as learning-persist) is directly used by the method of ${}.
For example, add < mybatis-generator.version > 1.3.6 </mybatis-generator.version > to the pom.xml attribute of hellolearn s, and use < version >${mybatis-generator.version} </version > directly in pom.xml of learn-persist.
Note that the code label section in "For example" above has spaces for escape, preventing browsers from recognizing "mybatis-generator.version" and "version" as html labels.
1.4 Maven Project Plug-in
As shown above, in the Maven project on the right side of idea, you can find the corresponding plug-in of mybatis-generator. If you can't find it, right-click learn-persist in the maven project, and then click generate sources....
1.5 Run the mybatis generator plug-in
As shown above, clicking on the mybatis generator:generator plug-in will generate three files marked red on the left.
v Write controller
2.0 Add result to return entity class
11111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111
2.1 Add controller
package learn.web.controller;
import learn.model.vo.Result;
import learn.model.vo.UserAccountVO;
import learn.service.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
/**
* @author toutou
* @date by 2019/07
*/
@RestController
public class UserController {
@Autowired
UserAccountService userAccountService;
@GetMapping("/user/hello")
public String helloWorld() {
return "hello world.";
}
@GetMapping("/user/getuser")
public Result getUserAccountById(@RequestParam("uid") int id){
UserAccountVO user = userAccountService.getUserAccountById(id);
if(user != null){
return Result.setSuccessResult(user);
}else{
return Result.setErrorResult(404, "user does not exist");
}
}
}
Note: getUserAccountById is not available for the time being, you can not add it first.
2.2 Add aplication startup class
package learn.web; import org.mybatis.spring.annotation.MapperScan; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.context.annotation.ComponentScan; /** * Created by toutou on 2019/7 */ @SpringBootApplication @ComponentScan(basePackages = {"learn.*" }) @MapperScan(basePackages = {"learn.persist"}) public class Application { public static void main(String[] args) { SpringApplication.run(Application.class, args); } }
2.3 Add aplication.properties
server.port=8300
spring.profiles.active=@env@
#mybatis
mybatis.mapper-locations = classpath:mapper/*Mapper.xml
2.4 Configuration Startup Class
2.5 Test results
v Writing service
3.1 Add Service
package learn.service; import learn.model.vo.UserAccountVO; /** * @author toutou * @date by 2019/07 */ public interface UserAccountService { UserAccountVO getUserAccountById(Integer id); }
3.2 Implementing Service
package learn.service.impl; import learn.model.po.UserAccount; import learn.model.vo.UserAccountVO; import learn.persist.UserAccountMapper; import learn.service.UserAccountService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; /** * @author toutou * @date by 2019/07 */ @Service public class UserAccountServiceImpl implements UserAccountService{ @Autowired UserAccountMapper userMapper; public UserAccountVO getUserAccountById(Integer id){ UserAccountVO accountVO = null; UserAccount account = userMapper.selectByPrimaryKey(id); if (account != null) { accountVO = new UserAccountVO(); accountVO.setId(account.getId()); accountVO.setAccount(account.getAccount()); accountVO.setAge(account.getAge()); accountVO.setEmail(account.getEmail()); accountVO.setUsername(account.getUsername()); accountVO.setPhone(account.getPhone()); } return accountVO; } }
v configuration settings
4.1 Add application.properties
4.2 Add application.dev.properties
spring.datasource.url=jdbc:mysql://localhost:3306/mytest?useSSL=false&useUnicode=true&characterEncoding=utf-8&zeroDateTimeBehavior=convertToNull&serverTimezone=GMT%2b8 spring.datasource.username=toutou spring.datasource.password=demo123456 spring.datasource.driver-class-name=com.mysql.jdbc.Driver
4.3 Add pom.xml configuration
4.3.1 hellolearn pom.xml
4.3.2 learn-web pom.xml
<build> <filters> <filter>src/main/resources/config/application-${env}.properties</filter> </filters> </build>
4.4 Update the application startup class
4.5 Test results
vlinux deployment spring boot
5.1 Add plug-ins to learn-web pom.xml
<build> <filters> <filter>src/main/resources/config/application-${env}.properties</filter> </filters> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> <configuration> <mainClass>learn.web.Application</mainClass> <classifier>exec</classifier> </configuration> <executions> <execution> <goals> <goal>repackage</goal> </goals> </execution> </executions> </plugin> </plugins> </build>
5.2 Add plug-ins to Hello learn pom. XML
<build> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-jar-plugin</artifactId> <version>3.0.2</version> <configuration> <excludes> <exclude>**/profiles/</exclude> <exclude>**/mybatis-generator/</exclude> </excludes> </configuration> </plugin> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-compiler-plugin</artifactId> <configuration> <source>1.8</source> <target>1.8</target> </configuration> </plugin> </plugins> </build>
Note: exclude if profile file directory is used.
5.3 Packaged Deployment
java -jar learn-web-0.0.1-SNAPSHOT-exec.jar --server.port=95
Problems you may encounter:
- Spring boot Field required a bean of type that could not be found
- Caused by: java.lang.IllegalStateException: Ambiguous mapping found. Cannot map 'xxxController' bean method
- Mybatis-generator's Maven plug-in uses exception (mybatis-generator-maven-plugin): generate failed: Exception get JDBC Driver
- maven appears: Failed to execute goal on project...: Can not resolve dependencies for project...
- Execution default of goal org. spring framework. boot: spring-boot-maven-plugin: 1.5.
- Failed to configure a DataSource: 'url' attribute is not specified and no embedded datasource could be configured.
v source address
https://github.com/toutouge/javademosecond/tree/master/hellolearn
Author: Please call me Brother Chief
Origin: http://www.cnblogs.com/toutou/
About the author: Focus on the project development of the basic platform. If you have any questions or suggestions, please give me more advice.
Copyright Statement: Copyright of this article is shared by the author and the blog park. Reproduction is welcomed, but this statement must be retained without the author's consent, and a link to the original text is given in a clear place on the article page.
I hereby declare that all comments and personal letters will be answered at the first time. We also welcome people in the garden to correct their mistakes and make progress together. perhaps Direct private trust I
Support Blogger: If you think the article is helpful to you, you can click on the bottom right corner of the article.[Recommend ] Just a minute. Your encouragement is the author's greatest motivation to stick to original and continuous writing!