在應用MyBatis時,使用物件關係映射,將物件和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對應的類,並最終導致sqlSessionFactory等初始化失敗。而且吊軌的是,直接在Idea中啟動是沒有問題的,啟動jar包才會出現這個問題
參考博主A_Beaver的文章,原來mybatis的facroty需要載入SpringBoot獨特的虛擬檔案系統,才能辨識類別路徑
public SpringBootVFS() { this.resourceResolver = new PathMatchingResourcePatternResolver(getClass().getClassLoader()); }
從以上程式碼看,其實是透過PathMatchingResourcePatternResolver實作資源的載入
修復該問題只需要在mybatis的設定類別中,設定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);//设置SpringBootVFS bean.setTypeAliasesPackage("com.fulan.domain.red"); ... }
1.1 建立專案
1.2 修改POM文件,加入相關依賴
修改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> <!--数据库驱动坐标--> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>8.0.12</version> </dependency> <!--Druid数据源依赖--> <dependency> <groupId>com.alibaba</groupId> <artifactId>druid</artifactId> <version>1.1.10</version> </dependency>
1.3 設定資料來源
在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.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> <!-- 数据库连接信息:驱动类、连接地址、用户名、密码--> <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> <!-- 默认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=".srcmainjava"> <!--enableSubPackages:是否让schema作为包的后缀--> <property name="enableSubPackages" value="false" /> <!-- 从数据库返回的值被清理前后的空格 --> <property name="trimStrings" value="true" /> </javaModelGenerator> <!--对应的mapper.xml文件 --> <sqlMapGenerator targetPackage="com.example.springbootmybatis.mapper" targetProject=".srcmainjava"> <!--enableSubPackages:是否让schema作为包的后缀--> <property name="enableSubPackages" value="false" /> </sqlMapGenerator> <!-- 对应的Mapper接口类文件 --> <javaClientGenerator type="XMLMAPPER" targetPackage="com.example.springbootmybatis.mapper" targetProject="./src/main/java"> <!--enableSubPackages:是否让schema作为包的后缀--> <property name="enableSubPackages" value="false" /> </javaClientGenerator> <!-- 指定数据库表 --> <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 執行generator外掛程式產生程式碼
##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
<!DOCTYPE html>
<html 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数据库</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.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; /** * 页面跳转Controller */ @Controller public class PageController { /** * 页面跳转方法 */ @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 建立Service 介面實作類別Impl
/**
* 用户管理业务层
*/
@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); }
遇到的錯誤
[WARNING] Cannot obtain primary key information from the database, generated objects may be incomplete在MyBatis Generator官網中對此問題做出了解答。
翻譯如下:Mysql 無法正常支援 SQL catalogs 和 schema。因此,最好不要在 generator 設定檔中指定 catalog 以及schema,只需指定資料表的名字並在 JDBC URL 中指定資料庫即可。如果使用mysql-connector-java 8.x 版本,generator 會為MySql中資訊資料庫(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&characterEnconding=utf-8&useSSL=false&serverTimezone=UTC" userId="username" password="password"> <property name="nullCatalogMeansCurrent" value="true"/> </jdbcConnection>
2. 頁面出現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配置文件。要加载所有的静态资源。
<!--原本的--> <!--资源文件的路径--> <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>
以上是SpringBoot怎麼解決TypeAliases配置失敗問題的詳細內容。更多資訊請關注PHP中文網其他相關文章!