Tag Archives: mybatis

[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

Mybatis passes in multiple parameters to mapper. And uses @param details to report an error

“nested   exception   is   org.apache.ibatis.binding.BindingException:   Parameter  ‘ orgName’   not   found.   Available   parameters   are  [ wxOrganizationAccount,   page,   param1,   param2]”,

This bug was fixed for a long time and finally found.

At the beginning, I thought that the @ param annotation was not written when multiple parameters were passed in, but I found that it was not right after writing,

“nested   exception   is   org.apache.ibatis.binding.BindingException:   Parameter  ‘ orgName’   not   found.   Available   parameters   are  [ wxOrganizationAccount,   page,   param1,   param2]”,

I want to add another parameter’s type field to an entity class, then save the parameter into the entity class, and then pass only one object in the process of passing the parameter. Of course, these are just my personal ideas. In the end, of course, they failed.

“nested   exception   is   org.apache.ibatis.binding.BindingException:   Parameter  ‘ orgName’   not   found.   Available   parameters   are  [ wxOrganizationAccount,   page,   param1]”,

It’s just missing a parameter, or it’s wrong. At this time, I was thinking that since it’s not the problem passed in, it might be the problem of value taking. Finally, I found that the value can’t be taken because it’s not accurate enough to get the value from the object!

com.fasterxml.jackson.databind.exc.InvalidDefinitionException: No serializer found for class

com.fasterxml.jackson.databind.exc.InvalidDefinitionException: No serializer found for class (through reference chain: com.jd.lean.mjp.dal.entity.Province_$$_ jvste70_ 0[“handler”])

1. Background

When using mybatis one to many collection query, an error is reported

2. Solution

One to many, entity class, with annotation
@ jsonignoreproperties (value = {“handler”})

3. Reasons

JSON serialization does not ignore some properties in the bean that do not need to be converted, such as handler

[Solved] The number of rows returned by the mybatis UPDATE statement is always 1 or useaffectedrows = true

The number of rows returned by the mybatis UPDATE statement is always 1 or useaffectedrows = true

Problem solving explanation useaffectedrows = true

solve the problem

     This is because the database url connection is missing useAffectedRows=true

 The problem is solved here, but I'll explain it later useAffectedRows=true.

Explain useaffectedrows = true

 useAffectedRows defaults to false, and the value returned is the number of rows matched.
    useAffectedRows = true, the value returned is the number of rows affected.

[Solved] Mybatis Error: Cause: org.apache.ibatis.builder.BuilderException: Error parsing SQL Mapper Configuration.

Testing Mybatis, querying data, reporting errors.
### Error building SqlSession
### The error may exist in com/lxc/dao/UserMapper.xml
### Cause: org.apache.ibatis.builder.BuilderException: Error parsing SQL Mapper Configuration. Cause: org.apache.ibatis.builder.BuilderException: Error parsing Mapper XML. The XML location is ‘com/lxc/dao/UserMapper.xml’. Cause: org.apache.ibatis.builder.BuilderException: Error resolving class. Cause: org.apache.ibatis.type.TypeException: Could not resolve type alias ‘User’.  Cause: java.lang.ClassNotFoundException: Cannot find class: User
The green circle in the screenshot below is the error file, look further back Cannot find class: User , indicating that the class was not found

In looking at the error file configuration.
Locate the error place, should write the full path

Solution:

Using Mybatis to connect to the database error: Loading class `com.mysql.jdbc.Driver‘. This is deprecated. The new driver···

Mybatis connects to a Mysql database with the following warning.
Loading class `com.mysql.jdbc.Driver’. This is deprecated. The new driver class is `com.mysql.cj.jdbc.Driver’. The driver is automatically registered via the SPI and manual loading of the driver class is generally unnecessary.

Solution.
In the Mybatis connection database configuration file, modify the connection driver to.

<dataSource type="POOLED">
    <!--change com.mysql.jdbc.Driver to com.mysql.cj.jdbc.Driver -->
    <property name="driver" value="com.mysql.cj.jdbc.Driver"/>
</dataSource>

Mybatis Error: Cause: org.apache.ibatis.builder.BuilderException: Error creating document instance.

Error reporting in mybatis learning: cause: org.apache.ibatis.builder.builderexception: error creating document instance. Cause: com.sun.org.apache.xerces.internal.impl.io.malformedbytesequenceexception: byte 1 of 1-byte UTF-8 sequence is invalid.)

Error details solution

Error details

java.lang.ExceptionInInitializerError
	at com.yy.dao.UserDaoTest.test(UserDaoTest.java:16)
	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: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.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)
	at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:78)
	at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:57)
	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.junit.runners.ParentRunner.run(ParentRunner.java:363)
	at org.junit.runner.JUnitCore.run(JUnitCore.java:137)
	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.exceptions.PersistenceException: 
### Error building SqlSession.
### Cause: org.apache.ibatis.builder.BuilderException: Error creating document instance.  Cause: com.sun.org.apache.xerces.internal.impl.io.MalformedByteSequenceException: 1 字节的 UTF-8 序列的字节 1 无效。
	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.yy.utils.MybatisUtils.<clinit>(MybatisUtils.java:20)
	... 23 more
Caused by: org.apache.ibatis.builder.BuilderException: Error creating document instance.  Cause: com.sun.org.apache.xerces.internal.impl.io.MalformedByteSequenceException: 1 字节的 UTF-8 序列的字节 1 无效。
	at org.apache.ibatis.parsing.XPathParser.createDocument(XPathParser.java:260)
	at org.apache.ibatis.parsing.XPathParser.<init>(XPathParser.java:126)
	at org.apache.ibatis.builder.xml.XMLConfigBuilder.<init>(XMLConfigBuilder.java:81)
	at org.apache.ibatis.session.SqlSessionFactoryBuilder.build(SqlSessionFactoryBuilder.java:77)
	... 25 more
Caused by: com.sun.org.apache.xerces.internal.impl.io.MalformedByteSequenceException: 1 字节的 UTF-8 序列的字节 1 无效。
	at com.sun.org.apache.xerces.internal.impl.io.UTF8Reader.invalidByte(UTF8Reader.java:701)
	at com.sun.org.apache.xerces.internal.impl.io.UTF8Reader.read(UTF8Reader.java:567)
	at com.sun.org.apache.xerces.internal.impl.XMLEntityScanner.load(XMLEntityScanner.java:1895)
	at com.sun.org.apache.xerces.internal.impl.XMLEntityScanner.scanData(XMLEntityScanner.java:1375)
	at com.sun.org.apache.xerces.internal.impl.XMLScanner.scanComment(XMLScanner.java:801)
	at com.sun.org.apache.xerces.internal.impl.XMLDocumentFragmentScannerImpl.scanComment(XMLDocumentFragmentScannerImpl.java:1034)
	at com.sun.org.apache.xerces.internal.impl.XMLDocumentFragmentScannerImpl$FragmentContentDriver.next(XMLDocumentFragmentScannerImpl.java:2982)
	at com.sun.org.apache.xerces.internal.impl.XMLDocumentScannerImpl.next(XMLDocumentScannerImpl.java:602)
	at com.sun.org.apache.xerces.internal.impl.XMLDocumentFragmentScannerImpl.scanDocument(XMLDocumentFragmentScannerImpl.java:505)
	at com.sun.org.apache.xerces.internal.parsers.XML11Configuration.parse(XML11Configuration.java:842)
	at com.sun.org.apache.xerces.internal.parsers.XML11Configuration.parse(XML11Configuration.java:771)
	at com.sun.org.apache.xerces.internal.parsers.XMLParser.parse(XMLParser.java:141)
	at com.sun.org.apache.xerces.internal.parsers.DOMParser.parse(DOMParser.java:243)
	at com.sun.org.apache.xerces.internal.jaxp.DocumentBuilderImpl.parse(DocumentBuilderImpl.java:339)
	at org.apache.ibatis.parsing.XPathParser.createDocument(XPathParser.java:258)
	... 28 more


Process finished with exit code -1

When I taught mybatis by myself, I always reported this error because I wrote comments in two. XML files for easy learning

resolvent

Just delete all the Chinese comments in. XML

Just use this to record the error report, so as to avoid wasting time to find solutions when reporting errors again in the future.

Solve the problem that springboot does not scan @ repository

Problem: if you use @ repository annotation to annotate Dao layer alone, and do not use @ mapperscan scan, you will report an error when starting the project: field xxmapper in com.sms.shiro.service.impl.xxserviceimpl required a bean of type ‘com.sms.shiro.mapper.xxmapper’that could not be found.
, the difference between @ mapper and @ Repository:
1, @Repository is the annotation of spring family
2. When using @ mapper annotation, spring doesn’t know it, and the mapper injected into service by @ Autowired will be popular.

2、 Back to the question, it is clear that componentscan in springboot scans all annotated components under the starter package, but why can’t we find @ repository components
reason: the reason for this problem is that springboot automatically filters out interfaces and abstract classes during scanning, so the mapper interface modified by @ repository can’t be called a bean, so it can’t be injected into the service.

3、 Solution:

3.1 do not use @ repository, use @ mapper directly in the mapper layer interface, but if the project is large, it will be very troublesome.

3.2 if you want to use @ repository because springboot can’t scan mapper interface, then use @ mapperscan to scan all mapper interface packages on the launcher, such as: @ mapperscan ("com. SMS. Shiro. *. Mapper")

3.3 in fact, after using @ maperscan annotation to scan the mapper interface, the mapper interface does not need @ repository and @ mapper to register beans. However, if you want the project structure to be clear, after using @ maperscan annotation to scan, both @ repository and @ mapper can be used, and no error will be reported.