可使用官網https://start.spring.io/,或者 idea來新建springboot工程。前提條件是安裝好jdk8和maven3.2以上版本。使用的idea也要作好jdk、maven、utf-8編碼格式設置。html
在pom.xml文件,能夠修改springboot的版本號。從新導入maven便可。java
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.1.6.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
若是報數據庫的錯,給註釋 @SpringBootApplication 添加參數。mysql
@SpringBootApplication(exclude = DataSourceAutoConfiguration.class)
由於已經指定了parent是2.1.6.RELEASE版本的spring-boot-starter-parent,這裏web的版本不須要指定。linux
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
添加一個用於測試的controller。訪問 http://localhost:8010/user/test , 正常便可。
nginx
@Controller @RequestMapping("user") public class UserController { @RequestMapping("test") @ResponseBody public String test(){ return "test"; } }
<!-- 熱部署 devtools -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<scope>runtime</scope>
<optional>true</optional>
</dependency>
<!-- lombok -->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
mysql5.7在win和linux下的安裝操做,參考個人其它兩篇博客:「記一次linux下安裝mysql5.7」,「在win下,安裝MySQL5.7」。web
再介紹docker安裝mysql5.7的作法。拉取iamge,docker pull centos/mysql-57-centos7。redis
[root@master ~]# docker images
REPOSITORY TAG IMAGE ID CREATED SIZE
nginx latest a1523e859360 2 weeks ago 127MB
mongo latest bcef5fd2979d 2 weeks ago 386MB
centos/mysql-57-centos7 latest f83a2938370c 5 months ago 452MB
redis 3.2 87856cc39862 17 months ago 76MB
啓動mysql容器。我沒有使用數據卷 -v,掛載到宿主機。spring
docker run -di -p 3306:3306 --name mysql -e MYSQL_ROOT_PASSWORD=123456 centos/mysql-57-centos7
mysql數據庫,建新庫使用utf8字符集,排序建議使用utf8_unicode_xx。sql
創建一張user測試表。docker
CREATE TABLE `user` ( `id` int(11) NOT NULL AUTO_INCREMENT, `created_at` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP, `updated_at` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP, `telphone` varchar(40) COLLATE utf8_unicode_ci NOT NULL DEFAULT '', `password` varchar(200) COLLATE utf8_unicode_ci NOT NULL DEFAULT '', `nick_name` varchar(40) COLLATE utf8_unicode_ci NOT NULL DEFAULT '', `gender` int(11) NOT NULL DEFAULT '0', PRIMARY KEY (`id`), UNIQUE KEY `telphone_unique_index` (`telphone`) USING BTREE ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci
<!-- 數據庫mysql和mybatis-->
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>1.3.1</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.1.3</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.47</version>
</dependency>
刪除啓動類上的 exclude = DataSourceAutoConfiguration.class 這個參數。
spring:
datasource:
type: com.alibaba.druid.pool.DruidDataSource
name: dianpingdb
url: jdbc:mysql://master:3306/dbname?useUnicode=true&characterEncoding=UTF-8
username: root
password: 123456
driver-class-name: com.mysql.jdbc.Driver
mybatis:
mapper-locations: classpath:com/xxx/mapper/*.xml
type-aliases-package: com.xxx.pojo.entity
# 爲了打印sql
logging:
level:
com.xxx.mapper: debug
debug: true
使用mybatis 的逆向工程, 參考 http://mybatis.org/generator/ 。第一步,使用插件。
<build>
<!-- mybatis 逆向工程 -->
<pluginManagement>
<plugins>
<plugin>
<groupId>org.mybatis.generator</groupId>
<artifactId>mybatis-generator-maven-plugin</artifactId>
<version>1.3.5</version>
<dependencies>
<dependency>
<groupId>org.mybatis.generator</groupId>
<artifactId>mybatis-generator-core</artifactId>
<version>1.3.5</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.47</version>
</dependency>
</dependencies>
<executions>
<execution>
<id>mybatis generator</id>
<phase>package</phase>
<goals>
<goal>generate</goal>
</goals>
</execution>
</executions>
<configuration>
<!--容許移動生成的文件-->
<verbose>true</verbose>
<!--容許自動覆蓋文件-->
<overwrite>true</overwrite>
<configurationFile> src/main/resources/mybatis-generator.xml </configurationFile>
</configuration>
</plugin>
</plugins>
</pluginManagement>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
第二步,添加文件 mybatis-generator.xml 。
<!DOCTYPE generatorConfiguration PUBLIC "-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN" "http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd">
<generatorConfiguration>
<context id="simple" targetRuntime="MyBatis3Simple">
<jdbcConnection driverClass="com.mysql.jdbc.Driver" connectionURL="jdbc:mysql://master:3306/dbname" userId="root" password="123456"/>
<!-- 實體類 -->
<javaModelGenerator targetPackage="com.xxx.pojo.entity" targetProject="src/main/java"/>
<!-- xml的mapper文件-->
<sqlMapGenerator targetPackage="com.xxx.mapper" targetProject="src/main/resources"/>
<!-- interface 文件 -->
<javaClientGenerator type="XMLMAPPER" targetPackage="com.xxx.mapper" targetProject="src/main/java"/>
<table tableName="user" enableCountByExample="false" enableUpdateByExample="false" enableDeleteByExample="false" enableSelectByExample="false" selectByExampleQueryId="false">
<generatedKey column="id" sqlStatement="MySql" identity="true" />
</table>
</context>
</generatorConfiguration>
第三步,maven啓動。
mvn mybatis-generator:generate
@GetMapping("get") @ResponseBody public User getUserById(@RequestParam Integer id){ return userService.getUserById(id); }
public interface UserService { User getUserById(Integer id); }
@Service public class UserServiceImpl implements UserService { @Autowired UserMapper userMapper; @Override public User getUserById(Integer id) { return userMapper.selectByPrimaryKey(id); } }
除了mybatis以外,還有集成度更高的 mybatis plus。
好比給定一個 User實體類。
添加依賴
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>3.2.0</version>
</dependency>
對應的 mapper接口
@Repository public interface UserMapper extends BaseMapper<User> { }
以及service
public interface UserService extends IService<User> { }
@Service public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService { }
IService 和 ServiceImpl 都是 mybatis-plus提供的。
在controller裏調用
@Autowired
UserService userService;User user = userService.getById(1L);
import com.fasterxml.jackson.annotation.JsonInclude; import lombok.Builder; import lombok.Data; @Data @Builder public class Result { private int code; private String msg; @JsonInclude(JsonInclude.Include.NON_NULL) private Object data; // 不要返回null值。
public static Result success(Object data) { return Result.builder() .data(data).msg("success").code(200) .build(); } public static Result create(ErrorCode errorCode){ return Result.builder() .msg(errorCode.msg).code(errorCode.code) .build(); } }
新建錯誤碼枚舉類
public enum ErrorCode { OBJECT_NOT_FOUNT(10001, "請求對象不存在"), UNKNOWN_ERROR(10002, "未知錯誤"), NO_HANDLER_FOUND(10003, "找不到頁面,有多是提交的路徑或參數不對。"), PARAMETER_ERROR(10004, "請求的參數不對"), ; public int code; public String msg; ErrorCode(int code, String msg) { this.code = code; this.msg = msg; } }
測試返回內容
@GetMapping("get") @ResponseBody public Result getUserById(@RequestParam Integer id) throws GlobalException { User userById = userService.getUserById(id); if(userById==null){ // 統一返回錯誤碼
return Result.create(ErrorCode.OBJECT_NOT_FOUNT); } return Result.success(userById); }
在錯誤碼的基礎上,新建自定義異常類。
@Data public class GlobalException extends Exception{ private ErrorCode errorCode; public GlobalException(ErrorCode errorCode) { super(); this.errorCode = errorCode; } }
新建異常處理handler的類。
@RestControllerAdvice public class GlobalExceptionHandler { @ExceptionHandler(value = Exception.class) Result handlerException(HttpServletRequest request, HttpServletResponse response, Exception ex){ if(ex instanceof GlobalException){ // 自定義的異常類
GlobalException exception = (GlobalException) ex; return Result.create(exception.getErrorCode()); }else if(ex instanceof NoHandlerFoundException){ // 404 沒找處處理頁面
return Result.create(ErrorCode.NO_HANDLER_FOUND); }else if(ex instanceof MissingServletRequestParameterException){ // 提交的參數不對
return Result.create(ErrorCode.PARAMETER_ERROR); }else { return Result.create(ErrorCode.UNKNOWN_ERROR); } } }
爲了阻止默認的404錯誤頁面,要添加配置。
spring:
#出現錯誤時, 直接拋出異常,如下2個配置都要有。
mvc: throw-exception-if-no-handler-found: true resources: add-mappings: false
參考 https://www.jianshu.com/p/36505ac4d32a
測試controller
@GetMapping("get") @ResponseBody public Result getUserById(@RequestParam Integer id) throws GlobalException { User userById = userService.getUserById(id); if(userById==null){ // 統一返回錯誤碼,固然也能夠。 // return Result.create(ErrorCode.OBJECT_NOT_FOUNT); // 這裏嘗試拋出異常,再統一作自定義的全局異常處理。 throw new GlobalException(ErrorCode.OBJECT_NOT_FOUNT); } return Result.success(userById); }