Intellij Idea project is an example of how to create multiple modules in intellij Idea. Today I will briefly introduce the breakdown of the detailed work between modules. If you do not consider subdividing multiple modules, you can take a look at this article “SpringBoot introduction tutorial (a) detailed explanation of Intellij IDEA build SpringBoot”.

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,' dev ',23,158,'[email protected]','test001','test001'); insert into 'useraccount' values(1,' dev ',23,158,'[email protected]','test001','test001'); Insert into 'useraccount' values(2,' dev ',27,136,'[email protected]','test002','test002'); insert into 'useraccount' values(2,' dev ',27,136,'[email protected]','test002','test002'); Insert into 'useraccount' VALUES (3,' dev ',31,159,'[email protected]','test003','test003'); Insert into 'useraccount' values(4,' dev ',35,130,'[email protected]','test004','test004'); insert into 'userAccount' values(4,' dev ',35,130,'[email protected]','test004','test004'); select * from `useraccount`;Copy the code

V is the introduction of mybatis

1.0 Add myBatis plug-in

Add the mybatis plug-in to pom.xml in the learn-Persist file.

<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> <! - automatically generate configuration - > < configurationFile > SRC/main/resources/mybatis config/mybatis - generator. XML < / configurationFile > <! -- Allow moving generated files --> <verbose>true</verbose> <! False </overwrite> </configuration> </plugins> </build>Copy the code

As shown above, create mapper and mybatis-config file directories under the Resources of learn-persist, and add jdbc.properties and mybatis-generator.xml files, respectively.

JDBC 1.1. The properties

jdbc.driverClassName=com.mysql.jdbc.Driver jdbc.url=jdbc:mysql://localhost:3306/mytest? useSSL=false jdbc.username=toutou jdbc.password=demo123456Copy the code

1.2 mybatis generator. XML

<? The 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> <! <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> <! --> <table tableName=" userAccount "domainObjectName=" userAccount" enableCountByExample="false" enableUpdateByExample="false" enableDeleteByExample="false" enableSelectByExample="false" selectByExampleQueryId="false"></table> </context> </generatorConfiguration>Copy the code

More information about mybatis-generator.xml can be found here.

1.3 Unified version Configuration

For the convenience of subsequent management, the version numbers of all introduced plug-ins are unified in pom.xml of project(Hellolearn), and directly used in pom.xml of each sub-module (such as learn-persist) by ${} method.

Such as: Add < mybatis-generator. Version >1.3.6< /mybatis-generator. Version > to the pom.xml attribute of Hellolearn, Use < version>${mybatis-generator.version}< /version> in the learn-persist pop.xml file.

Note that the “for example” section of the code tag has Spaces to escape, preventing the browser from recognizing “mybatis-generator.version” and “version” as HTML tags.

1.4 Maven Project plug-in

Find the plugin for Mybatis -Generator in maven Project. If you can’t find it, right-click the Learn-persist plugin in Maven Project and click Generate Sources… .

1.5 Run the Mybatis Generator plug-in

As shown above, click to run mybatis Generator: Generator plug-in, which will generate three files marked red on the left.

V write controller

2.0 Add result to return the entity class

package learn.model.vo; import java.io.Serializable; /** * @author toutou * @date by 2019/07 */ public class Result<T> implements Serializable { public int code; public String message; public T data; public int getCode() { return code; } public void setCode(int code) { this.code = code; } public String getMessage() { return message; } public void setMessage(String message) { this.message = message; } public T getData() { return data; } public void setData(T data) { this.data = data; } public static <T> Result<T> setSuccessResult(T t){ Result<T> r = new Result<T>(); r.setCode(200); r.setData(t); r.setMessage("success"); return r; } public static <T> Result<T> setErrorResult(int tempCode, String messageTemp){ Result<T> r = new Result<T>(); r.setCode(tempCode); r.setMessage(messageTemp); return r; }}Copy the code

2.1 add the 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 "); }}}Copy the code
Note: getUserAccountById is not needed at this time.Copy the code

2.2 Adding aplication startup

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); }}Copy the code

 

2.3 add the aplication. The properties

server.port=8300
spring.profiles.active=@env@

#mybatis
mybatis.mapper-locations = classpath:mapper/*Mapper.xml
Copy the code

2.4 Configuring the startup class

2.5 Test Effect

V writing service

3.1 add the Service

package learn.service;

import learn.model.vo.UserAccountVO;

/**
 * @author toutou
 * @date by 2019/07
 */
public interface UserAccountService {
    UserAccountVO getUserAccountById(Integer id);
}
Copy the code

3.2 implementation 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;
    }
}
Copy the code

V Configuration Settings

4.1 add application. The 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.DriverCopy the code

4.3 Adding the 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>
Copy the code

4.4 Updating the Application startup class

4.5 Test Effect

Vlinux deployment springboot

Add a plug-in to 5.1 Learning-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>Copy the code

5.2 Hellolearn Pom.xml plug-in added

<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> </plugins> </build>Copy the code

Note: Exclude if useful to the Profiles file directory.

5.3 Packaged Deployment

Java - jar learn - web - 0.0.1 - the SNAPSHOT - exec. Jar - server port = 95

Questions 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-maven-plugin: Generate failed: Exception getting JDBC Driver
  • Maven Failed to execute goal on project… : Could not resolve dependencies for project …
  • Spring boot package Execution times wrong default of goal org. Springframework. The boot: spring – the boot – maven – plugin: 1.5.
  • Failed to configure a DataSource: ‘url’ attribute is not specified and no embedded datasource could be configured.

V Source code address

Github.com/toutouge/ja…

About the author: Focus on basic platform project development. If you have any questions or suggestions, please feel free to comment! Copyright notice: The copyright of this article belongs to the author and the blog garden, welcome to reprint, but without the consent of the author must retain this statement, and give the original text link in a prominent place on the page of the article. For the record: all comments and messages will be answered as soon as possible. You are welcome to correct your mistakes and make progress together. Or direct private message I support the blogger: if you think the article is helpful to you, you can click on the lower right corner of the article [recommendation]. Your encouragement is the author to adhere to the original and continuous writing of the biggest power! \