Springboot 整合 MyBatis(一):跑起來

0x1 環境java

  1. 系統:Windows 10 mysql

  2. IDE:IntelliJ IDEA 2018.3 x64git

0x2 建立項目github

  1.建立一個SpringBoot項目web

    選擇Spring Initailizr >Nextspring

    

    

    簡單配置便可>Nextsql

    

    選擇項目所需依賴>Next數據庫

    

    選擇項目工做空間[隨便寫]:目錄不存在會自動建立 > Next springboot

    

    建立好後,idea就會加載依賴包,並彈出提示,Meven項目須要導入依賴,選擇自動導包mybatis

    

    等待一會....當右下角沒有進度條就說明好了

  2. 建立項目結構

    這三個文件能夠刪除

    

 

    依次建立目錄:controller層,domain層(entity),mapper層,query層,service層,建立好就是這樣子......

    

  

注意:本文不使用application.properties文件 而使用更加簡潔的application.yml文件,可能大家已經注意到了項目中有四個 yml文件這是爲何?

  由於如今一個項目有好多環境,開發環境,測試環境,準生產環境,生產環境,每一個環境的參數不一樣,因此咱們就能夠把每一個環境的參數配置到 yml文件中

  在Spring Boot中多環境配置文件名須要知足application-{profile}.yml的格式,其中{profile}對應你的環境標識,好比:

    application.yml:主文件
    application-dev.yml:開發環境
    application-test.yml:測試環境
    application-prod.yml:生產環境

  須要加載那個文件就在在 application.yml 文件中經過spring.profiles.active屬性來設置,其值對應{profile}值。好比

    

 

  建立數據庫表

    

CREATE TABLE `user` (
  `id` BIGINT(32) NOT NULL AUTO_INCREMENT,
  `userName` varchar(32) NOT NULL,
  `passWord` varchar(50) NOT NULL,
  `realName` varchar(32) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8;

 

 

  3. 完善結構

①User.java     

 1 package xyz.bit1024.sunny.domain;
 2 
 3 /**
 4  * @ClassName User
 5  * @Date 2019-06-15 16:14
 6  * @Author xiaozhi
 7  * @Version 1.0.0
 8  * @Since JDK 1.8
 9  * @Description 實體類
10  */
11 public class User {
12     private Long id;
13     private String userName;
14     private String passWord;
15     private String realName;
16 
17     public Long getId() {
18         return id;
19     }
20 
21     public void setId(Long id) {
22         this.id = id;
23     }
24 
25     public String getUserName() {
26         return userName;
27     }
28 
29     public void setUserName(String userName) {
30         this.userName = userName;
31     }
32 
33     public String getPassWord() {
34         return passWord;
35     }
36 
37     public void setPassWord(String passWord) {
38         this.passWord = passWord;
39     }
40 
41     public String getRealName() {
42         return realName;
43     }
44 
45     public void setRealName(String realName) {
46         this.realName = realName;
47     }
48 
49     @Override
50     public String toString() {
51         return "User{" +
52                 "id=" + id +
53                 ", userName='" + userName + '\'' +
54                 ", passWord='" + passWord + '\'' +
55                 ", realName='" + realName + '\'' +
56                 '}';
57     }
58 }

 

筆者按:在實體類中覆寫toString方法有助於查錯---<阿里巴巴Java開發手冊>

 

UserMapper.java 

 1 package xyz.bit1024.sunny.mapper;
 2 
 3 import xyz.bit1024.sunny.domain.User;
 4 
 5 import java.util.List;
 6 
 7 /**
 8  * @ClassName UserMapper
 9  * @Date 2019-06-15 16:21
10  * @Author xiaozhi
11  * @Version 1.0.0
12  * @Since JDK 1.8
13  * @Description
14  */
15 public interface UserMapper {
16     List<User> listAll();
17 }

 

    

UserQuery.java 查詢對象   

 1 package xyz.bit1024.sunny.query;
 2 
 3 /**
 4  * @ClassName UserQuery
 5  * @Date 2019-06-15 16:28
 6  * @Author xiaozhi
 7  * @Version 1.0.0
 8  * @Since JDK 1.8
 9  * @Description
10  */
11 public class UserQuery {
12 }

 

 

IUserService.java:接口層,面向接口思想  

 1 package xyz.bit1024.sunny.service;
 2 
 3 import xyz.bit1024.sunny.domain.User;
 4 
 5 import java.util.List;
 6 
 7 /**
 8  * @ClassName IUserService
 9  * @Date 2019-06-15 16:17
10  * @Author xiaozhi
11  * @Version 1.0.0
12  * @Since JDK 1.8
13  * @Description
14  */
15 public interface IUserService {
16 
17     /**
18      * 所有用戶
19      * @return List<User>
20      */
21     List<User> listAll();
22 }

 

 

    

在service 層下建立 impl 目錄,並在impl目錄下面建立 IUserService 實現類並實現覆寫父類方法

UserServiceImpl.java

 1 package xyz.bit1024.sunny.service.impl;
 2 
 3 import org.springframework.beans.factory.annotation.Autowired;
 4 import org.springframework.stereotype.Service;
 5 import xyz.bit1024.sunny.domain.User;
 6 import xyz.bit1024.sunny.mapper.UserMapper;
 7 import xyz.bit1024.sunny.service.IUserService;
 8 
 9 import java.util.List;
10 
11 /**
12  * @ClassName UserServiceImpl
13  * @Date 2019-06-15 16:19
14  * @Author xiaozhi
15  * @Version 1.0.0
16  * @Since JDK 1.8
17  * @Description 實現類[業務類]
18  */
19 @Service
20 public class UserServiceImpl implements IUserService {
21 
22     @Autowired
23     private UserMapper userMapper;
24 
25     @Override
26     public List<User> listAll() {
27         return userMapper.listAll();
28     }
29 }

 

     

⑥ 在resources 建立mapper目錄,並建立 UserMapper.xml

 1 <?xml version="1.0" encoding="UTF-8"?>
 2 <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
 3 <mapper namespace="xyz.bit1024.sunny.mapper.UserMapper">
 4     <resultMap id="BaseResultMap" type="xyz.bit1024.sunny.domain.User">
 5         <result column="id" jdbcType="BIGINT" property="id" />
 6         <result column="userName" jdbcType="VARCHAR" property="userName" />
 7         <result column="passWord" jdbcType="VARCHAR" property="passWord" />
 8         <result column="realName" jdbcType="VARCHAR" property="realName" />
 9     </resultMap>
10 
11     <sql id="Base_Column_List">
12         id, userName, passWord, realName
13     </sql>
14     <sql id="Base_Column_List_Value">
15         #{id,jdbcType=Long},
16         #{userName,jdbcType=VARCHAR},
17         #{passWord,jdbcType=VARCHAR},
18         #{realName,jdbcType=VARCHAR}
19     </sql>
20     <select id="listAll" resultMap="BaseResultMap">
21         select <include refid="Base_Column_List"/> from t_user
22     </select>
23 </mapper>

 

 

UserController.java

 1 package xyz.bit1024.sunny.controller;
 2 
 3 import org.springframework.beans.factory.annotation.Autowired;
 4 import org.springframework.web.bind.annotation.RequestMapping;
 5 import org.springframework.web.bind.annotation.RestController;
 6 import xyz.bit1024.sunny.domain.User;
 7 import xyz.bit1024.sunny.service.IUserService;
 8 
 9 import java.util.List;
10 
11 /**
12  * @ClassName UserController
13  * @Date 2019-06-15 16:16
14  * @Author xiaozhi
15  * @Version 1.0.0
16  * @Since JDK 1.8
17  * @Description
18  */
19 @RestController
20 @RequestMapping("/user")
21 public class UserController {
22 
23     //注入Service對象
24     @Autowired
25     private IUserService iUserService;
26 
27     @RequestMapping("/listAll")
28     public List<User> listAll(){
29         return iUserService.listAll();
30     }
31 }

 

  4 .完善配置

    ① 配置Mapper掃描包

       

 

     application-dev.yml

      

    logback.xml

      

<?xml version="1.0" encoding="UTF-8"?>
<configuration>
    <property name="LOG_HOME" value="./logs" />
    <property name="APP_NAME" value="bit1024" />
    <include resource="org/springframework/boot/logging/logback/defaults.xml" />
    <appender name="CONSOLE" class="ch.qos.logback.core.ConsoleAppender">
        <encoder>
            <pattern>%d{yyyy-MM-dd HH:mm:ss} [%thread] %-5level %logger{35} - %msg %n</pattern>
            <charset>UTF-8</charset>
        </encoder>
    </appender>
    <appender name="infoFile" class="ch.qos.logback.core.rolling.RollingFileAppender">
        <filter class="ch.qos.logback.classic.filter.LevelFilter">
            <level>INFO</level>
            <onMatch>ACCEPT</onMatch>
            <onMismatch>DENY</onMismatch>
        </filter>
        <rollingPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedRollingPolicy">
            <fileNamePattern>${LOG_HOME}/${APP_NAME}.info.%d{yyyy-MM-dd}.%i.log</fileNamePattern>
            <maxFileSize>10MB</maxFileSize>
            <maxHistory>30</maxHistory>
            <totalSizeCap>6GB</totalSizeCap>
        </rollingPolicy>
        <encoder class="ch.qos.logback.classic.encoder.PatternLayoutEncoder">
            <pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{50} - %msg%n</pattern>
            <charset>UTF-8</charset>
        </encoder>
    </appender>
    <appender name="warnFile" class="ch.qos.logback.core.rolling.RollingFileAppender">
        <filter class="ch.qos.logback.classic.filter.LevelFilter">
            <level>WARN</level>
            <onMatch>ACCEPT</onMatch>
            <onMismatch>DENY</onMismatch>
        </filter>
        <rollingPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedRollingPolicy">
            <fileNamePattern>${LOG_HOME}/${APP_NAME}.warn.%d{yyyy-MM-dd}.%i.log</fileNamePattern>
            <maxFileSize>10MB</maxFileSize>
            <maxHistory>30</maxHistory>
            <totalSizeCap>6GB</totalSizeCap>
        </rollingPolicy>
        <encoder class="ch.qos.logback.classic.encoder.PatternLayoutEncoder">
            <pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{50} - %msg%n</pattern>
            <charset>UTF-8</charset>
        </encoder>
    </appender>
    <appender name="errorFile" class="ch.qos.logback.core.rolling.RollingFileAppender">
        <filter class="ch.qos.logback.classic.filter.LevelFilter">
            <level>ERROR</level>
            <onMatch>ACCEPT</onMatch>
            <onMismatch>DENY</onMismatch>
        </filter>
        <rollingPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedRollingPolicy">
            <fileNamePattern>${LOG_HOME}/${APP_NAME}.error.%d{yyyy-MM-dd}.%i.log</fileNamePattern>
            <maxFileSize>10MB</maxFileSize>
            <maxHistory>30</maxHistory>
            <totalSizeCap>6GB</totalSizeCap>
        </rollingPolicy>
        <encoder class="ch.qos.logback.classic.encoder.PatternLayoutEncoder">
            <pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{50} - %msg%n</pattern>
            <charset>UTF-8</charset>
        </encoder>
    </appender>
    
    <!--myibatis日誌配置--> 
    <logger name="xyz.bit1024.sunny.mapper" level="INFO"/>
    <logger name="xyz.bit1024" level="DEBUG"/>

    <!-- 日誌輸出級別 -->
    <root level="INFO">
        <appender-ref ref="CONSOLE"></appender-ref>
        <appender-ref ref="infoFile"></appender-ref>
        <appender-ref ref="warnFile"></appender-ref>
        <appender-ref ref="errorFile"></appender-ref>
    </root>
</configuration>

 

  構造測試數據

INSERT INTO `springboot`.`t_user` (`id`, `userName`, `passWord`, `realName`) VALUES ('10000001', 'admin', 'admin', '超級管理員');
INSERT INTO `springboot`.`t_user` (`id`, `userName`, `passWord`, `realName`) VALUES ('10000002', 'user1', '123', '用戶1');
INSERT INTO `springboot`.`t_user` (`id`, `userName`, `passWord`, `realName`) VALUES ('10000003', 'user2', '123', '用戶2');

 

 

  一切完畢只待測試

   使用PostMan測試一波

    

 

  成功,,完美

  

 

 

採坑:

  java.sql.SQLException: The server time zone value '�й���׼ʱ��' is unrecognized or represents more than one time zone. You must configure either the server or JDBC driver (via the serverTimezone configuration property) to use a more specifc time zone value if you want to utilize time zone support.

 

修改配置文件:

url: jdbc:mysql://localhost:3306/springboot?useUnicode=true&characterEncoding=utf-8&useSSL=true&serverTimezone=UTC


此次的集成就算完了,,有空把登陸+shiro也集成

 以前也沒用過 GitHub :https://gist.github.com/bit1024-404/38f42bef407a7609e324eb00147ec5c1

相關文章
相關標籤/搜索