SpringBoot 는 Mybatis 를 통합 하여 TypeAliases 설정 에 실패 한 문 제 를 해결 합 니 다.
16847 단어 SpringBootMybatisTypeAliases
MyBatis 를 사용 할 때 대상 관 계 를 매 핑 하여 대상 과 Aliase 를 매 핑 합 니 다.
Mybatis 문서 에 명확 하 게 쓰 여 있 습 니 다.실체 클래스 의 Aliase 를 명확 하 게 정의 하지 않 으 면 프레임 워 크 는 자동 으로 Class Name 을 별명 으로 합 니 다.
질문 이 왔 습 니 다.자바-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
이상 정 보 를 보면 알 리 스 에 대응 하 는 클래스 를 로 컬 에서 검색 할 수 없 으 며,결국 sqlSession Factory 등 초기 화 에 실 패 했 습 니 다.그리고 레일 을 올 리 는 것 은 Idea 에서 직접 시작 하 는 것 은 문제 가 없 으 며,jar 가방 을 시작 해 야 이 문제 가 발생 할 수 있 습 니 다.
해결 방법
블 로 거 A 참조Beaver 의 글,원래 my batis 의 facroty 는 SpringBoot 의 독특한 가상 파일 시스템 을 불 러 와 야 클래스 경 로 를 식별 할 수 있 습 니 다.
public SpringBootVFS() {
this.resourceResolver = new PathMatchingResourcePatternResolver(getClass().getClassLoader());
}
상기 코드 를 보면 PathMatchingResourcePatternResolver 를 통 해 자원 의 로드 를 실현 합 니 다.이 문 제 를 복구 하려 면 my batis 설정 류 에 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");
...
}
SpringBoot 통합 Mybatis 및 만난 구덩이1.프로젝트 환경 구축
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.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>
<!-- : 、 、 、 -->
<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=".\src\main\java">
<!--enableSubPackages: schema -->
<property name="enableSubPackages" value="false" />
<!-- -->
<property name="trimStrings" value="true" />
</javaModelGenerator>
<!-- mapper.xml -->
<sqlMapGenerator targetPackage="com.example.springbootmybatis.mapper"
targetProject=".\src\main\java">
<!--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 발전기 플러그 인 생 성 코드 실행
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 페이지 만 들 기
<!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 </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 컨트롤 러 생 성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 서비스 인터페이스 구현 클래스 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);
}
잘못1.Mybatis Generator 가 자동 으로 생 성 되 고 데이터베이스 의 같은 이름 표 도 생산 되 는 문제
[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
홈 페이지 에 서 는 이 문제 에 대한 해답 이 나 왔 다.
Mysql 은 SQL catalogs 와 schema 를 정상적으로 지원 할 수 없습니다.따라서 generator 설정 파일 에 catalog 와 schema 를 지정 하지 않 고 데이터 시트 의 이름 을 지정 하고 JDBC URL 에 데이터 베 이 스 를 지정 하면 됩 니 다.mysql-connector-java 8.x 버 전 을 사용 하면 generator 는 MySql 의 정보 데이터베이스(sys,informationschema, 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>
이상 은 개인 적 인 경험 이 므 로 여러분 에 게 참고 가 되 기 를 바 랍 니 다.여러분 들 도 저 희 를 많이 응원 해 주시 기 바 랍 니 다.
이 내용에 흥미가 있습니까?
현재 기사가 여러분의 문제를 해결하지 못하는 경우 AI 엔진은 머신러닝 분석(스마트 모델이 방금 만들어져 부정확한 경우가 있을 수 있음)을 통해 가장 유사한 기사를 추천합니다:
【Java・SpringBoot・Thymeleaf】 에러 메세지를 구현(SpringBoot 어플리케이션 실천편 3)로그인하여 사용자 목록을 표시하는 응용 프로그램을 만들고, Spring에서의 개발에 대해 공부하겠습니다 🌟 마지막 데이터 바인딩에 계속 바인딩 실패 시 오류 메시지를 구현합니다. 마지막 기사🌟 src/main/res...
텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
CC BY-SA 2.5, CC BY-SA 3.0 및 CC BY-SA 4.0에 따라 라이센스가 부여됩니다.