在上一篇文章《SpringBoot 进阶教程 (六十)intellij idea project 下建多个 module(上)》中, 我们已经介绍了在 intellij idea 中创建 project 之后再分化多个 module, 今天再大致介绍介绍各个 module 之间详细工作的细分. 如果是不考虑细分多个 module 的话, 可以看看这篇文章《SpringBoot 入门教程(一) 详解 intellij idea 搭建 SpringBoot》.
v 设计数据库
- 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,'qq@qq.com','test001','test001');
- insert into `useraccount` values(2,'钱(dev)',27,136,'126@126.com','test002','test002');
- insert into `useraccount` values(3,'孙(dev)',31,159,'163@163.com','test003','test003');
- insert into `useraccount` values(4,'李(dev)',35,130,'sina@sina.com','test004','test004');
- select * from `useraccount`;
v 引入 mybatis
1.0 添加 mybatis 插件
在 learn-persist 的 pom.xml 中添加 mybatis 插件.
- <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>
- <!-- 自动生成的配置 -->
- <configurationFile>src/main/resources/mybatis-config/mybatis-generator.xml</configurationFile>
- <!-- 允许移动生成的文件 -->
- <verbose>true</verbose>
- <!-- 是否覆盖 -->
- <overwrite>false</overwrite>
- </configuration>
- </plugin>
- </plugins>
- </build>
如上图, 在 learn-persist 的 resources 下分别创建 mapper 和 mybatis-config 文件目录, 并添加 jdbc.properties 和 mybatis-generator.xml 文件.
- 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>
- <!-- 数据库链接地址账号密码 -->
- <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>
mybatis-generator.xml 更多介绍可以看这里.
1.3 版本号统一配置
为了方便后续管理, 将所有引入插件的版本号统一放在 project(hellolearn)的 pom.xml 中统一控制, 各子 module(如 learn-persist)的 pom.xml 中直接用 ${}的方法使用.
例如: 在 hellolearn 的 pom.xml 属性中添加 < mybatis-generator.version>1.3.6</mybatis-generator.version>, 在 learn-persist 的 pom.xml 中直接 < version>${mybatis-generator.version}</version > 使用即可.
注意上面的 "例如" 中代码标签部分有空格是为了转义的, 防止浏览器将 "mybatis-generator.version" 和 "version" 识别为 html 标签.
1.4 Maven Project 插件
如上图, 在 idea 右侧的 maven project 中就可以了对应的找到 mybatis-generator 的插件, 如果找不到就右键 maven project 中的 learn-persist, 然后点击 generate sources....
1.5 运行 mybatis generator 插件
如上图, 点击运行 mybatis generator:generator 插件, 会对应生成左侧标红的三个文件.
v 编写 controller
2.0 添加 result 返回实体类
11111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111
2.1 添加 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, "用户不存在");
- }
- }
- }
注意: getUserAccountById 暂时用不上, 可以先不添加.
2.2 添加 aplication 启动类
- 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 添加 aplication.properties
- server.port=8300
- spring.profiles.active=@env@
- #mybatis
- mybatis.mapper-locations = classpath:mapper/*Mapper.xml
- 2.4 配置启动类
- 2.5 测试效果
- v 编写 service
- 3.1 添加 Service
- package learn.service;
- import learn.model.vo.UserAccountVO;
- /**
- * @author toutou
- * @date by 2019/07
- */
- public interface UserAccountService {
- UserAccountVO getUserAccountById(Integer id);
- }
- 3.2 实现 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 配置设置
- 4.1 添加 application.properties
- 4.2 添加 application.dev.properties
- spring.datasource.url=jdbc:MySQL://localhost:3306/mytest?useSSL=false&useUnicode=true&characterEncoding=utf-8&zeroDateTimeBehavior=convertToNull&serverTimezone=GMT+8
- spring.datasource.username=toutou
- spring.datasource.password=demo123456
- spring.datasource.driver-class-name=com.MySQL.jdbc.Driver
- 4.3 添加 pom.xml 配置
- 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 更新 application 启动类
- 4.5 测试效果
- vlinux 部署 springboot
- 5.1 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 hellolearn 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>
注意: 如果有用到 profiles 文件目录则 exclude.
5.3 打包部署
java -jar learn-Web-0.0.1-SNAPSHOT-exec.jar --server.port=95
你可能会遇到的问题:
- 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 插件使用异常(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 项目打包时报错 Execution default of goal org.springframework.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 源码地址
作 者: 请叫我头头哥
来源: https://www.cnblogs.com/toutou/p/project_module_2.html