Tag Archives: mybatis

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

org.apache.ibatis.exceptions.PersistenceException: 
### Error building SqlSession.
### The error may exist in mappers/user.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 'mappers/user.xml'. Cause: org.apache.ibatis.builder.BuilderException: Error resolving class. Cause: org.apache.ibatis.type.TypeException: Could not resolve type alias ''.  Cause: java.lang.ClassNotFoundException: Cannot find class: 

This error occurs in the mybatis test for many reasons,
1: it may be the header information error of the mapping file. Correct:
2: there may also be an error in the label of the mapping file. Most of the errors reported in the mapping file are code errors. Just check the code
3: I made an error today because I wrote an extra tag, but the content in the tag was not written

4: The same type of error I encountered yesterday is because I wrote a comment in the where tag

<select>
	<where>
		Write comment here. This error has been encountered twice, as soon as a comment is written inside a tag, an error is reported
	</where>
</select>

These are the mistakes and solutions I met in learning mybatis.

[Solved] mybatis Error: Cause: org.apache.ibatis.builder.BuilderException: Error creating document instance.

java.lang.ExceptionInInitializerError
	at com.example.dao.UserDaoTest.test(UserDaoTest.java:12)
	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:566)
	at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:59)
	at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
	at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:56)
	at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
	at org.junit.runners.ParentRunner$3.evaluate(ParentRunner.java:306)
	at org.junit.runners.BlockJUnit4ClassRunner$1.evaluate(BlockJUnit4ClassRunner.java:100)
	at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:366)
	at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:103)
	at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:63)
	at org.junit.runners.ParentRunner$4.run(ParentRunner.java:331)
	at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:79)
	at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:329)
	at org.junit.runners.ParentRunner.access$100(ParentRunner.java:66)
	at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:293)
	at org.junit.runners.ParentRunner$3.evaluate(ParentRunner.java:306)
	at org.junit.runners.ParentRunner.run(ParentRunner.java:413)
	at org.junit.runner.JUnitCore.run(JUnitCore.java:137)
	at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:69)
	at com.intellij.rt.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:33)
	at com.intellij.rt.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:221)
	at com.intellij.rt.junit.JUnitStarter.main(JUnitStarter.java:54)
Caused by: org.apache.ibatis.exceptions.PersistenceException: 
### Error building SqlSession.
### Cause: org.apache.ibatis.builder.BuilderException: Error creating document instance.  Cause: org.xml.sax.SAXParseException; lineNumber: 5; columnNumber: 18; 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.example.util.MybatisUtils.<clinit>(MybatisUtils.java:19)
	... 26 more
Caused by: org.apache.ibatis.builder.BuilderException: Error creating document instance.  Cause: org.xml.sax.SAXParseException; lineNumber: 5; columnNumber: 18; 1 字节的 UTF-8 序列的字节 1 无效。
	at org.apache.ibatis.parsing.XPathParser.createDocument(XPathParser.java:263)
	at org.apache.ibatis.parsing.XPathParser.<init>(XPathParser.java:127)
	at org.apache.ibatis.builder.xml.XMLConfigBuilder.<init>(XMLConfigBuilder.java:81)
	at org.apache.ibatis.session.SqlSessionFactoryBuilder.build(SqlSessionFactoryBuilder.java:77)
	... 28 more
Caused by: org.xml.sax.SAXParseException; lineNumber: 5; columnNumber: 18; 1 字节的 UTF-8 序列的字节 1 无效。
	at java.xml/com.sun.org.apache.xerces.internal.util.ErrorHandlerWrapper.createSAXParseException(ErrorHandlerWrapper.java:204)
	at java.xml/com.sun.org.apache.xerces.internal.util.ErrorHandlerWrapper.fatalError(ErrorHandlerWrapper.java:178)
	at java.xml/com.sun.org.apache.xerces.internal.impl.XMLErrorReporter.reportError(XMLErrorReporter.java:400)
	at java.xml/com.sun.org.apache.xerces.internal.impl.XMLErrorReporter.reportError(XMLErrorReporter.java:306)
	at java.xml/com.sun.org.apache.xerces.internal.impl.XMLDocumentScannerImpl$PrologDriver.next(XMLDocumentScannerImpl.java:1000)
	at java.xml/com.sun.org.apache.xerces.internal.impl.XMLDocumentScannerImpl.next(XMLDocumentScannerImpl.java:605)
	at java.xml/com.sun.org.apache.xerces.internal.impl.XMLDocumentFragmentScannerImpl.scanDocument(XMLDocumentFragmentScannerImpl.java:534)
	at java.xml/com.sun.org.apache.xerces.internal.parsers.XML11Configuration.parse(XML11Configuration.java:888)
	at java.xml/com.sun.org.apache.xerces.internal.parsers.XML11Configuration.parse(XML11Configuration.java:824)
	at java.xml/com.sun.org.apache.xerces.internal.parsers.XMLParser.parse(XMLParser.java:141)
	at java.xml/com.sun.org.apache.xerces.internal.parsers.DOMParser.parse(DOMParser.java:246)
	at java.xml/com.sun.org.apache.xerces.internal.jaxp.DocumentBuilderImpl.parse(DocumentBuilderImpl.java:339)
	at org.apache.ibatis.parsing.XPathParser.createDocument(XPathParser.java:261)
	... 31 more
Caused by: com.sun.org.apache.xerces.internal.impl.io.MalformedByteSequenceException: 1 字节的 UTF-8 序列的字节 1 无效。
	at java.xml/com.sun.org.apache.xerces.internal.impl.io.UTF8Reader.invalidByte(UTF8Reader.java:702)
	at java.xml/com.sun.org.apache.xerces.internal.impl.io.UTF8Reader.read(UTF8Reader.java:568)
	at java.xml/com.sun.org.apache.xerces.internal.impl.XMLEntityScanner.load(XMLEntityScanner.java:1904)
	at java.xml/com.sun.org.apache.xerces.internal.impl.XMLEntityScanner.scanData(XMLEntityScanner.java:1377)
	at java.xml/com.sun.org.apache.xerces.internal.impl.XMLScanner.scanComment(XMLScanner.java:800)
	at java.xml/com.sun.org.apache.xerces.internal.impl.XMLDocumentFragmentScannerImpl.scanComment(XMLDocumentFragmentScannerImpl.java:1069)
	at java.xml/com.sun.org.apache.xerces.internal.impl.XMLDocumentScannerImpl$PrologDriver.next(XMLDocumentScannerImpl.java:883)
	... 39 more

Solution:

Change UTF-8 in the XML of all configuration files to utf8

After modification, you can query it.

MP Error: ‘getBaseMappe ServiceImpl’ clashes [How to Solve]

ServiceImp error:

‘getBaseMapper()’ in ‘com.baomidou.mybatisplus.extension.service.impl.ServiceImpl’ clashes with ‘getBaseMapper()’ in ‘com.baomidou.mybatisplus.extension.service.IService’; attempting to use incompatible return type

In MyBatis-plus, the general reference package is

com.baomidou.mybatisplus.core.mapper;

Looking at the source code, we can see that both the IService and its implementation class ServiceImpl require the Mapper

<M extends BaseMapper<T>, T>
ServiceImpl<M extends BaseMapper<T>, T> implements IService<T>

Problem solving: check whether the mapper used in the self-defined xxservicei is a subclass of basemapper, and

Mapper generic reference should be consistent with iservice.

log4j:WARN Error during default initialization [How to Solve]

Error generation environment

Generated when mybatis sets log4j log

Error description

log4j:ERROR Category option " 1 " not a decimal integer.
java.lang.NumberFormatException: For input string: " 1 "

Error reason

In the log4j.properties file, there are more spaces in the log4j.appender.console.layout.conversionpattern attribute

Solution:

Before modification:

log4j.appender.console.layout.ConversionPattern =  %d{ABSOLUTE} %5p %c{ 1 }:%L - %m%n

After modification:

log4j.appender.console.layout.ConversionPattern =  %d{ABSOLUTE} %5p %c{1}:%L - %m%n

Mybatis sets the primary key Auto-Increment error: No setter found for the keyProperty

Mybatis sets the auto increment of the primary key, and an error is reported: no setter found for the keyproperty

SQL statement in XML:

<insert id="registerReader" parameterType="com.by.tsgl.bean.Reader" useGeneratedKeys="true" keyProperty="reader_id">
    insert into reader(deposit_num,borrowing_num,reader_state,grade_id,user_id)
    values(0,0,"normal",1,#{user_id});
</insert>

Test Times Error
org.mybatis.spring.MyBatisSystemException: nested exception is org.apache.ibatis.executor.ExecutorException: Error getting generated key or setting result to parameter object. Cause: org.apache.ibatis.executor.ExecutorException: No setter found for the keyProperty 'reader_id' in 'java.lang.String'.
Solution:
Remove the keyProperty property from the insert tag
Change it to.

<insert id="registerReader" parameterType="com.by.tsgl.bean.Reader" useGeneratedKeys="true">

Cause analysis

The corresponding value in keyProperty is a property of the entity class, not a database field.

The fields that have been set up for primary key auto-increment in the database only need to configure the useGeneratedKeys attribute.

useGeneratedKeys=“true” keyProperty=“id”
When useGeneratedKeys is set to true, it means that if the inserted table id has an auto-incrementing column as the primary key, JDBC is allowed to support automatic primary key generation.

keyProperty=“id” The automatically generated primary key id can be returned to the id of the passed in object . Since the object we passed in does not have the id field, it naturally does not have its set method, so an error will be reported.

What if there is no primary key in the inserted table?

Can use attributeskeyColumn

<insert id="registerReader" parameterType="com.by.tsgl.bean.Reader" useGeneratedKeys=true keyProperty="userId" keyColumn="user_id">
    

This annotation means to use the primary key automatically increased by the database and user from the table_ In the ID field, put the data into the member variable userid of the incoming object. If we have specified the primary key in the database table, the keycolumn attribute can be defaulted</ ol>

The following is from the mybatis document

usegeneratedkeys (only applicable to insert and update) this will make mybatis use JDBC’s getgeneratedkeys method to retrieve the primary key generated internally by the database (such as the auto increment field of relational database management systems such as MySQL and SQL Server). The default value is false
keyproperty (only applicable to insert and update) specifies the property that can uniquely identify the object. Mybatis will use the return value of getgeneratedkeys or the selectkey sub element of the insert statement to set its value. The default value is unset. If more than one column is generated, multiple attribute names can be separated by commas.

[Solved] thymeleaf.TemplateEngineException processing template “main“: An error happened during template pars

preface

This project uses the thymeleaf template in the springboot project. The main error is that the front-end HTML page uses thymeleaf to obtain the value passed from the background. There is a problem (the value cannot be obtained, or it is empty and null)

Error message

1. error 1: the forwarded is used as redirect:/main

2021-11-18 21:02:01.321 ERROR 9272 — [nio-8082-exec-4] org.thymeleaf.TemplateEngine : [THYMELEAF][http-nio-8082-exec-4] Exception processing template “main”: An error happened during template parsing (template: “class path resource [templates/main.html]”)
*
* org.thymeleaf.exceptions.TemplateInputException: An error happened during template parsing (template: “class path resource [templates/main.html]”)
* at org.thymeleaf.templateparser.markup.AbstractMarkupTemplateParser.parse(AbstractMarkupTemplateParser.java:241) ~[thymeleaf-3.0.12.RELEASE.jar:3.0.12.RELEASE]
* caused by: org.thymeleaf.exceptions.templateprocessingexception: exception evaluating springel expression: "page. Getcurrent()" (template: "main" - line 86, col 17)
* redirection cannot be used here: otherwise, the front-end data cannot be obtained through thymeleaf

2. error 2: null value error

 org.springframework.expression.spel.SpelEvaluationException: EL1007E: Property or field ‘records’ cannot be found on null

Solution:

1. The first error is that when the data queried in the background is sent to the front-end HTML page, there is no corresponding value, and redirection cannot be used, otherwise the front-end data cannot be obtained through thymeleaf. Remove redirect directly and return “main” directly “;
2. The second error is somewhat similar to the first one. This error can find the corresponding data in the background on the page, but the paging data cannot be obtained without corresponding request. If you enter this page directly from the login interface, it is an error because the data of another requested page paging query is used, and there is no query directly The paging data is null. Therefore, you can only send a request to query the page paging data before it can successfully reach the main page.

Corresponding part code

1. Front end code main.html

<!--Employee data table display-->
<div class="container table-responsive" style="margin-top: 50px">
    <table class="table table-bordered">
        <caption class="caption"><a th:href="@{/showemp}">Display employee information</a> </caption>
        <thead>
            <tr>
                <th>ID</th>
                <th>ID</th>
                <th>Name</th>
                <th>Password</th>
                <th>operate</th>
            </tr>
        </thead>
        <tbody>
            <tr th:each="book,statu:${page.records}">
                <th>[[${statu.count}]]</th>
                <td th:text="${book.id}"></td>
                <td>[[${book.name}]]</td>
                <td>[[${book.password}]]</td>
                <td>
                    <a th:href="@{/delete}" type="button" class="btn btn-danger btn-sm">delete</a>
                    <a th:href="@{/update}" type="button" class="btn btn-info btn-sm">update</a></td>
            </tr>
        </tbody>
    </table>
</div>

2.CrudController.java

@Controller
public class CrudController {
   @Autowired
   BookServiceImpl bookService;

   @GetMapping("/showemp")
   public String selectAll(@RequestParam(value = "pn",defaultValue = "1")Integer pn,
                           Model model){
       Page<Book> page = new Page<>(pn,2);
       Page<Book> bookPage = bookService.page(page, null);
       model.addAttribute("page",bookPage);
       System.out.println(bookPage.getCurrent());
       System.out.println(bookPage.getRecords().size());
       /**
        * 2021-11-18 21:02:01.321 ERROR 9272 --- [nio-8082-exec-4] org.thymeleaf.TemplateEngine             : [THYMELEAF][http-nio-8082-exec-4] Exception processing template "main": An error happened during template parsing (template: "class path resource [templates/main.html]")
        *
        * org.thymeleaf.exceptions.TemplateInputException: An error happened during template parsing (template: "class path resource [templates/main.html]")
        * 	at org.thymeleaf.templateparser.markup.AbstractMarkupTemplateParser.parse(AbstractMarkupTemplateParser.java:241) ~[thymeleaf-3.0.12.RELEASE.jar:3.0.12.RELEASE]
        * Caused by: org.thymeleaf.exceptions.TemplateProcessingException: Exception evaluating SpringEL expression: "page.getCurrent()" (template: "main" - line 86, col 17)
        * Redirection cannot be used here: otherwise the front-end data cannot be obtained through thymeleaf
        */
//        return "redirect:/main";
       return "main";
   }
}

3.LoginController.java

@PostMapping("/login")
    public String LoginValidation(Book book,
                                  RedirectAttributes redirectAttributes){
        String name = book.getName();
        String password = book.getPassword();
        Map<String,Object> map = new HashMap<>();
        map.put("name",name);
        map.put("password",password);
        QueryWrapper<Book> queryWrapper = new QueryWrapper<>();
        queryWrapper.ge("name",name );
        queryWrapper.ge("password",password);
        Book one = bookService.getOne(queryWrapper);
        if (one.toString()!=null){
            /**
             * org.springframework.expression.spel.SpelEvaluationException: EL1007E: Property or field 'records' cannot be found on null
             * It is wrong to enter this page directly from the login interface, because the page paging query data requested by showemp is used here, and there is no query when entering directly, and the page paging data is null.
              * So you can only successfully reach the main page by sending a showemp request to query the page paging data.
             */
//            return "redirect:/main";
            return "redirect:/showemp";
        }
        return "login";
    }

[Solved] java.sql.SQLSyntaxErrorException: You have an error in your SQL syntax; check the manual that corres

0. Foreword: this error is an error reported by using mybatis in the spring boot project to query a piece of data in the database according to the ID value

1. Error message

2021-11-14 15:37:38.168 ERROR 9936 --- [nio-8086-exec-7] o.a.c.c.C.[.[.[/].[dispatcherServlet]    : Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed; nested exception is 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 '' at line 1
### The error may exist in file [E:\smallTools\idea\code\spring\springboot-new-2021_11_09\springboot-new-mybatis\target\classes\mybatis\mapper\BookMapper.xml]
### The error may involve com.feng.mybatis.mapper.BookMapper.getBookById-Inline
### The error occurred while setting parameters
### SQL: select * from book where id={#id}
### 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 '' 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 '' at line 1] with root 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 '' at line 1
	at com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:120) ~[mysql-connector-java-8.0.27.jar:8.0.27]

2. Mapper.xml file content

<select id="getBookById" parameterType="com.feng.mybatis.bean.Book">
        select * from book where id={#id}
</select>

3. Error reason: the SQL statement is written incorrectly. It should be where id = #{id}

<select id="getBookById" parameterType="com.feng.mybatis.bean.Book">
        select * from book where id=#{id}
</select>

[Solved] Mybatis integrates PageHelper and uses sqlserver paging error

The environment uses mybatis plus, the paging plug-in: PageHelper 5.2.0, and the database uses sqlserver2012 or above

In fact, the paging plug-in is ultimately handled by the mybatis interceptor, so it is equivalent to the mybatis environment.

Using paging

 PageHelper.startPage(1,10); // Pagination
  orderMapper.list(); // Follow the execution

Then an error will be reported

SQL: SELECT  id,product_name,xxxx,xxxxx  FROM product_xxxx  OFFSET ?ROWS FETCH NEXT ?ROWS ONLY
### Cause: com.microsoft.sqlserver.jdbc.SQLServerException: “@P0”There is a grammatical error nearby.
; uncategorized SQLException; SQL state [S0001]; error code [102]; There is a syntax error near "@P0". ; nested exception is com.microsoft.sqlserver.jdbc.SQLServerException: There is a syntax error near "@P0".

Finally, after checking, it is found that the paging syntax offset and fetch used by PageHelper are sqlserver’s support for sorting.

Therefore, if you want to use this plug-in to page, you need to add sorting.

PageHelper.startPage(1,10,"xxxx sorted table field name, not attribute name");
orderMapper.list(); // Follow the execution

Or use the default sort field

PageHelper.startPage(1,10,"CURRENT_TIMESTAMP");
orderMapper.list(); //Follow up

How to Solve idea com.baomidou Error

Completely solve the error reported by com.baomidou in idea

Add in pom.xml:

		<dependency>
			<groupId>com.baomidou</groupId>
			<artifactId>mybatis-plus-boot-starter</artifactId>
			<version>3.4.2<ersion>
		</dependency>

Clear all mybatis and mybatis plus related configurations in the YML file and add:

mybatis-plus:
  type-aliases-package: com.peanut.entity
  mapper-locations: classpath:mappers

Select the item and right-click Maven -> Reload project
as shown in the figure, com.baidu no longer turns red:

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

In a connection query, there is no problem with the query in the MySQL query tool. It is pasted into the mapper.xml file in the project, but the runtime reports mybatisplusexception: error: method querytotal execution error of SQL:

 SELECT
        ANY_VALUE(e.id)  AS "id",
        ANY_VALUE(e.project_no) AS "projectNo",
        ANY_VALUE(sampleIn.sample_id)  AS "fieldNumber",
        ANY_VALUE(e.subject_no) AS "laboratoryNumber",
        ANY_VALUE(e.type) AS "type",
        ANY_VALUE(d.sampling_location) AS "location",
        ANY_VALUE(sampleIn.in_quantity)   AS "inquatity",
        ANY_VALUE(sampleIn.create_date)  AS "createDate",
        ANY_VALUE(sys_user.name)  AS "createUser",          
        ANY_VALUE(s. project_no)  AS "projectNoName",
        ANY_VALUE(s.subject_name)   AS "subjectName",
        ANY_VALUE(sd.name) AS "saveCondition",
        ANY_VALUE(sa.location) AS "location",
        ANY_VALUE(DATE_FORMAT(sa.shelf_life,'%Y-%m-%d'))AS"shelfLife"
        FROM labcode e
        LEFT JOIN labprojects s ON e.project_no = s.id
        LEFT JOIN labprojectplan n ON s.id = n.project_no        
        LEFT JOIN labprojectplan_field d ON n.id = d. lab_project_plan_id  AND e.serial_number = d.serial_number AND e.letter_code =d.letter_code    
        LEFT JOIN labsubjectsample sa ON e.id =sa.laboratory_number
        LEFT JOIN laboratorysamplein sampleIn ON sampleIn.code_id = e.id
        LEFT JOIN sys_user ON sampleIn.create_user=sys_user.user_id
        LEFT JOIN sys_dict sd ON sd.code = sa.save_condition
        WHERE 1 = 1
        AND s.is_delete = 0
        AND e.is_delete=0
        AND e.subject_no LIKE '%B'
        AND e.type=3
       
        GROUP BY e.id     
        ORDER BY ANY_VALUE(sampleIn.create_date) DESC

After going online to search, it was confirmed that it was the problem of where conditions, so they were eliminated one by one, and finally locked on several is_delete fields, which are of char type in the database. The database query tool supports direct use of 0 and 1 to query, and MyBatis needs to contact the database Keep consistent in the middle, and finally, change the where part to

WHERE 1 = 1
        AND s.is_delete = '0'
        AND e.is_delete='0'
        AND e.subject_no LIKE '%B'
        AND e.type='3'

Problem-solving

This exception is basically the problem of where conditions, and type mismatch is only one of them. Other problems include condition null value, keyword conflict with framework and so on. As long as you are careful when writing code, think more about avoiding exceptions, be patient when problems occur, check them one by one, and be good at summarizing after problems are solved, you can accumulate experience and grow gradually on the way of writing code.

Error attempting to get column ‘xxxxx’ from result set — after Lombok is annotated with builder, mybatis cannot recognize the correct type of field

Pit stepping record – after Lombok is annotated with builder, mybatis cannot recognize the correct type of field

After adding Lombok to the entity class, sometimes we will use @ builder annotation, so we don’t need to write too many set methods to define the attribute content, which makes our code more elegant. Once the @ builder annotation is added to the entity class, it will cause problems in our mybatis mapping database fields

The questions are as follows

org.springframework.dao.DataIntegrityViolationException: Error attempting to get column 'username' from result set.  Cause: java.sql.SQLDataException: Cannot determine value type from string 'zhangsa'
; Cannot determine value type from string 'zhangsa'; nested exception is java.sql.SQLDataException: Cannot determine value type from string 'zhangsa'

note: when using @ builder annotation, a full parameter structure will be generated, resulting in the disappearance of no parameter structure

terms of settlement

    we can directly remove @ builder annotation, and there will be no problem for mybatis to query the database. We can generate parametric and nonparametric constructs in entity classes (you can add them manually or add annotations @ allargsconstructor , @ noargsconstructor )

    if it is still abnormal, you should check whether your entity class and database type mapping do not correspond

    Hold fireworks to seek life, poetic to seek love

[Solved] Mybatis-Plus Error: Invalid bound statement (not found)

Mybatis plus reports an error: invalid bound statement (not found)

After integrating mybatis plus in the spring boot project, it is found that the user-defined query method will report an error: “invalid bound statement (not found): * * *.” your method “, which means that your user-defined method cannot be found in the XML file. Various methods are tried and the problem is finally solved. This problem exists in the following situations:

1. Mapper file and XML file cannot correspond

1. Check whether mapper file and XML file names are consistent

UserMapper and UserMapper.xml

2. Check whether the attribute configuration of namespace in the XML file corresponds to the corresponding mapper file

<mapper namespace="com.*.*.mapper.UserMapper">

3. Check whether the method binding ID in the XML file is consistent

Mapper:
    List<User> getUserList();
xml:
    <select id="getUserList" resultType="com.*.*.entity.User">
        SELECT * FROM user
    </select>

2. The XML file is placed in the resources directory at different levels and is not packaged into the target

By default, all will be packaged. Check whether the property of not packaging is configured in the POM file, and modify it

Note: this configuration is to package the resources directory and check the differences

	<build>
        <!-- Pack the files in the resources directory -->
        <resources>
            <resource>
                <directory>src/main/resources</directory>
                <includes>
                    <include>**/*.*</include>
                </includes>
            </resource>
        </resources>
     </build>

(focus on configuration, which is also my problem) third, the XML file is placed in the resources directory at different levels and has been packaged into the target, but the corresponding method cannot be found

It is thought that after packaging, you can match according to the name. Finally, it is found that even if the XML file is packaged, it still belongs to a different level from mapper, so check whether the mybatis plus configuration matching the location of the XML file is missing

mybatis-plus.mapper-locations = classpath:mapping/*.xml
# The "mapping" in this configuration corresponds to the name of the directory where your xml is located