欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

SpringBoot整合Mybatis,解決TypeAliases配置失敗的問題

 更新時間:2021年07月13日 11:38:44   作者:小小怪醫(yī)芙蘭  
這篇文章主要介紹了SpringBoot整合Mybatis,解決TypeAliases配置失敗的問題,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教

問題描述

在應(yīng)用MyBatis時,使用對象關(guān)系映射,將對象和Aliase映射起來。

在Mybatis的文檔明確寫出,如果你沒有明確定義實體類的Aliase,框架會自動將Class Name自動作為別名。

那么問題來了,當使用java -jar xxx.jar&啟動的時候,會報出以下錯誤,

Error resolving class. Cause: org.apache.ibatis.type.TypeException: Could not resolve type alias 'XXXXX'.Cause: java.lang.ClassNotFoundException: Cannot find class: XXXXX

從異常信息來看,明顯就是無法從本地檢索到alise對應(yīng)的類,并最終導(dǎo)致sqlSessionFactory等初始化失敗。而且吊軌的是,直接在Idea中啟動是沒有問題的,啟動jar包才會出現(xiàn)這個問題

解決方法

參考博主A_Beaver的文章,原來mybatis的facroty需要加載SpringBoot獨特的虛擬文件系統(tǒng),才能識別類路徑

public SpringBootVFS() {
    this.resourceResolver = new PathMatchingResourcePatternResolver(getClass().getClassLoader());
}

從以上代碼看,其實是通過PathMatchingResourcePatternResolver實現(xiàn)資源的加載

修復(fù)該問題只需要在mybatis的配置類中,設(shè)置一下factory即可,

    @Bean(name = "masterSqlSessionFactory")
    @Primary
    public SqlSessionFactory sqlSessionFactory(@Qualifier("masterDataSource") DataSource dataSource) throws Exception {
        SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
        bean.setDataSource(dataSource);
        bean.setVfs(SpringBootVFS.class);//設(shè)置SpringBootVFS
        bean.setTypeAliasesPackage("com.fulan.domain.red");
        ...
    }

SpringBoot整合Mybatis及遇到的坑

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

1.1 創(chuàng)建項目

在這里插入圖片描述

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

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

<!--Thymeleaf啟動器-->
		<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啟動器-->
		<dependency>
			<groupId>org.mybatis.spring.boot</groupId>
			<artifactId>mybatis-spring-boot-starter</artifactId>
			<version>2.1.3</version>
		</dependency>
		<!--jdbc啟動器-->
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-jdbc</artifactId>
		</dependency>
		<!--數(shù)據(jù)庫驅(qū)動坐標-->
		<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插件坐標

<!--配置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>
                <!-- 是否去除自動生成的注釋 true:是 : false:否 -->
                <property name="suppressAllComments" value="true" />  
            </commentGenerator>
            <!-- 數(shù)據(jù)庫連接信息:驅(qū)動類、連接地址、用戶名、密碼-->
            <jdbcConnection driverClass="com.mysql.cj.jdbc.Driver"
                connectionURL="jdbc:mysql://localhost:3306/test?useUnicode=true&amp;characterEnconding=utf-8&amp;useSSL=false&amp;serverTimezone=UTC"
                            userId="root" password="root">
            </jdbcConnection>
            <!-- 默認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>
            <!--對應(yīng)的mapper.xml文件 -->  
            <sqlMapGenerator targetPackage="com.example.springbootmybatis.mapper"
                targetProject=".\src\main\java">
                <!--enableSubPackages:是否讓schema作為包的后綴-->
                <property name="enableSubPackages" value="false" />
            </sqlMapGenerator>
            <!-- 對應(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自動添加。


在這里插入圖片描述

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

在這里插入圖片描述

3. 配置資源拷貝插件

3.1 添加資源拷貝插件坐標

<!--配置資源拷貝插件-->
		<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 修改啟動類添加@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. 其他配置項

mybatis:
  # 掃描classpath中mapper目錄下的映射配置文件,針對于映射文件放到了resources目錄下
  mapper-locations: classpath:/mapper/*.xml
  # 定義包別名,使用pojo時可以直接使用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" th:href="@{/static/favion.ico}">
<head>
    <meta charset="UTF-8">
    <title>測試SpringBoot連接PostgreSQL數(shù)據(jù)庫</title>
</head>
<body>
    <form th:action="@{/user/addUser}" method="post">
        <input type="text" name="userid"><br>
        <input type="text" name="username"><br>
        <input type="text" name="usersex"><br>
        <input type="submit" value="添加"><br>
    </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 接口實現(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);
}

遇到的錯誤

1. Mybatis Generator自動生成,數(shù)據(jù)庫的同名表也會生產(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) 中對這一問題做出了解答。

翻譯如下:Mysql 無法正常支持 SQL catalogs 和 schema。因此,最好不要在 generator 配置文件中指定 catalog 以及schema,僅需指定數(shù)據(jù)表的名字并在 JDBC URL 中指定數(shù)據(jù)庫即可。如果使用 mysql-connector-java 8.x 版本,generator 會為MySql中信息數(shù)據(jù)庫(sys, information_schema, performance_schema)的表生成代碼,若要避免這種操作,請在 JDBC URL 中加入屬性“nullCatalogMeansCurrent=true”。

修改配置文件generator.xml

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

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

在這里插入圖片描述

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配置文件中的資源路徑中,沒有寫所有,而是單獨的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>

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

相關(guān)文章

  • 使用Java實現(xiàn)系統(tǒng)托盤功能的介紹(附源碼以及截圖)

    使用Java實現(xiàn)系統(tǒng)托盤功能的介紹(附源碼以及截圖)

    本篇文章介紹了,在Java中實現(xiàn)系統(tǒng)托盤功能的詳解,文中附源碼以及截圖介紹。需要的朋友參考下
    2013-05-05
  • SpringBoot中事務(wù)失效的六個原因解析

    SpringBoot中事務(wù)失效的六個原因解析

    這篇文章主要介紹了SpringBoot中事務(wù)失效的六個原因解析,由于Spring的事務(wù)是基于AOP的方式結(jié)合動態(tài)代理來實現(xiàn)的,因此事務(wù)方法一定要是public的,這樣才能便于被Spring做事務(wù)的代理和增強,需要的朋友可以參考下
    2023-10-10
  • IDEA中Maven報錯Cannot resolve xxx的解決方法匯總(親測有效)

    IDEA中Maven報錯Cannot resolve xxx的解決方法匯總(親測有效)

    在IDEA中的pom文件中添加了依賴,并且正確加載了相應(yīng)依賴,pom文件沒有報紅,看起來像是把所有依賴庫全部加載進來了,但是代碼中使用依賴的類庫使報紅,本文給大家介紹了IDEA中Maven報錯Cannot resolve xxx的解決方法匯總,需要的朋友可以參考下
    2024-06-06
  • Spring簡明分析Bean作用域

    Spring簡明分析Bean作用域

    scope用來聲明容器中的對象所應(yīng)該處的限定場景或者說該對象的存活時間,即容器在對象進入其 相應(yīng)的scope之前,生成并裝配這些對象,在該對象不再處于這些scope的限定之后,容器通常會銷毀這些對象,這篇文章主要介紹了Spring中的Bean作用域,需要的朋友可以參考下
    2022-07-07
  • springboot 中文件上傳下載實例代碼

    springboot 中文件上傳下載實例代碼

    Spring Boot是由Pivotal團隊提供的全新框架,其設(shè)計目的是用來簡化新Spring應(yīng)用的初始搭建以及開發(fā)過程。這篇文章主要介紹了springboot 中文件上傳下載實例代碼,需要的朋友可以參考下
    2017-11-11
  • java支付寶即時到帳提交訂單功能

    java支付寶即時到帳提交訂單功能

    這篇文章主要為大家詳細介紹了java支付寶即時到帳提交訂單功能,具有一定的參考價值,感興趣的小伙伴們可以參考一下
    2017-08-08
  • Java與MySQL導(dǎo)致的時間不一致問題分析

    Java與MySQL導(dǎo)致的時間不一致問題分析

    在使用MySQL的過程中,你可能會遇到時區(qū)相關(guān)問題,本文主要介紹了Java與MySQL導(dǎo)致的時間不一致問題分析,具有一定的參考價值,感興趣的可以了解一下
    2024-07-07
  • 使用@Autowired注解有錯誤提示的解決

    使用@Autowired注解有錯誤提示的解決

    這篇文章主要介紹了使用@Autowired注解有錯誤提示的解決,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教
    2021-11-11
  • java教程之java程序編譯運行圖解(java程序運行)

    java教程之java程序編譯運行圖解(java程序運行)

    最近重新復(fù)習了一下java基礎(chǔ),在使用javap的過程中遇到了一些問題,這里便講講對于一個類文件如何編譯、運行、反編譯的。也讓自己加深一下印象
    2014-03-03
  • springboot-assembly自定義打包全過程

    springboot-assembly自定義打包全過程

    這篇文章主要介紹了springboot-assembly自定義打包全過程,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教
    2023-06-06

最新評論