使用mybatis-generator代码生成器时出现sql语句异常(这里的主要问题为数据库和表之间用了两个.)

org.springframework.jdbc.BadSqlGrammarException:

Error querying database. Cause: java.sql.SQLSyntaxErrorException: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ‘.department’ at line 1

The error may exist in com/practice/springbootpracticemybatis/dao/DepartmentMapper.java (best guess)

The error may involve defaultParameterMap

The error occurred while setting parameters

SQL: SELECT did,dname,dpassword FROM interview…department

Cause: java.sql.SQLSyntaxErrorException: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ‘.department’ at line 1

; bad SQL grammar []; nested exception is java.sql.SQLSyntaxErrorException: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ‘.department’ at line 1

at org.springframework.jdbc.support.SQLErrorCodeSQLExceptionTranslator.doTranslate(SQLErrorCodeSQLExceptionTranslator.java:234)
at org.springframework.jdbc.support.AbstractFallbackSQLExceptionTranslator.translate(AbstractFallbackSQLExceptionTranslator.java:72)
at org.mybatis.spring.MyBatisExceptionTranslator.translateExceptionIfPossible(MyBatisExceptionTranslator.java:73)
at org.mybatis.spring.SqlSessionTemplate$SqlSessionInterceptor.invoke(SqlSessionTemplate.java:446)
at com.sun.proxy.$Proxy64.selectList(Unknown Source)
at org.mybatis.spring.SqlSessionTemplate.selectList(SqlSessionTemplate.java:230)
at org.apache.ibatis.binding.MapperMethod.executeForMany(MapperMethod.java:139)
at org.apache.ibatis.binding.MapperMethod.execute(MapperMethod.java:76)
at org.apache.ibatis.binding.MapperProxy.invoke(MapperProxy.java:59)
at com.sun.proxy.$Proxy83.selectAll(Unknown Source)
at com.practice.springbootpracticemybatis.SpringBootPracticeMybatisApplicationTests.testInsert(SpringBootPracticeMybatisApplicationTests.java:33)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.base/java.lang.reflect.Method.invoke(Method.java:564)
at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)
at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
at org.springframework.test.context.junit4.statements.RunBeforeTestExecutionCallbacks.evaluate(RunBeforeTestExecutionCallbacks.java:74)
at org.springframework.test.context.junit4.statements.RunAfterTestExecutionCallbacks.evaluate(RunAfterTestExecutionCallbacks.java:84)
at org.springframework.test.context.junit4.statements.RunBeforeTestMethodCallbacks.evaluate(RunBeforeTestMethodCallbacks.java:75)
at org.springframework.test.context.junit4.statements.RunAfterTestMethodCallbacks.evaluate(RunAfterTestMethodCallbacks.java:86)
at org.springframework.test.context.junit4.statements.SpringRepeat.evaluate(SpringRepeat.java:84)
at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:251)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:97)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
at org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61)
at org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:70)
at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:190)
at org.junit.runner.JUnitCore.run(JUnitCore.java:137)
at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:68)
at com.intellij.rt.execution.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:47)
at com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:242)
at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:70)

Caused by: java.sql.SQLSyntaxErrorException: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ‘.department’ at line 1
at com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:120)
at com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:97)
at com.mysql.cj.jdbc.exceptions.SQLExceptionsMapping.translateException(SQLExceptionsMapping.java:122)
at com.mysql.cj.jdbc.ClientPreparedStatement.executeInternal(ClientPreparedStatement.java:974)
at com.mysql.cj.jdbc.ClientPreparedStatement.execute(ClientPreparedStatement.java:391)
at com.alibaba.druid.pool.DruidPooledPreparedStatement.execute(DruidPooledPreparedStatement.java:497)
at org.apache.ibatis.executor.statement.PreparedStatementHandler.query(PreparedStatementHandler.java:63)
at org.apache.ibatis.executor.statement.RoutingStatementHandler.query(RoutingStatementHandler.java:79)
at org.apache.ibatis.executor.SimpleExecutor.doQuery(SimpleExecutor.java:63)
at org.apache.ibatis.executor.BaseExecutor.queryFromDatabase(BaseExecutor.java:326)
at org.apache.ibatis.executor.BaseExecutor.query(BaseExecutor.java:156)
at org.apache.ibatis.executor.CachingExecutor.query(CachingExecutor.java:109)
at com.github.pagehelper.PageInterceptor.intercept(PageInterceptor.java:143)
at org.apache.ibatis.plugin.Plugin.invoke(Plugin.java:61)
at com.sun.proxy. P r o x y 97. q u e r y ( U n k n o w n S o u r c e ) a t o r g . a p a c h e . i b a t i s . s e s s i o n . d e f a u l t s . D e f a u l t S q l S e s s i o n . s e l e c t L i s t ( D e f a u l t S q l S e s s i o n . j a v a : 148 ) a t o r g . a p a c h e . i b a t i s . s e s s i o n . d e f a u l t s . D e f a u l t S q l S e s s i o n . s e l e c t L i s t ( D e f a u l t S q l S e s s i o n . j a v a : 141 ) a t j a v a . b a s e / j d k . i n t e r n a l . r e f l e c t . N a t i v e M e t h o d A c c e s s o r I m p l . i n v o k e 0 ( N a t i v e M e t h o d ) a t j a v a . b a s e / j d k . i n t e r n a l . r e f l e c t . N a t i v e M e t h o d A c c e s s o r I m p l . i n v o k e ( N a t i v e M e t h o d A c c e s s o r I m p l . j a v a : 62 ) a t j a v a . b a s e / j d k . i n t e r n a l . r e f l e c t . D e l e g a t i n g M e t h o d A c c e s s o r I m p l . i n v o k e ( D e l e g a t i n g M e t h o d A c c e s s o r I m p l . j a v a : 43 ) a t j a v a . b a s e / j a v a . l a n g . r e f l e c t . M e t h o d . i n v o k e ( M e t h o d . j a v a : 564 ) a t o r g . m y b a t i s . s p r i n g . S q l S e s s i o n T e m p l a t e Proxy97.query(Unknown Source) at org.apache.ibatis.session.defaults.DefaultSqlSession.selectList(DefaultSqlSession.java:148) at org.apache.ibatis.session.defaults.DefaultSqlSession.selectList(DefaultSqlSession.java:141) at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) at java.base/java.lang.reflect.Method.invoke(Method.java:564) at org.mybatis.spring.SqlSessionTemplate Proxy97.query(UnknownSource)atorg.apache.ibatis.session.defaults.DefaultSqlSession.selectList(DefaultSqlSession.java:148)atorg.apache.ibatis.session.defaults.DefaultSqlSession.selectList(DefaultSqlSession.java:141)atjava.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(NativeMethod)atjava.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)atjava.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)atjava.base/java.lang.reflect.Method.invoke(Method.java:564)atorg.mybatis.spring.SqlSessionTemplateSqlSessionInterceptor.invoke(SqlSessionTemplate.java:433)
… 37 more

解决办法

在配置文件中,不要使用数据库加表的形式配置,直接给每个表配置

<!-- 这个是原来的配置-->

<!-- 配置需要指定生成的数据库和表,% 代表所有表 -->
    <table catalog="interview" tableName="%">
        <!-- mysql 配置 -->
        <generatedKey column="id" sqlStatement="Mysql" identity="true"/>
    </table>

  
<!-- 这个是现在的配置-->
<table tableName="department" domainObjectName="Department">
    </table>
    <table tableName="student" domainObjectName="Student">
    </table>

虽然一个一个表设置是麻烦了点,但是稳啊

这里再附带上我的所有配置吧,毕竟是成功了

generatorConfig.xml配置文件

<?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>
<!-- 引入数据库连接配置 -->
<properties resource="jdbc.properties"/>

<context id="Mysql" targetRuntime="MyBatis3Simple" defaultModelType="flat">
    <property name="beginningDelimiter" value="`"/>
    <property name="endingDelimiter" value="`"/>

    <!-- 配置 tk.mybatis 插件 -->
    <plugin type="tk.mybatis.mapper.generator.MapperPlugin">
        <property name="mappers" value="com.practice.springbootpracticemybatis.tk.mybatis.MyMapper"/>
    </plugin>

    <!-- 配置数据库连接 -->
    <jdbcConnection
            driverClass="${jdbc.driverClass}"
            connectionURL="${jdbc.connectionURL}"
            userId="${jdbc.username}"
            password="${jdbc.password}">
    </jdbcConnection>

    <!-- 配置实体类存放路径 -->
    <javaModelGenerator targetPackage="com.practice.springbootpracticemybatis.entity" targetProject="src/main/java"/>

    <!-- 配置 XML 存放路径 -->
    <sqlMapGenerator targetPackage="mapper" targetProject="src/main/resources/generator"/>

    <!-- 配置 DAO 存放路径 -->
    <javaClientGenerator
            targetPackage="com.practice.springbootpracticemybatis.dao"
            targetProject="src/main/java"
            type="XMLMAPPER"/>

    <!-- 配置需要指定生成的数据库和表,% 代表所有表 -->
    <table tableName="department" domainObjectName="Department">
    </table>
    <table tableName="student" domainObjectName="Student">
    </table>

</context>
</generatorConfiguration>


jdbc.properties

jdbc.driverClass=com.mysql.cj.jdbc.Driver
jdbc.connectionURL=jdbc:mysql://localhost:3306/interview?characterEncoding=utf-8&useSSL=false&serverTimezone=UTC&rewriteBatchedStatements=true
jdbc.username=root
jdbc.password=root

pom.xml

<?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 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.1.8.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.practice</groupId>
    <artifactId>spring-boot-practice-mybatis</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>spring-boot-practice-mybatis</name>
    <description>Demo project for Spring Boot</description>

    <properties>
        <java.version>1.8</java.version>
    </properties>

    <dependencies>
        <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>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web-services</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>localrepository.com.alibaba</groupId>
            <artifactId>druid-spring-boot-starter</artifactId>
            <version>1.1.16</version>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>8.0.13</version>
        </dependency>
        <dependency>
            <groupId>localrepository.tk.mybatis</groupId>
            <artifactId>mapper-spring-boot-starter</artifactId>
            <version>2.1.4</version>
        </dependency>
        <dependency>
            <groupId>com.github.pagehelper</groupId>
            <artifactId>pagehelper-spring-boot-starter</artifactId>
            <version>1.2.5</version>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
            <plugin>
                <groupId>org.mybatis.generator</groupId>
                <artifactId>mybatis-generator-maven-plugin</artifactId>
                <version>1.3.5</version>
                <configuration>
                    <configurationFile>${basedir}/src/main/resources/generator/generatorConfig.xml</configurationFile>
                    <overwrite>true</overwrite>
                    <verbose>true</verbose>
                </configuration>
                <dependencies>
                    <dependency>
                        <groupId>mysql</groupId>
                        <artifactId>mysql-connector-java</artifactId>
                        <version>${mysql.version}</version>
                    </dependency>
                    <dependency>
                        <groupId>tk.mybatis</groupId>
                        <artifactId>mapper</artifactId>
                        <version>3.4.4</version>
                    </dependency>
                </dependencies>
            </plugin>
        </plugins>
    </build>

</project>

目录结构
在这里插入图片描述

MyBatis-Plus是一个MyBatis的增强工具,在MyBatis的基础上进行了扩展,提供了更加便捷的CRUD操作、分页、乐观锁、逻辑删除等功能。而MyBatis-Plus的代码生成器则是MyBatis-Plus中的一个子模块,用于生成基于MyBatis-Plus的CRUD代码。 MyBatis-Plus的代码生成器是一个基于Velocity模板引擎的代码生成器,支持生成Java、XML、SQL脚本等文件。使用MyBatis-Plus的代码生成器可以快速生成CRUD代码,减少手动编写代码的工作量。 下面是使用MyBatis-Plus3.5.2代码生成器生成代码的步骤: 1. 添加MyBatis-Plus的依赖 在pom.xml文件中添加以下依赖: ```xml <dependency> <groupId>com.baomidou</groupId> <artifactId>mybatis-plus-generator</artifactId> <version>3.5.2</version> </dependency> ``` 2. 编写代码生成器配置文件 在src/main/resources目录下创建generator.properties文件,编写代码生成器的配置信息,例如: ```properties # 数据库配置 jdbc.driver=com.mysql.jdbc.Driver jdbc.url=jdbc:mysql://localhost:3306/mybatis_plus?useUnicode=true&characterEncoding=utf-8&serverTimezone=GMT%2B8 jdbc.username=root jdbc.password=root # 代码生成器配置 outputDir=D:/code-generator author=MyBatis-Plus fileOverride=true openDir=false ``` 其中,jdbc.driver、jdbc.url、jdbc.username、jdbc.password是数据库的配置信息,outputDir是生成文件的输出目录,author是代码的作者,fileOverride是是否覆盖已有文件,openDir是是否打开输出目录。 3. 编写代码生成器模板文件 在src/main/resources/templates目录下创建模板文件,例如entity.java.vm、mapper.xml.vm、service.java.vm、serviceImpl.java.vm等,编写模板文件的内容。 模板文件中使用Velocity的语法,可以使用变量、条件语句、循环语句等,例如: ```java package ${packageName}; import com.baomidou.mybatisplus.annotation.TableName; import lombok.Data; /** * ${tableComment} */ @Data @TableName("${tableName}") public class ${entityName} { #foreach($column in $table.columns) /** * ${column.columnComment} */ private ${column.javaType} ${column.fieldName}; #end } ``` 在模板文件中,$packageName、$tableComment、$tableName、$entityName、$table.columns等都是变量,会根据生成器配置文件和数据库表的信息动态替换为具体的值。 4. 运行代码生成器 编写好配置文件和模板文件后,就可以运行代码生成器了。在Java代码中使用CodeGenerator类,并传入配置文件和模板文件的路径,即可启动代码生成器,例如: ```java public class MybatisPlusGenerator { public static void main(String[] args) { String configFile = "generator.properties"; String templatePath = "/templates/%s.vm"; AutoGenerator generator = new AutoGenerator(); // 全局配置 GlobalConfig globalConfig = new GlobalConfig(); globalConfig.setAuthor(PropertyUtil.getProperty(configFile, "author")); globalConfig.setFileOverride(Boolean.parseBoolean(PropertyUtil.getProperty(configFile, "fileOverride"))); globalConfig.setOpen(Boolean.parseBoolean(PropertyUtil.getProperty(configFile, "openDir"))); globalConfig.setOutputDir(PropertyUtil.getProperty(configFile, "outputDir")); generator.setGlobalConfig(globalConfig); // 数据源配置 DataSourceConfig dataSourceConfig = new DataSourceConfig(); dataSourceConfig.setDbType(DbType.MYSQL); dataSourceConfig.setDriverName(PropertyUtil.getProperty(configFile, "jdbc.driver")); dataSourceConfig.setUrl(PropertyUtil.getProperty(configFile, "jdbc.url")); dataSourceConfig.setUsername(PropertyUtil.getProperty(configFile, "jdbc.username")); dataSourceConfig.setPassword(PropertyUtil.getProperty(configFile, "jdbc.password")); generator.setDataSource(dataSourceConfig); // 包配置 PackageConfig packageConfig = new PackageConfig(); packageConfig.setParent(PropertyUtil.getProperty(configFile, "package")); generator.setPackageInfo(packageConfig); // 自定义配置 InjectionConfig injectionConfig = new InjectionConfig() { @Override public void initMap() { } }; injectionConfig.setFileOutConfigList(getFileOutConfigList(templatePath)); generator.setCfg(injectionConfig); // 配置模板 TemplateConfig templateConfig = new TemplateConfig(); templateConfig.setXml(null); generator.setTemplate(templateConfig); // 策略配置 StrategyConfig strategyConfig = new StrategyConfig(); strategyConfig.setNaming(NamingStrategy.underline_to_camel); strategyConfig.setColumnNaming(NamingStrategy.underline_to_camel); strategyConfig.setEntityLombokModel(true); strategyConfig.setRestControllerStyle(true); strategyConfig.setInclude(PropertyUtil.getProperty(configFile, "tableNames").split(",")); generator.setStrategy(strategyConfig); generator.execute(); } private static List<FileOutConfig> getFileOutConfigList(String templatePath) { List<FileOutConfig> fileOutConfigList = new ArrayList<>(); fileOutConfigList.add(new FileOutConfig(templatePath) { @Override public String outputFile(TableInfo tableInfo) { return String.format("%s/%s%s", PropertyUtil.getProperty("generator.properties", "outputDir"), tableInfo.getEntityName(), this.getSuffix()); } }); return fileOutConfigList; } } ``` 在代码中,使用AutoGenerator类配置全局配置、数据源配置、包配置、自定义配置、模板配置、策略配置等,然后调用execute()方法即可生成代码。 总结:使用MyBatis-Plus的代码生成器可以快速生成基于MyBatis-Plus的CRUD代码,减少手动编写代码的工作量,提高开发效率。需要注意的是,生成的代码只是基础代码,需要根据具体业务进行修改和优化。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值