Tag Archives: MyBatis

mybatisThere is no getter for property named ‘***’ in ‘class ***’

There is no getter for property named ‘* * *’ in ‘class * * *’

Check to see if the mapping fields in XML are misspelled and case sensitive

Sometimes when the original code is generated by the plug-in, there is no problem. A field is added. When it is not generated automatically

I like to add some manually. At this time, I often make spelling mistakes. Pay attention to the case between hump words

How to Solve Mybatis Error: java.lang.UnsupportedOperationException

The error information is as follows:

Caused by: org.apache.ibatis.exceptions.PersistenceException:
### Error querying database. Cause: java.lang.UnsupportedOperationException

Exception root: resulttype returns the element type in the collection, not the collection itself

The code is as follows:

    <!--Check detailed order information-->
    <resultMap id="orderDetailMap" type="com.alibaba.fastjson.JSONArray">
        <result column="order_code" property="orderCode"/>
        <result column="state" property="state"/>
        <result column="address" property="address"/>
        <result column="received_telephone" property="receivedTelephone"/>
        <result column="send_linkman" property="sendLinkman"/>
        <result column="send_telephone" property="sendTelephone"/>
        <result column="delivery_time" property="deliveryTime"/>
        <result column="delivery_time_quantum" property="deliveryTimeQuantum"/>
        <result column="greeting_card" property="greetingCard"/>
        <result column="show_pay_name" property="showPayName"/>
        <result column="pay_time" property="payTime"/>
        <result column="order_total_amount" property="orderTotalAmount"/>
        <result column="is_invoice" property="isInvoice"/>
        <result column="settled_amount" property="settledAmount"/>
        <result column="delivery_money" property="deliveryMoney"/>
        <collection property="goods" column="order_code"  ofType="com.alibaba.fastjson.JSONObject" javaType="List" select="findOrderChildDetail">
            <result column="item_sku_code" property="itemSkuCode"/>
            <result column="sku_title" property="skuTitle"/>
            <result column="sale_price" property="salePrice"/>
            <result column="buy_cnt" property="buyCnt"/>
            <result column="totalPrice" property="totalPrice"/>
        </collection>
    </resultMap>
    <select id="queryOrderDetail" parameterType="Map" resultMap="orderDetailMap">
        SELECT
            order_code,
            state,
            received_linkman,
            CONCAT(received_address_area,received_address_desc) AS 'address',
            received_telephone,
            send_linkman,
            send_telephone,
            delivery_time,
            delivery_time_quantum,
            greeting_card,
            show_pay_name,
            pay_time,
            order_total_amount,
            is_invoice,
            settled_amount,
            delivery_money
        FROM
            order_info
        WHERE
            account_code = #{accountCode}
        AND
            order_code = #{orderCode}
        LIMIT 1
    </select>

    <!--Check detailed order information-->
    <select id="findOrderChildDetail" parameterType="String" resultType="com.alibaba.fastjson.JSONObject">
        SELECT
            item_sku_code ,
            sku_title ,
            sale_price ,
            buy_cnt ,
            sale_price *  buy_cnt AS totalPrice
        FROM
            order_detail
        WHERE
            order_code = #{orderCode}
    </select>
    

Error reason:

    <resultMap id="orderDetailMap" type="com.alibaba.fastjson.JSONArray">
    The JSONArray type in the error, modified to
    <resultMap id="orderDetailMap" type="com.alibaba.fastjson.JSONObject">

Note: the type here is the type used in the current development. If the object is used, check whether the type in the resultmap is a list or an object. If it is an associated subquery, modify it to an object

[Solved] When mybatis query result type is char: cause: Java. Lang. stringindexoutofboundsexception: string index out of range: 0

When mybatis was used to process a field of type char, there was an error:

org.mybatis.spring.MyBatisSystemException: nested exception is org.apache.ibatis.executor.result.ResultMapException: Error attempting to get column '字段名' from result set.  Cause: java.lang.StringIndexOutOfBoundsException: String index out of range: 0
	at org.mybatis.spring.MyBatisExceptionTranslator.translateExceptionIfPossible(MyBatisExceptionTranslator.java:79)
	at org.mybatis.spring.SqlSessionTemplate$SqlSessionInterceptor.invoke(SqlSessionTemplate.java:447)
	at com.sun.proxy.$Proxy24.selectList(Unknown Source)
	at org.mybatis.spring.SqlSessionTemplate.selectList(SqlSessionTemplate.java:231)
	at org.apache.ibatis.binding.MapperMethod.executeForMany(MapperMethod.java:122)
	at org.apache.ibatis.binding.MapperMethod.execute(MapperMethod.java:64)
	at org.apache.ibatis.binding.MapperProxy.invoke(MapperProxy.java:53)
	at com.sun.proxy.$Proxy67.selectOldPhoneInfo(Unknown Source)
	at com.hibroad.compatibleweb.service.impl.FallDownServiceImpl.phonePup(FallDownServiceImpl.java:210)
	at com.hibroad.compatibleweb.service.impl.FallDownServiceImpl$$FastClassByCGLIB$$a692b24b.invoke(<generated>)
	at org.springframework.cglib.proxy.MethodProxy.invoke(MethodProxy.java:204)
	at org.springframework.aop.framework.CglibAopProxy$CglibMethodInvocation.invokeJoinpoint(CglibAopProxy.java:713)
	at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:157)
	at org.springframework.transaction.interceptor.TransactionInterceptor$1.proceedWithInvocation(TransactionInterceptor.java:98)
	at org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:262)
	at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:95)
	at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
	at org.springframework.aop.interceptor.ExposeInvocationInterceptor.invoke(ExposeInvocationInterceptor.java:92)
	at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
	at org.springframework.aop.framework.CglibAopProxy$DynamicAdvisedInterceptor.intercept(CglibAopProxy.java:646)
	at com.hibroad.compatibleweb.service.impl.FallDownServiceImpl$$EnhancerByCGLIB$$28859386.phonePup(<generated>)
	at com.hibroad.compatibleweb.handler.FallDownHandler.doHandler(FallDownHandler.java:82)
	at com.hibroad.compatibleweb.handler.FamilyApiHandler_Web.mappingClass(FamilyApiHandler_Web.java:238)
	at com.hibroad.compatibleweb.handler.FamilyApiHandler_Web.service(FamilyApiHandler_Web.java:165)
	at com.hibroad.compatibleweb.handler.FamilyApiHandler_Web.service_get(FamilyApiHandler_Web.java:57)
	at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
	at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
	at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
	at java.lang.reflect.Method.invoke(Method.java:606)
	at org.springframework.web.method.support.InvocableHandlerMethod.invoke(InvocableHandlerMethod.java:214)
	at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:132)
	at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:104)
	at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandleMethod(RequestMappingHandlerAdapter.java:748)
	at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:689)
	at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:83)
	at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:945)
	at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:876)
	at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:931)
	at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:822)
	at javax.servlet.http.HttpServlet.service(HttpServlet.java:624)
	at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:807)
	at javax.servlet.http.HttpServlet.service(HttpServlet.java:731)
	at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:303)
	at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
	at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
	at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:241)
	at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
	at com.hibroad.util.CorsFilter.doFilter(CorsFilter.java:24)
	at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:241)
	at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
	at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:88)
	at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:108)
	at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:241)
	at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
	at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:219)
	at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:110)
	at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:498)
	at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:169)
	at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:103)
	at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:1025)
	at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:116)
	at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:445)
	at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1115)
	at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:637)
	at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:316)
	at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
	at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
	at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
	at java.lang.Thread.run(Thread.java:745)
Caused by: org.apache.ibatis.executor.result.ResultMapException: Error attempting to get column '字段名' from result set.  Cause: java.lang.StringIndexOutOfBoundsException: String index out of range: 0
	at org.apache.ibatis.type.BaseTypeHandler.getResult(BaseTypeHandler.java:68)
	at org.apache.ibatis.executor.resultset.DefaultResultSetHandler.applyAutomaticMappings(DefaultResultSetHandler.java:471)
	at org.apache.ibatis.executor.resultset.DefaultResultSetHandler.getRowValue(DefaultResultSetHandler.java:364)
	at org.apache.ibatis.executor.resultset.DefaultResultSetHandler.handleRowValuesForSimpleResultMap(DefaultResultSetHandler.java:318)
	at org.apache.ibatis.executor.resultset.DefaultResultSetHandler.handleRowValues(DefaultResultSetHandler.java:293)
	at org.apache.ibatis.executor.resultset.DefaultResultSetHandler.handleResultSet(DefaultResultSetHandler.java:266)
	at org.apache.ibatis.executor.resultset.DefaultResultSetHandler.handleResultSets(DefaultResultSetHandler.java:180)
	at org.apache.ibatis.executor.statement.PreparedStatementHandler.query(PreparedStatementHandler.java:63)
	at org.apache.ibatis.executor.statement.RoutingStatementHandler.query(RoutingStatementHandler.java:78)
	at org.apache.ibatis.executor.SimpleExecutor.doQuery(SimpleExecutor.java:62)
	at org.apache.ibatis.executor.BaseExecutor.queryFromDatabase(BaseExecutor.java:303)
	at org.apache.ibatis.executor.BaseExecutor.query(BaseExecutor.java:154)
	at org.apache.ibatis.executor.CachingExecutor.query(CachingExecutor.java:102)
	at com.github.pagehelper.PageInterceptor.intercept(PageInterceptor.java:141)
	at org.apache.ibatis.plugin.Plugin.invoke(Plugin.java:61)
	at com.sun.proxy.$Proxy136.query(Unknown Source)
	at org.apache.ibatis.session.defaults.DefaultSqlSession.selectList(DefaultSqlSession.java:120)
	at org.apache.ibatis.session.defaults.DefaultSqlSession.selectList(DefaultSqlSession.java:113)
	at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
	at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
	at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
	at java.lang.reflect.Method.invoke(Method.java:606)
	at org.mybatis.spring.SqlSessionTemplate$SqlSessionInterceptor.invoke(SqlSessionTemplate.java:434)
	... 67 more
Caused by: java.lang.StringIndexOutOfBoundsException: String index out of range: 0
	at java.lang.String.charAt(String.java:658)
	at org.apache.ibatis.type.CharacterTypeHandler.getNullableResult(CharacterTypeHandler.java:37)
	at org.apache.ibatis.type.CharacterTypeHandler.getNullableResult(CharacterTypeHandler.java:26)
	at org.apache.ibatis.type.BaseTypeHandler.getResult(BaseTypeHandler.java:66)

This field is of char type, and everything else is good. For this error report, the problem lies in mybatis processing char. Let’s see how mybatis processes char, and attach the source code of mybatis processing

/**
 *    Copyright 2009-2015 the original author or authors.
 *
 *    Licensed under the Apache License, Version 2.0 (the "License");
 *    you may not use this file except in compliance with the License.
 *    You may obtain a copy of the License at
 *
 *       http://www.apache.org/licenses/LICENSE-2.0
 *
 *    Unless required by applicable law or agreed to in writing, software
 *    distributed under the License is distributed on an "AS IS" BASIS,
 *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *    See the License for the specific language governing permissions and
 *    limitations under the License.
 */
package org.apache.ibatis.type;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

/**
 * @author Clinton Begin
 */
public class CharacterTypeHandler extends BaseTypeHandler<Character> {

  @Override
  public void setNonNullParameter(PreparedStatement ps, int i, Character parameter, JdbcType jdbcType) throws SQLException {
    ps.setString(i, parameter.toString());
  }

  @Override
  public Character getNullableResult(ResultSet rs, String columnName) throws SQLException {
    String columnValue = rs.getString(columnName);
    if (columnValue != null) {
      return columnValue.charAt(0);
    } else {
      return null;
    }
  }

  @Override
  public Character getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
    String columnValue = rs.getString(columnIndex);
    if (columnValue != null) {
      return columnValue.charAt(0);
    } else {
      return null;
    }
  }

  @Override
  public Character getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
    String columnValue = cs.getString(columnIndex);
    if (columnValue != null) {
      return columnValue.charAt(0);
    } else {
      return null;
    }
  }
}

If you only judge whether it is null, you will directly charat (0). If the columnvalue is empty, you will directly get an exception. How to rewrite a typehandle <Character>

package com.lpc.config;

import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

public class MyCharacterTypeHandler extends BaseTypeHandler<Character> {
    @Override
    public void setNonNullParameter(PreparedStatement ps, int i, Character parameter, JdbcType jdbcType)
            throws SQLException {
        ps.setString(i, parameter.toString());
    }

    @Override
    public Character getNullableResult(ResultSet rs, String columnName) throws SQLException {
        String columnValue = rs.getString(columnName);
        if (columnValue != null && !columnValue.isEmpty() ) {
            return columnValue.charAt(0);
        } else {
            return null;
        }
    }

    @Override
    public Character getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
        String columnValue = rs.getString(columnIndex);
        if (columnValue != null && !columnValue.isEmpty() ) {
            return columnValue.charAt(0);
        } else {
            return null;
        }
    }

    @Override
    public Character getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
        String columnValue = cs.getString(columnIndex);
        if (columnValue != null && !columnValue.isEmpty() ) {
            return columnValue.charAt(0);
        } else {
            return null;
        }
    }
}

Then write in mybatis-config.xml:

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
    <typeHandlers>
        <typeHandler javaType="java.lang.Character" jdbcType="CHAR" handler="com.lpc.config.MyCharacterTypeHandler" />
    </typeHandlers>
</configuration>

Add mybatis config configuration in application.properties

mybatis.config-location=classpath:mybatis-config.xml

This field in the mapper.xml file needs to be modified as follows:

<result column="orderNum" property="orderNum" jdbcType="CHAR" typeHandler="com.lpc.config.MyCharacterTypeHandler"/>

All right, restart it

How to Solve MyBatisPlus Error: Failed to process, please exclude the tableName or statementId

Error reporting details:
error querying database. Cause: com.baomidou.mybatisplus.core.exceptions.mybatisplus exception: failed to process, please exclude the tablename or statementid. Error SQL: XXXXXXXX 

Error reason:
the user-defined SQL is used, which may contain special functions or complex syntax, so it is not supported by jsqlparser (the fields such as tenant ID cannot be added), so the jsqlparserexception is thrown.

The exception is caught by mybatisplus and is encapsulated as mybatisplus exception and then thrown.

Source code: com.baomidou.mybatisplus.core.parser.abstractjsqlparser

solution:
failed to process, please exclude the tablename or statementid
translation is: processing failed, please exclude the table name or statement ID
the P.S. prompt is very specific, but it’s easy to be confused, because the unfamiliar people don’t know that the tenant ID has a problem

Method 1: exclude the table name
when configuring tenanthandler of mybatisplus, filter out the table in dotablefilter method (that is, do not process the tenant ID field of the table).

Method 2: exclude the statement
mark @ sqlparser (filter = true) on the interface of custom SQL

    @SqlParser(filter = true)
    @Select("SQL")
    void selectDemo();

The official explanation for this note is:

Tenant annotation supports method and mapper interface. The default value is false
true means to filter SQL parsing, that is, it will not enter the isqlparser parsing chain
if it is false, it will enter the parsing chain and append a tenant_ ID and so on.

Org.yaml.snakeyaml.parser.ParserException: while parsing a block mapping

org.yaml.snakeyaml.parser.ParserException: while parsing a block mapping

Reason: yml file format error, this file requires strict requirements format

If the nodes are not aligned, align the Mybatis nodes with the Spring nodes, here is the yml configuration file for SpringBoot 2.0 + Mybatis + Mysql

server:
port: 8080
spring:
datasource:
name: daducha
type: com.alibaba.druid.pool.DruidDataSource
druid:
url: jdbc:mysql://127.0.0.1:3306/daducha
username: root
password: root
maxActive: 20
initialSize: 1
maxWait: 60000
minIdle: 1
timeBetweenEvictionRunsMillis: 60000
minEvictableIdleTimeMillis: 300000
testWhileIdle: true
testOnBorrow: false
testOnReturn: false
poolPreparedStatements: true
maxOpenPreparedStatements: 20
driver-class-name: com.mysql.jdbc.Driver
mybatis:
mapper-locations: classpath:mapping/*.xml
type-aliases-package: com.wuji.entity.po

Mybatis where 1 = 1 and Tags

When splicing query statements in mybatis, it occasionally appears that there may be no value of a field after where, which leads to all conditions being invalid and makes where meaningless. However, it is also possible that these conditions may exist. The most common way to solve this problem is to:

Add 1 = 1 after where

<select id="findActiveBlogLike" resultType="Blog"&>
 SELECT * FROM BLOG
 WHERE 1=1
 <if test="state != null"&>
 and state = #{state}
 </if&> 
</select&>

But this method has one of the biggest disadvantages, which is that it leads to the invalidation of the index on the data table, if there is an index. And it’s a rubbish condition

The where element knows to insert a “where” clause only if more than one if condition has a value. Moreover, if the final content starts with “and” or “, the where element also knows how to remove them.

If the where element doesn’t play according to the normal routine, we can still customize the function we want by customizing the trim element. For example, a custom trim element equivalent to the where element is:

<trimprefix=”WHERE”prefixOverrides=”AND|OR”&>…</trim&>