Tag Archives: mybatis

Mybatis plus configuration console prints complete SQL statement with parameters

Solution
if it is application.yml

#mybatis-plus configures the console to print full SQL statements with parameters
mybatis-plus:
  configuration:
    log-impl: org.apache.ibatis.logging.stdout.StdOutImpl

If it is application.properties, add:

#mybatis-plus configures the console to print full SQL statements with parameters
mybatis-plus.configuration.log-impl=org.apache.ibatis.logging.stdout.StdOutImpl

Cannot resolve classpath entry: e://jar/mysql-connector-java-5.1.17-bin mybatis error in reverse engineering

error: failed: Cannot resolve classpath entry: E:\jar\mysql-connector-java-5.1.17-bin -> [Help 1]

[INFO] Scanning for projects…
[INFO]
[INFO] ————————–< pay-center:demo >—————————
[INFO] Building demo 0.0.1-SNAPSHOT
[INFO] ——————————–[ jar ]———————————
[INFO]
[INFO] — mybatis-generator-maven-plugin:1.3.2:generate (default-cli) @ demo —
[INFO] ————————————————————————
[INFO] BUILD FAILURE
[INFO] ————————————————————————
[INFO] Total time: 1.043 s
[INFO] Finished at: 2021-07-01T10:31:26+08:00
[INFO] ————————————————————————
[ERROR] Failed to execute goal org.mybatis.generator:mybatis-generator-maven-plugin:1.3.2:generate (default-cli) on project demo: Execution default-cli of goal org.mybatis.generator:mybatis-generator-maven-plugin:1.3.2:generate failed: Cannot resolve classpath entry: E:\jar\mysql-connector-java-5.1.17-bin -> [Help 1]
[ERROR]
[ERROR] To see the full stack trace of the errors, re-run Maven with the -e switch.
[ERROR] Re-run Maven using the -X switch to enable full debug logging.
[ERROR]
[ERROR] For more information about the errors and possible solutions, please read the following articles:
[ERROR] [Help 1] http://cwiki.apache.org/confluence/display/MAVEN/PluginExecutionException
My generatorConfig.xml file looks like this, showing only the parts.



My generatorConfig.xml file looks like this, showing only the parts.

<?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>


    <!-- Database driver: select the database driver package on your local hard disk-->
    <classPathEntry  location="E:\jar\mysql-connector-java-5.1.17-bin"/>

    <context id="DB2Tables"  targetRuntime="MyBatis3">
        <commentGenerator>
            <property name="suppressDate" value="true"/>
            <!-- Whether to remove automatically generated comments true: yes : false:no -->
            <property name="suppressAllComments" value="true"/>
        </commentGenerator>



This database driver cannot be found problem occurs, go directly to the database driver to delete. The following figure shows the comparison of the two figures
<?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="DB2Tables"  targetRuntime="MyBatis3">
        <commentGenerator>
            <property name="suppressDate" value="true"/>
            <!-- Whether to remove automatically generated comments true: yes : false:no -->
            <property name="suppressAllComments" value="true"/>
        </commentGenerator>

Error querying database. Cause: com.mysql.jdbc.exceptions.jdbc4.CommunicationsException: Communicat

Solution: when connecting to the database, change usessl = true to usessl = false. Of course, if usessl = true is not written, it is true by default.

Note: however, I don’t know why I did it. What’s more, the tutorial I read only uses true, and why I report an error. If a boss sees it, he hopes to answer it.

[Solved] MybatisPlusException: Error: Method queryTotal execution error of sql

Cause: com.baomidou.mybatisplus.core.exceptions.MybatisPlusException: Error: Method queryTotal execution error of sql :

Error reason:
the user-defined SQL is written in mapper, where is added too much, and the user-defined SQL is transferred into querywrapper, where cannot be added
error code:

String customSql="select * from ("+queryAll+") as q where ${ew.customSqlSegment}";
    @Select(customSql)
    IPage<BranchBasic> baseQuery(Page<Object> objectPage, @Param(Constants.WRAPPER)QueryWrapper queryWrapper);
   

Correct code:
as both case and upper case are OK

String customSql="select * from ("+queryAll+") as q ${ew.customSqlSegment}";
    @Select(customSql)
    IPage<BranchBasic> baseQuery(Page<Object> objectPage, @Param(Constants.WRAPPER)QueryWrapper queryWrapper);

[Solved] Could not find resource COM / atguigu / Dao / studentdao.xm, the mapper file for storing SQL statements could not be found and an error occurred

The mapper file created by using the Maven project mybatis to operate the database is not put under the resource resource file. The following error occurs during compilation

org.apache.ibatis.exceptions.PersistenceException: 
### Error building SqlSession.
### The error may exist in com\atguigu\dao\StudentDao.xml
### Cause: org.apache.ibatis.builder.BuilderException: Error parsing SQL Mapper Configuration. Cause: java.io.IOException: Could not find resource com\atguigu\dao\StudentDao.xml

	at org.apache.ibatis.exceptions.ExceptionFactory.wrapException(ExceptionFactory.java:30)
	at org.apache.ibatis.session.SqlSessionFactoryBuilder.build(SqlSessionFactoryBuilder.java:80)
	at org.apache.ibatis.session.SqlSessionFactoryBuilder.build(SqlSessionFactoryBuilder.java:64)
	at com.atguigu.Test1.test01(Test1.java:23)
	at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
	at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
	at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
	at java.lang.reflect.Method.invoke(Method.java:498)
	at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:47)
	at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
	at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:44)
	at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
	at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:271)
	at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:70)
	at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:50)
	at org.junit.runners.ParentRunner$3.run(ParentRunner.java:238)
	at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:63)
	at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:236)
	at org.junit.runners.ParentRunner.access$000(ParentRunner.java:53)
	at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:229)
	at org.junit.runners.ParentRunner.run(ParentRunner.java:309)
	at org.junit.runner.JUnitCore.run(JUnitCore.java:160)
	at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:68)
	at com.intellij.rt.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:33)
	at com.intellij.rt.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:230)
	at com.intellij.rt.junit.JUnitStarter.main(JUnitStarter.java:58)
Caused by: org.apache.ibatis.builder.BuilderException: Error parsing SQL Mapper Configuration. Cause: java.io.IOException: Could not find resource com\atguigu\dao\StudentDao.xml
	at org.apache.ibatis.builder.xml.XMLConfigBuilder.parseConfiguration(XMLConfigBuilder.java:121)
	at org.apache.ibatis.builder.xml.XMLConfigBuilder.parse(XMLConfigBuilder.java:98)
	at org.apache.ibatis.session.SqlSessionFactoryBuilder.build(SqlSessionFactoryBuilder.java:78)
	... 24 more
Caused by: java.io.IOException: Could not find resource com\atguigu\dao\StudentDao.xml
	at org.apache.ibatis.io.Resources.getResourceAsStream(Resources.java:114)
	at org.apache.ibatis.io.Resources.getResourceAsStream(Resources.java:100)
	at org.apache.ibatis.builder.xml.XMLConfigBuilder.mapperElement(XMLConfigBuilder.java:371)
	at org.apache.ibatis.builder.xml.XMLConfigBuilder.parseConfiguration(XMLConfigBuilder.java:119)
	... 26 more



This is because the dao.xml file under the mapper file can not find the statement file to operate the database during compilation. There are two solutions to the problem.
the first one is to put the file to store the database statement under the resource file. Remember to modify the mybatis main configuration file

 	 <mappers>
        <mapper resource="com\zixi\dao\StudentDao.xml"/>
    </mappers>

    <!--    Modify your path directly to the following-->

    <mappers>
    <mapper resource="StudentDao.xml"/>
</mappers>
    

If you don’t want to modify and copy, you can directly add the Blid tag under the Maven configuration file and add the following content

  <build>
<!--        To solve the problem of writing sql statements in main.com.**. file, but when compiling, the xmlsql file error does not appear in out-->
        <resources>
            <resources>
                <directory>src/main/java</directory><! --directory where -->
                <includes><! --Includes directories where .properties, .xml files are scanned -->
                    <include>**/*.properties</include>
                    <include>**/*.xml</include>
                </includes>
                <filtering>false</filtering>
            </resource>
        </resources>
    </build>

This is my own practice problems, the above content can only be used as a reference, hope to be useful to you. thank you

Springboot running shows application run failed [How to Solve]

Error:

Error starting ApplicationContext. To display the conditions report re-run your application with 'debug' enabled.
2021-06-28 14:27:13.827 ERROR 7512 --- [  restartedMain] o.s.boot.SpringApplication               : Application run failed

Background

It’s time to review. The teacher asked me to write a springboot project, but I couldn’t run it. Running application shows that application cannot be run
some errors were encountered in the process. I searched Baidu, and the result is as follows:
in the annotation of application, there is @ springbootapplication , which should be replaced by @ springbootapplication (exclude = datasourceautoconfiguration. Class) , but the result still doesn’t work.

Exclude to exclude such autoconfig, that is, to prohibit springboot from automatically injecting data source configuration. In this case, the automatic injection of mybits is excluded. As a result, there is a problem in the mapper layer.

Let the teacher have a look today. There is something wrong with the YML file.

Forget to write spring keywords, which I don’t understand.

server:
  port: 5050 # tomcat port
  servlet:
    context-path: /UserModel

spring:# I forgot to write it here, so that datesource belongs to the server
  datasource:
    type: com.alibaba.druid.pool.DruidDataSource
    driver-class-name: com.mysql.cj.jdbc.Driver
    url: jdbc:mysql://localhost:3306/1202?useSSL=false&serverTimezone=Asia/Shanghai&characterEncoding=utf-8
    username: root
    password: root

An error occurred while accessing the controller

The error reported is the same as this:

would dispatch back to the current handler URL [/UserModel/queryUserById] 

The difference between @Controller and @RestController is actually confusing
@Controller, @RestController?
Forgot the difference between get and post

Written by.
http://localhost:5050/UserModel/deleteUserByIds?ids=3,4

[Solved] javax.servlet.ServletException: Servlet[springmvc] Servlet.init()

1. There are many cases of this exception. First of all,
when configuring sqlsessionfactorybean, you should not pay attention to the problem (see the figure)

the same as above, when configuring other places, you also use ref as value. For example,

PS: combined with the above, it can discharge itself. Pay attention to whether it is this problem

2. Problems that we didn’t pay attention to when configuring servlets with web.xml

as shown in the figure: after the integration, the configuration file should not be MVC, but should be all. Generally, when creating a configuration file, there will be a prompt in the upper right corner, which may cause this kind of problem if you don’t pay attention to it. Generally, my solution is to use the import tag (as shown in the figure)

import all the configuration files into a general file
and then import the web and XML into the general file as follows

PS: there are some special reasons, which vary from person to person. Hope someone can add!

Error attempting to get column from result set

When using mybatis plus3.2.0 + springboot2.1.1, an error is reported
error attaching to get column from result set
1. Generally, this kind of problem occurs. The simplest error may be that the field type of the database is inconsistent with the type of the entity class
2. But I’m not. I use @ builder in the entity class, but I don’t use @ allargsconstructor and @ noargsconstructor, There is no parameterless constructor

[Solved] Cannot find class: com.mysql.jdbc.Driver

When using mybatis to write the entry instance for the first time, I encountered the error of cannot find class: com.mysql.jdbc.driver database property configuration file content:

jdbc.driver=com.mysql.cj.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/exercise?serverTimezone=GMT%2B8
jdbc.user=root
jdbc.password=1996mysqlyue

Mybatis configuration part:

            <!--Four basic information for connecting to the database-->
            <dataSource type="POOLED">
                <property name="driver" value="${jdbc.driver}"/>
                <property name="url" value="${jdbc.url}"/>
                <property name="username" value="${jdbc.user}"/>
                <property name="password" value="${jdbc.password}"/>
            </dataSource>

Confirm that there is no space in the quotation marks of the value value in the configuration file, and there is no space in the configuration information of the database property file, but still report an error
subsequent solution:
modified the dependency version of MySQL connector introduced by Maven.

[How to Solve] Invalid bound statement (not found)

When integrating mybatis with springboot, an error of invalid bound statement (not found) is reported. After repeated changes and trial and error, it is found that mapper.xml cannot be scanned. The key lies in two aspects.

    1. if you put XML in the Java directory, you need to configure the path in the POM package
<resources>
			<resource>
				<directory>src/main/java</directory>
				<includes>
					<include>**/sqlmap/*.xml</include>
				</includes>
				<filtering>false</filtering>
			</resource>
			<resource>
				<directory>src/main/resources</directory>
				<includes>
					<include>**/*.*</include>
				</includes>
				<filtering>true</filtering>
			</resource>
		</resources>
      1. add the statement of scan mapping file to mybatis configuration class
 PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
        sessionFactory.setMapperLocations(resolver.getResources("classpath*:**/sqlmap/*.xml"));//扫描映射文件
        1. if the mapper.xml file is placed in the resources directory, maperlocations should be configured in application.yml
mybatis:
  mapper-locations: classpath:mapping/*.xml  #Note: Be sure to correspond to the path where the mapper mapping xml file is located