spring-boot+mybatis+restful api+jwt登陸(1)

1. pom.xml

包含了mybatis代碼生成插件,c3p0連接池

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.itcuc</groupId>
    <artifactId>qaserver</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>war</packaging>

    <name>qaserver</name>
    <description>Demo project for Spring Boot</description>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.0.2.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
        <java.version>1.8</java.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-redis</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-jdbc</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>1.3.2</version>
        </dependency>

        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <scope>runtime</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-tomcat</artifactId>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>

        <!-- 數(shù)據(jù)庫(kù)連接池 -->
        <dependency>
            <groupId>com.mchange</groupId>
            <artifactId>c3p0</artifactId>
            <version>0.9.5.2</version>
        </dependency>


        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>1.2.47</version>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-security</artifactId>
        </dependency>
        <dependency>
            <groupId>io.jsonwebtoken</groupId>
            <artifactId>jjwt</artifactId>
            <version>0.7.0</version>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
            <!-- mybatis generator 自動(dòng)生成代碼插件 -->
            <plugin>
                <groupId>org.mybatis.generator</groupId>
                <artifactId>mybatis-generator-maven-plugin</artifactId>
                <version>1.3.2</version>
                <configuration>
                    <configurationFile>${basedir}/src/main/resources/generatorConfig.xml</configurationFile>
                    <overwrite>true</overwrite>
                    <verbose>true</verbose>
                </configuration>
            </plugin>
        </plugins>
    </build>
</project>

2. 創(chuàng)建數(shù)據(jù)庫(kù)user表

CREATE TABLE `t_sys_user` (
  `id` char(36) NOT NULL,
  `username` varchar(255) DEFAULT NULL,
  `password` varchar(255) DEFAULT NULL,
  `email` varchar(255) DEFAULT NULL,
  `mobile` varchar(11) DEFAULT NULL,
  `login_ip` varchar(255) DEFAULT NULL,
  `login_time` timestamp NULL DEFAULT NULL ON UPDATE CURRENT_TIMESTAMP,
  `is_aviliable` tinyint(4) DEFAULT NULL,
  `type` int(2) DEFAULT NULL,
  `avatar` varchar(255) DEFAULT NULL,
  PRIMARY KEY (`id`),
  KEY `username` (`username`) USING HASH,
  KEY `email` (`email`),
  KEY `mobile` (`mobile`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

不需要的字段可以酌情刪除,實(shí)際上可以只保留username和password字段

3. 創(chuàng)建generatorConfig.xml 用于自動(dòng)生成mapper文件和模型

<?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>
    <!-- 數(shù)據(jù)庫(kù)驅(qū)動(dòng):選擇你的本地硬盤(pán)上面的數(shù)據(jù)庫(kù)驅(qū)動(dòng)包-->
    <classPathEntry  location="C:\Users\Emily\.m2\repository\mysql\mysql-connector-java\5.1.46\mysql-connector-java-5.1.46.jar"/>
    <context id="DB2Tables"  targetRuntime="MyBatis3">
        <commentGenerator>
            <property name="suppressDate" value="true"/>
            <!-- 是否去除自動(dòng)生成的注釋 true:是 : false:否 -->
            <property name="suppressAllComments" value="true"/>
        </commentGenerator>
        <!--數(shù)據(jù)庫(kù)鏈接URL,用戶名、密碼 -->
        <jdbcConnection driverClass="com.mysql.jdbc.Driver" connectionURL="jdbc:mysql://localhost:3306/qa" userId="root" password="root">
        </jdbcConnection>
        <javaTypeResolver>
            <property name="forceBigDecimals" value="false"/>
        </javaTypeResolver>
        <!-- 生成模型的包名和位置-->
        <javaModelGenerator targetPackage="com.itcuc.qaserver.model" targetProject="src/main/java">
            <property name="enableSubPackages" value="true"/>
            <property name="trimStrings" value="true"/>
        </javaModelGenerator>
        <!-- 生成映射文件的包名和位置-->
        <sqlMapGenerator targetPackage="mapping" targetProject="src/main/resources">
            <property name="enableSubPackages" value="true"/>
        </sqlMapGenerator>
        <!-- 生成DAO的包名和位置-->
        <javaClientGenerator type="XMLMAPPER" targetPackage="com.itcuc.qaserver.mapper" targetProject="src/main/java">
            <property name="enableSubPackages" value="true"/>
        </javaClientGenerator>
        <!-- 要生成的表 tableName是數(shù)據(jù)庫(kù)中的表名或視圖名 domainObjectName是實(shí)體類(lèi)名-->
        <table tableName="t_sys_user" domainObjectName="User" enableCountByExample="false" enableUpdateByExample="false" enableDeleteByExample="false" enableSelectByExample="false" selectByExampleQueryId="false"></table>
    </context>
</generatorConfiguration>

運(yùn)行一下插件就可以生成代碼了

4. 加入啟動(dòng)類(lèi)

package com.itcuc.qaserver;

import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;

@SpringBootApplication
@MapperScan("com.itcuc.qaserver.mapper")
public class QaserverApplication {

    public static void main(String[] args) {
        SpringApplication.run(QaserverApplication.class, args);
    }
}

5. 配置application.properties

server.port=8080

spring.datasource.name=qadata
spring.datasource.url=jdbc:mysql://localhost:3306/qa
spring.datasource.username=root
spring.datasource.password=root
spring.datasource.type=com.mchange.v2.c3p0.ComboPooledDataSource
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.maxActive=20
spring.datasource.maxWait=60000
spring.datasource.minIdle=1
spring.datasource.timeBetweenEvictionRunsMillis=60000
spring.datasource.minEvictableIdleTimeMillis=300000
spring.datasource.validationQuery=select 'x'
spring.datasource.testOnBorrow=false
spring.datasource.testOnReturn=false
spring.datasource.poolPreparedStatements=100
spring.datasource.maxOpenPreparedStatements=20

mybatis.type-aliases-package=com.itcuc.qaserver.model
mybatis.mapper-locations=classpath:mapping/*.xml

6. 創(chuàng)建DataSource和Sessionfactory

DataSourceConfiguration 類(lèi)配置c3p0數(shù)據(jù)源
SessionFactoryConfiguration 類(lèi)配置SqlSessionFactory

@SpringBootConfiguration
public class DataSourceConfiguration {
    @Value("${spring.datasource.driver-class-name}")
    private String jdbcDriver;
    @Value("${spring.datasource.url}")
    private String jdbcUrl;
    @Value("${spring.datasource.username}")
    private String jdbcUser;
    @Value("${spring.datasource.password}")
    private String jdbcPassword;
    @Value("${spring.datasource.maxActive}")
    private Integer maxPoolSize;
    @Value("${spring.datasource.maxWait}")
    private Integer maxIdleTime;
    @Value("${spring.datasource.minIdle}")
    private Integer minPoolSize;
    @Value("${spring.datasource.poolPreparedStatements}")
    private Integer maxStatements;
    @Value("${spring.datasource.timeBetweenEvictionRunsMillis}")
    private Integer idleConnectionTestPeriod;
    @Value("${spring.datasource.validationQuery}")
    private String preferredTestQuery;
    @Value("${spring.datasource.testOnBorrow}")
    private Boolean testConnectionOnCheckin;
    @Value("${spring.datasource.testOnReturn}")
    private Boolean testConnectionOnCheckout;
    @Bean
    public DataSource createDataSource() throws PropertyVetoException {
        ComboPooledDataSource dataSource = new ComboPooledDataSource();

        dataSource.setDriverClass(jdbcDriver);
        dataSource.setJdbcUrl(jdbcUrl);
        dataSource.setUser(jdbcUser);
        dataSource.setPassword(jdbcPassword);
        dataSource.setMaxPoolSize(maxPoolSize);
        dataSource.setMaxIdleTime(maxIdleTime);
        dataSource.setMinPoolSize(minPoolSize);
        dataSource.setMaxStatementsPerConnection(maxStatements);
        dataSource.setIdleConnectionTestPeriod(idleConnectionTestPeriod);
        dataSource.setPreferredTestQuery(preferredTestQuery);
        dataSource.setTestConnectionOnCheckin(testConnectionOnCheckin);
        dataSource.setTestConnectionOnCheckout(testConnectionOnCheckout);
        dataSource.setAutoCommitOnClose(false);

        return dataSource;
    }
}
@SpringBootConfiguration
public class SessionFactoryConfiguration {

    @Value("${mybatis.mapper-locations}")
    private String mapperXMLConfigPath;
    @Value("${mybatis.type-aliases-package}")
    private String mapperPackagePath;
    @Autowired
    private DataSource dataSource;

    @Bean
    public SqlSessionFactoryBean createSqlSessionFactory() throws IOException {
        SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
        PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
        String packageXMLConfigPath = mapperXMLConfigPath;

        // 設(shè)置mapper 對(duì)應(yīng)的XML 文件的路徑
        sqlSessionFactoryBean.setMapperLocations(resolver.getResources(packageXMLConfigPath));
        // 設(shè)置數(shù)據(jù)源
        sqlSessionFactoryBean.setDataSource(dataSource);
        // 設(shè)置mapper 接口所在的包
        sqlSessionFactoryBean.setTypeAliasesPackage(mapperPackagePath);

        return sqlSessionFactoryBean;
    }
}

7. 創(chuàng)建一個(gè)簡(jiǎn)單的api

@RestController
@RequestMapping("/api/index")
public class IndexController {
    @GetMapping("hello")
    public String hello() {
        return "hello";
    }
}

使用crap測(cè)試接口


image.png

參考感謝:

  1. https://blog.csdn.net/sxdtzhaoxinguo/article/details/77965226
  2. https://blog.csdn.net/codejas/article/details/79334545
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容