最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

SpringBoot整合Mybatis及遇到的坑與解決過程

 更新時(shí)間:2026年01月15日 15:22:55   作者:沉淅塵  
該文章詳細(xì)介紹了如何配置和使用MyBatis Generator插件生成代碼,包括創(chuàng)建項(xiàng)目、修改POM文件、配置數(shù)據(jù)源、添加Maven插件、配置資源拷貝插件、添加用戶功能以及解決遇到的錯(cuò)誤

1. 搭建項(xiàng)目環(huán)境

1.1 創(chuàng)建項(xiàng)目

1.2 修改POM文件,添加相關(guān)依賴

修改pom.xml文件,在其中添加下面依賴。

<!--Thymeleaf啟動(dòng)器-->
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-thymeleaf</artifactId>
		</dependency>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-web</artifactId>
		</dependency>
		<!--mybatis啟動(dòng)器-->
		<dependency>
			<groupId>org.mybatis.spring.boot</groupId>
			<artifactId>mybatis-spring-boot-starter</artifactId>
			<version>2.1.3</version>
		</dependency>
		<!--jdbc啟動(dòng)器-->
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-jdbc</artifactId>
		</dependency>
		<!--數(shù)據(jù)庫驅(qū)動(dòng)坐標(biāo)-->
		<dependency>
			<groupId>mysql</groupId>
			<artifactId>mysql-connector-java</artifactId>
			<version>8.0.12</version>
		</dependency>
		<!--Druid數(shù)據(jù)源依賴-->
		<dependency>
			<groupId>com.alibaba</groupId>
			<artifactId>druid</artifactId>
			<version>1.1.10</version>
		</dependency>

1.3 配置數(shù)據(jù)源

在application.yml文件中配置如下代碼。

spring:
  datasource:
    driver-class-name: com.mysql.cj.jdbc.Driver
    url: jdbc:mysql://localhost:3306/test?useUnicode=true&characterEnconding=utf-8&useSSL=false&serverTimezone=GMT%2B8
    username: root
    password: root
    type: com.alibaba.druid.pool.DruidDataSource

2. 配置Maven的generator插件

2.1 添加generator插件坐標(biāo)

<!--配置generator插件-->
			<plugin>
				<groupId>org.mybatis.generator</groupId>
				<artifactId>mybatis-generator-maven-plugin</artifactId>
				<version>1.4.0</version>
				<dependencies>
					<dependency>
						<groupId>mysql</groupId>
						<artifactId>mysql-connector-java</artifactId>
						<version>8.0.12</version>
					</dependency>
				</dependencies>

				<!--指定配置文件的路徑-->
				<configuration>
					<configurationFile>${project.basedir}/src/main/resources/generator.xml</configurationFile>
					<verbose>true</verbose>
					<overwrite>true</overwrite>
				</configuration>
			</plugin>

2.2 添加generator配置文件

將文件命名為generator.xml,在src/main/resources中添加。

<?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>
        <context id="testTables" targetRuntime="MyBatis3">
            <commentGenerator>
                <!-- 是否去除自動(dòng)生成的注釋 true:是 : false:否 -->
                <property name="suppressAllComments" value="true" />  
            </commentGenerator>
            <!-- 數(shù)據(jù)庫連接信息:驅(qū)動(dòng)類、連接地址、用戶名、密碼-->
            <jdbcConnection driverClass="com.mysql.cj.jdbc.Driver"
                connectionURL="jdbc:mysql://localhost:3306/test?useUnicode=true&characterEnconding=utf-8&useSSL=false&serverTimezone=UTC"
                            userId="root" password="root">
            </jdbcConnection>
            <!-- 默認(rèn)false,把JDBC DECIMAL 和 NUMERIC 類型解析為 Integer true,把JDBC DECIMAL   
                和 NUMERIC 類型解析為java.math.BigDecimal -->  
            <javaTypeResolver>  
                <property name="forceBigDecimals" value="false" />  
            </javaTypeResolver>

            <!--targetProject:生成PO類的位置-->
            <javaModelGenerator targetPackage="com.example.springbootmybatis.pojo"
                targetProject=".\src\main\java">
                <!--enableSubPackages:是否讓schema作為包的后綴-->
                <property name="enableSubPackages" value="false" />
                <!-- 從數(shù)據(jù)庫返回的值被清理前后的空格 -->  
                <property name="trimStrings" value="true" />  
            </javaModelGenerator>
            <!--對(duì)應(yīng)的mapper.xml文件 -->  
            <sqlMapGenerator targetPackage="com.example.springbootmybatis.mapper"
                targetProject=".\src\main\java">
                <!--enableSubPackages:是否讓schema作為包的后綴-->
                <property name="enableSubPackages" value="false" />
            </sqlMapGenerator>
            <!-- 對(duì)應(yīng)的Mapper接口類文件 -->  
            <javaClientGenerator type="XMLMAPPER"
                                 targetPackage="com.example.springbootmybatis.mapper" targetProject="./src/main/java">
                <!--enableSubPackages:是否讓schema作為包的后綴-->
                <property name="enableSubPackages" value="false" />
            </javaClientGenerator>
            <!-- 指定數(shù)據(jù)庫表 -->
            <table schema="" tableName="users"></table>
            <!-- 列出要生成代碼的所有表,這里配置的是不生成Example文件 -->  
<!--            <table tableName="userinfo" domainObjectName="UserInfoPO"  -->
<!--                enableCountByExample="false" enableUpdateByExample="false"  -->
<!--                enableDeleteByExample="false" enableSelectByExample="false"  -->
<!--                selectByExampleQueryId="false">  -->
<!--                <property name="useActualColumnNames" value="false" />  -->
<!--            </table>  -->
        </context>  
    </generatorConfiguration> 

2.3 添加generator配置文件的DTD文件

可以在工具欄中的File->Settings中添加,也可以直接在文件中按alt+shift自動(dòng)添加。

2.4 運(yùn)行g(shù)enerator插件生成代碼

3. 配置資源拷貝插件

3.1 添加資源拷貝插件坐標(biāo)

<!--配置資源拷貝插件-->
		<resources>
			<resource>
				<directory>src/main/java</directory>
				<includes>
					<include>**/*.xml</include>
				</includes>
			</resource>

			<resource>
				<directory>src/main/resources</directory>
				<includes>
					<include>**/*.yml</include>
				</includes>
			</resource>
		</resources>

3.2 修改啟動(dòng)類添加@MapperScan注解

package com.example.springbootmybatis;

import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
@MapperScan("com.example.springbootmybatis.mapper")//指定掃描接口與映射配置文件的包名
public class DemoApplication {

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

}

4. 其他配置項(xiàng)

mybatis:
  # 掃描classpath中mapper目錄下的映射配置文件,針對(duì)于映射文件放到了resources目錄下
  mapper-locations: classpath:/mapper/*.xml
  # 定義包別名,使用pojo時(shí)可以直接使用pojo的類型名稱不用加包名
  type-aliases-package: com.example.springbootmybatis.pojo

5. 添加用戶功能

5.1 創(chuàng)建頁面

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<link rel="shortcut icon" href="../resources/favicon.ico" rel="external nofollow"  th:href="@{/static/favion.ico}" rel="external nofollow" >
<head>
    <meta charset="UTF-8">
    <title>測(cè)試SpringBoot連接PostgreSQL數(shù)據(jù)庫</title>
</head>
<body>

    <form th:action="@{/user/addUser}" method="post">
        <input type="text" name="userid">

        <input type="text" name="username">

        <input type="text" name="usersex">

        <input type="submit" value="添加">

    </form>
</body>
</html>

5.2 創(chuàng)建Controller

5.2.1 PageController

package com.example.springbootmybatis.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;

/**
 * 頁面跳轉(zhuǎn)Controller
 */
@Controller
public class PageController {

    /**
     * 頁面跳轉(zhuǎn)方法
     */
    @RequestMapping("/{page}")
    public String showPage(@PathVariable String page){
        return page;
    }
}

5.2.2 UsersController

package com.example.springbootmybatis.controller;

import com.example.springbootmybatis.pojo.Users;
import com.example.springbootmybatis.service.UsersService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * 用戶管理Controller
 */
@RestController
@RequestMapping("/user")
public class UsersController {

    @Autowired
    private UsersService usersService;
    /**
     * 添加用戶
     */
    @PostMapping("/addUser")
    public String addUsers(Users users){
        try {
            this.usersService.addUsers(users);
        } catch (Exception e){
            e.printStackTrace();
            return "error";
        }
        return "redirect:/ok";
    }
}

5.3 創(chuàng)建Service

接口實(shí)現(xiàn)類Impl

/**
 * 用戶管理業(yè)務(wù)層
 */
@Service
public class UsersServiceImpl implements UsersService {
    @Autowired
    private UsersMapper usersMapper;

    @Override
    @Transactional
    public void addUsers(Users users) {
        this.usersMapper.insert(users);
    }
}

接口

public interface UsersService {
    void addUsers(Users users);
}

遇到的錯(cuò)誤

1. Mybatis Generator自動(dòng)生成,數(shù)據(jù)庫的同名表也會(huì)生產(chǎn)的問題

[WARNING] Table Configuration users matched more than one table (test..users,performance_schema..users)
[WARNING] Cannot obtain primary key information from the database, generated objects may be incomplete

MyBatis Generator官網(wǎng) 中對(duì)這一問題做出了解答。

翻譯如下:Mysql 無法正常支持 SQL catalogs 和 schema。因此,最好不要在 generator 配置文件中指定 catalog 以及schema,僅需指定數(shù)據(jù)表的名字并在 JDBC URL 中指定數(shù)據(jù)庫即可。

如果使用 mysql-connector-java 8.x 版本,generator 會(huì)為MySql中信息數(shù)據(jù)庫(sys, information_schema, performance_schema)的表生成代碼,若要避免這種操作,請(qǐng)?jiān)?JDBC URL 中加入屬性“nullCatalogMeansCurrent=true”。

修改配置文件generator.xml

<jdbcConnection driverClass="com.mysql.cj.jdbc.Driver"
                        connectionURL="jdbc:mysql://localhost:3306/test?useUnicode=true&characterEnconding=utf-8&useSSL=false&serverTimezone=UTC"
                        userId="username" password="password">
            <property name="nullCatalogMeansCurrent" value="true"/>
        </jdbcConnection>

2. 頁面出現(xiàn)500錯(cuò)誤

2020-06-27 14:23:42.459 ERROR 19676 --- [nio-8080-exec-1] o.a.c.c.C.[.[.[/].[dispatcherServlet]    : Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Circular view path [addUsers]: would dispatch back to the current handler URL [/addUsers] again. Check your ViewResolver setup! (Hint: This may be the result of an unspecified view, due to default view name generation.)] with root cause

javax.servlet.ServletException: Circular view path [addUsers]: would dispatch back to the current handler URL [/addUsers] again. Check your ViewResolver setup! (Hint: This may be the result of an unspecified view, due to default view name generation.)
	at org.springframework.web.servlet.view.InternalResourceView.prepareForRendering(InternalResourceView.java:210) ~[spring-webmvc-5.2.7.RELEASE.jar:5.2.7.RELEASE]
	at 

解決方法

查了很多博客,但是都不是自己的問題,自己的問題是在pom.xml配置文件中的資源路徑中,沒有寫所有,而是單獨(dú)的xml和yml配置文件。要加載所有的靜態(tài)資源。

<!--原本的-->
<!--資源文件的路徑-->
			<resource>
				<directory>src/main/resources</directory>
				<includes>
					<include>**/*.yml</include>
                    <include>**/*.xml</include>
				</includes>
				<!-- <filtering>false</filtering>-->
			</resource>
<!--修改后的-->
<!--資源文件的路徑-->
			<resource>
				<directory>src/main/resources</directory>
				<includes>
					<include>**/*.*</include>
				</includes>
				<!-- <filtering>false</filtering>-->
			</resource>

總結(jié)

以上為個(gè)人經(jīng)驗(yàn),希望能給大家一個(gè)參考,也希望大家多多支持腳本之家。

相關(guān)文章

  • MyBatis-Plus使用動(dòng)態(tài)表名分表查詢的實(shí)現(xiàn)

    MyBatis-Plus使用動(dòng)態(tài)表名分表查詢的實(shí)現(xiàn)

    本文主要介紹了MyBatis-Plus使用動(dòng)態(tài)表名分表查詢,主要是動(dòng)態(tài)修改表名的幾種常見場(chǎng)景,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
    2025-11-11
  • Java方法的返回值及注意事項(xiàng)小結(jié)

    Java方法的返回值及注意事項(xiàng)小結(jié)

    這篇文章主要介紹了Java方法的返回值及注意事項(xiàng),本文給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下
    2023-04-04
  • MybatisPlus實(shí)現(xiàn)對(duì)象嵌套關(guān)聯(lián)查詢一對(duì)多List集合查詢

    MybatisPlus實(shí)現(xiàn)對(duì)象嵌套關(guān)聯(lián)查詢一對(duì)多List集合查詢

    這篇文章主要介紹了MybatisPlus實(shí)現(xiàn)對(duì)象嵌套關(guān)聯(lián)查詢一對(duì)多List集合查詢,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教
    2022-05-05
  • SpringBoot工程搭建打包、啟動(dòng)jar包和war包的教程圖文詳解

    SpringBoot工程搭建打包、啟動(dòng)jar包和war包的教程圖文詳解

    這篇文章主要介紹了SpringBoot工程搭建打包、啟動(dòng)jar包和war包的教程,本文通過圖文并茂的形式給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下
    2020-09-09
  • 使用jenkins部署springboot項(xiàng)目的方法步驟

    使用jenkins部署springboot項(xiàng)目的方法步驟

    這篇文章主要介紹了使用jenkins部署springboot項(xiàng)目的方法步驟,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
    2021-04-04
  • Java中的interrupt、interrupted和isInterrupted方法區(qū)別詳解

    Java中的interrupt、interrupted和isInterrupted方法區(qū)別詳解

    這篇文章主要介紹了Java中的interrupt、interrupted和isInterrupted方法區(qū)別詳解,interrupt用于中斷線程,調(diào)用該方法的線程的狀態(tài)將會(huì)被設(shè)置為中斷狀態(tài),線程中斷僅僅是設(shè)置線程的中斷狀態(tài)位,并不會(huì)停止線程,需要用戶自己去監(jiān)視線程的狀態(tài)并作出處理,需要的朋友可以參考下
    2023-12-12
  • PowerJob的OhMyClassLoader工作流程源碼解讀

    PowerJob的OhMyClassLoader工作流程源碼解讀

    這篇文章主要介紹了PowerJob的OhMyClassLoader工作流程源碼解讀,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪
    2024-01-01
  • Springboot使用slf4j記錄日志的方法步驟

    Springboot使用slf4j記錄日志的方法步驟

    本文主要介紹了Springboot使用slf4j記錄日志的方法步驟,文中通過示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下
    2022-01-01
  • maven私有鏡像倉庫nexus部署使用

    maven私有鏡像倉庫nexus部署使用

    Nexus在企業(yè)開發(fā)中還是比較常用的私有倉庫管理工具,本文主要介紹了maven私有鏡像倉庫nexus部署使用,具有一定的參考價(jià)值,感興趣的可以了解一下
    2024-07-07
  • Spring Boot項(xiàng)目利用Redis實(shí)現(xiàn)集中式緩存實(shí)例

    Spring Boot項(xiàng)目利用Redis實(shí)現(xiàn)集中式緩存實(shí)例

    本篇文章主要介紹了Spring Boot項(xiàng)目利用Redis實(shí)現(xiàn)集中式緩存實(shí)例,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下
    2017-06-06

最新評(píng)論

大新县| 平遥县| 克拉玛依市| 横峰县| 陇西县| 靖边县| 鄯善县| 阿图什市| 佛山市| 沁水县| 宝坻区| 德昌县| 柳林县| 兴和县| 县级市| 平度市| 芦山县| 常宁市| 平度市| 桂平市| 远安县| 铜鼓县| 两当县| 呼图壁县| 深泽县| 当阳市| 礼泉县| 德惠市| 布尔津县| 都昌县| 明水县| 太仆寺旗| 郸城县| 从化市| 保德县| 海门市| 诸暨市| 惠来县| 孟津县| 南澳县| 玉环县|