Tag Archives: MyBatis

Cannot change the executortype when there is an existing transaction [How to Solve]

Error content

org.springframework.dao.TransientDataAccessResourceException: Cannot change the ExecutorType when there is an existing transaction
	at org.mybatis.spring.SqlSessionUtils.sessionHolder(SqlSessionUtils.java:157)
	at org.mybatis.spring.SqlSessionUtils.getSqlSession(SqlSessionUtils.java:91)
	at com.baomidou.mybatisplus.core.toolkit.sql.SqlHelper.sqlSessionBatch(SqlHelper.java:55)
	at com.baomidou.mybatisplus.extension.service.impl.ServiceImpl.sqlSessionBatch(ServiceImpl.java:75)
	at com.baomidou.mybatisplus.extension.service.impl.ServiceImpl.saveOrUpdateBatch(ServiceImpl.java:172)
	at com.baomidou.mybatisplus.extension.service.impl.ServiceImpl.saveOrUpdateBatch(ServiceImpl.java:163)
	at com.baomidou.mybatisplus.extension.service.impl.ServiceImpl$$FastClassBySpringCGLIB$$76535273.invoke(<generated>)

Actual use method (error example)

    @Override
    @Transactional(rollbackFor = Exception.class)
    public BaseResp saveOrUpdate(TestPlanParam param) {
        //add, update
============================================================
Omit the codes
============================================================
        //1.New, updated firefighting plans (now with additional master tables)
        this.saveOrUpdate(planEntity);
        Integer testPlanId = planEntity.getId();
        List<PlanTestTeamEntity> teamEntities=new ArrayList<>();
        List<PlanTestResourceEntity> resourceEntities=new ArrayList<>();

        //2.Add update firefighting team (bulk add schedule, need to hook up the id of the main table)
        teams.forEach(team->{
            PlanTestTeamEntity teamEntity=new PlanTestTeamEntity();
            BeanUtil.copyProperties(team,teamEntity);
            teamEntity.setFireFightTestPlanId(testPlanId);
            //planTestTeamService.saveOrUpdate(teamEntity); Solution, using an article-by-article update
            teamEntities.add(teamEntity);
        });
        //3.Add update of fire fighting supplies (bulk add schedule, need to hook up the id of the main table)
        resources.forEach(res->{
            PlanTestResourceEntity resourceEntity=new PlanTestResourceEntity();
            BeanUtil.copyProperties(res,resourceEntity);
            resourceEntity.setFireFightTestPlanId(testPlanId);
            //planTestResourceService.saveOrUpdate(resourceEntity); Solution, using an article-by-article update
            resourceEntities.add(resourceEntity);
        });
        planTestTeamService.saveOrUpdateBatch(teamEntities);
        planTestResourceService.saveOrUpdateBatch(resourceEntities);

        return BaseResp.success();
    }

Error reporting reason

Executortype cannot be changed when a transaction exists

Solution:

When batch updating, first check out all the updated objects, and then update them circularly

How to Solve Mybatis Chinese parameter error

A simple query, if there is Chinese in the parameters. As follows:

<select id="xxxx" resultType="hashmap">
    select * from talbe_a a where  a.kpeople = ${name} </select>

Error reporting:

org.apache.ibatis.exceptions.PersistenceException: 
### Error querying database.  Cause: java.sql.SQLSyntaxErrorException: ORA-00904: "Xiao Yaxuan": Identifier is invalid
...

Caused by: java.sql.SQLSyntaxErrorException: ORA-00904: "Xiao Yaxuan": Identifier is invalid
....

mybatis sql log

18:06:36,192 DEBUG JdbcTransaction:47 - Openning JDBC Connection
18:06:36,830 DEBUG PooledDataSource:47 - Created connection 1459361227.
18:06:36,843 DEBUG queryrealactormediatop:47 - ooo Using Connection [[email protected]]
18:06:36,843 DEBUG queryrealactormediatop:47 - ==>  Preparing: select * from table_a a where v1.kpeople = 萧亚轩 
18:06:36,961 DEBUG queryrealactormediatop:47 - ==> Parameters:

Note: “Xiao Yaxuan” has no single quotation marks around it, not “?” There is no value in the parameter list

 

The modification is actually very simple:

V1: change $to#

<select id="xxxx" resultType="hashmap">
    select * from talbe_a a where  a.kpeople = #{name} </select>

V2: Add ” single quotation mark

<select id="xxxx" resultType="hashmap">
    select * from talbe_a a where  a.kpeople = ‘${name}‘ </select>

#It’s just a string

$is not necessarily a string or other type

Error in mybatis mapping .XML File [How to Solve]

In the mybatis framework, the test is carried out in the Dao layer, and the console displays an error: the attribute “resulttype” must be declared for the element type “delete”

The SQL statement of the corresponding. XML file is:

The detailed error messages on the console are:

1. Attribute ‘resulttype’ must be declared for element type ‘Delete’

2.

Check the information on the Internet and say that every_In the sqlmapper.xml file, try to match each SQL statement to a namespace (the complete Java class of each Dao layer); As a result, the attempt was unsuccessful

Finally, simply_Delete the resulttype in the sqlmapper.xml file, and the test is successful; Delete as shown:

Successful test chart:

1 is to get the spring container

2 is the number of deleted data in the test (the number of deleted data in the first test is 1), and this result is the second test

 

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

Mybatis error reporting: there are many reasons for invalid bound statement (not found), but just like the error reporting prompt, the SQL statement in XML cannot be found. There are three types of error reporting:

The first: syntax error

Java Dao layer interface

public void delete(@Param("id")String id);

Mapper.xml file corresponding to Java

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="xxx.xxx.xxx.Mapper">
    <!-- Delete Datas -->
    <delete id="delete" parameterType="java.lang.String">
        DELETE FROM xxx WHERE id=#{id}
    </delete>
</mapper>

Check:

Is the method name (delete) in the interface consistent with id = "delete" in the XML file

Is the path in namespace = "XXX. XXX. XXX. Mapper" in the XML file consistent with the path in the interface file

Whether the parametertype type and resulttype types are accurate; Resultmap is different from resulttype

 

Second: compilation error

Navigate to the project path: under the error path in target \ classes \ , find out whether the corresponding XML file exists

(1) . if there is no corresponding XML file, you need to add the following code to pom.xml:

<build>
    <resources>
         <resource>
             <directory>src/main/java</directory>
             <excludes>
                 <exclude>**/*.java</exclude>
             </excludes>
         </resource>
         <resource>
             <directory>src/main/resources</directory>
             <includes>
                 <include>**/*.*</include>
             </includes>
        </resource>
    </resources>
</build>

Delete the files in the classes folder, recompile, and the corresponding XML file appears

(2) If there is an XML file, open the XML file and check whether the error part is consistent with the source file. If it is inconsistent,

first clear the files in the classes folder and execute the command: MVN clean clean the content and recompile it

 

Third: configuration error

There was a problem with the configuration path when specifying the scan package in the configuration file

for example, : the package name of the “basepackage” attribute in the spring configuration file must be specific to the package where the interface is located, and do not write the package of the parent level or higher, otherwise problems may occur; Cn. Dao and CN. * may also cause errors; During annotation scanning, packages may not be scanned

[Solved] Mybatis batch insert error: The incoming Table Format Data Stream (TDS) Remote Procedure Call…

Error message:

The incoming Table Format Data Stream (TDS) Remote Procedure Call (RPC) protocol stream is incorrect. Too many parameters were provided in this RPC request. The maximum should be 2100

Error analysis:

Due to too many SQL statement parameters spliced by mybatis

Solution:

Batch processing without mybatis

① Configuration file   applicationContext-mybatis.xml

  <!-- Solving mybatis batch insert -->
    <bean class="org.mybatis.spring.SqlSessionTemplate" id="sqlSession">
        <constructor-arg name="sqlSessionFactory" ref="sqlSessionFactory" />
        <constructor-arg name="executorType" value="BATCH" />
    </bean>

②service import

    @Autowired
	private SqlSessionTemplate sst;

③ The self encapsulated method was used in the service for batch insert

	public Boolean insert(List<PDA_JWL_INTERFACE_H> inList,String zyh){
		// Get a new session with mode BATCH and auto-commit set to false
		// If auto-commit is set to true, it will not be possible to control the number of commits and will instead be submitted uniformly at the end, which may lead to a memory overflow
		SqlSession session = sst.getSqlSessionFactory().openSession(ExecutorType.BATCH,false);
		moMapper= session.getMapper(MOMapper.class);
		Map<String,Object> cc = new HashMap<>();
		
		try {
			for (PDA_JWL_INTERFACE_H in : inList) {
				moMapper.insert(in);
			}
			cc.put("zyh", zyh);
			moMapper.call(cc);
			session.commit();
			//Clearing the cache to prevent overflow
			session.clearCache();
			return true;
		} catch (Exception e) {
			session.rollback();
			return false;
		} finally {
			session.close();
		}
	}

 

End 9315;

	/**
	 * submit
	 */
	@RequestMapping(value="/tj", method = RequestMethod.POST,produces="application/json;charset=utf-8")
	@ResponseBody
	public Map<String,Object> tj(@RequestBody List<PDA_JWL_INTERFACE_H> tList,HttpServletRequest req){
		
		//Encapsulating the return value of a map
		Map<String,Object> m = new HashMap<>();
		
		
		//Decryption Certification
		String token = req.getParameter("token");
		String tk = MD5Utils.encode(CREKEY);
		System.out.println(tk);
		if(!token.equals(tk)){
			m.put("flag",Code.FLAG1.getIndex());
			m.put("erroCode", Code.ERROR1.getIndex());
			m.put("content", "");
			return m;
		}
		//Store the data to be placed in the intermediate table
		List<PDA_JWL_INTERFACE_H> inList = new LinkedList<>();
		
		// Job number, produced with UUID, unique number, distinguishes job type
		
		//Long t1 = System.currentTimeMillis();
		
		String zyh = UUID.randomUUID().toString();
		try {
			for (PDA_JWL_INTERFACE_H t : tList) {
				
				PDA_JWL_INTERFACE_H in = new PDA_JWL_INTERFACE_H();
				
				//Job number
				in.setZYH(zyh);
				// Order maker number: default current login ID (required, not shown)
				in.setZDRH(t.getZDRH());
				//Things type: default "Purchase Inbound" (required, not shown)
				in.setSWLX(t.getSWLX());
				//Supplier number: required, not shown
				in.setGYSH(t.getGYSH());
				//Supplier: The company number in the view is the same as the company number of this job
				in.setGYS(t.getGYS());
				//Company number: required, not shown
				in.setGSH(t.getGSH());
				//Warehouse number: required, not shown
				in.setCKH(t.getCKH());
				//Warehouse: the operator number in the view is the same as the current login ID
				in.setCK(t.getCK());
				//new warehouse number
				in.setXCKH(t.getXCKH());
				//new warehouse
				in.setXCK(t.getXCK());
				//claimers
				in.setLYR(t.getLYR());
				//new warehouse position number
				in.setXKWH(t.getXKWH());
				//new storage position
				in.setXKW(t.getXKW());
				//Purchase Type:Required
				in.setCGLX(t.getCGLX());
				//Purchaser: required
				in.setCGR(t.getCGR());
				//Stockroom number: required, not displayed
				in.setKWH(t.getKWH());
				// Warehouse location: the warehouse number in the view is the same as the warehouse number of this job
				in.setKW( t.getKW());
				//line number: automatically generate a non-repeating serial number for this job. app-side pass over
				in.setHH( t.getHH());
				//Item number: return the corresponding value directly after inputting the item number, which needs to be matched exactly. The company number and item type in the view are the same as the company number and purchase type of this job. (required)
				in.setWPH(t.getWPH());
				//Item name: display, not editable
				in.setWPMC(t.getWPMC());
				//spec: show, not editable
				in.setGG(t.getGG());
				//units: display, non-editable
				in.setDW(t.getDW());
				//production lot number: popup selection after entering keyword.
				in.setSCPH(t.getSCPH());
				//Grade: default First class (required)
				in.setDJI(t.getDJI());
				//Quantity: required
				in.setSL(t.getSL());
				//Number of pieces: Not required
				in.setJS(t.getJS());
				//Unit price: non-required, if it is empty or 0, only prompted, no control over subsequent operations.
				in.setDJ(t.getDJ());
				//amount: unit price*quantity, not editable.
				in.setJE(t.getJE());
				//Currency code: default RMB (required)
				in.setBBM(t.getBBM());
				//Tax rate: default 0.17 (required)
				in.setSLV(t.getSLV());
				// First level sector
				in.setYJBM(t.getYJBM());
				//Inventory source
				in.setPDLY(t.getPDLY());
				//lot number
				in.setPH(t.getPH());
				
				inList.add(in);
				
			}
			Boolean flag = moService.insert(inList,zyh); if(!flag){ int i = 1/0; }else{ /*Long t2 = System.currentTimeMillis(); System.out.println(t2-t1);*/ }
			
		} catch (Exception e) {
			e.printStackTrace();
			m.put("flag",Code.FLAG1.getIndex());
			m.put("erroCode", Code.ERROR2.getIndex());
			m.put("content", "");
			return m;
		}
		m.put("flag",Code.FLAG.getIndex());
		m.put("erroCode", "");
		m.put("content", "");
		return m;
	}
	

 

⑤ Xxmapper.xml in the mapping file

	<!-- submit -->
	<insert id="insert" parameterType="PDA_JWL_INTERFACE_H" >
	  insert into PDA_JWL_INTERFACE_H ( 
	  
	  ZYH,ZDRH,SWLX,SWRQ,GYSH,GYS,GSH,CKH,CK,XCKH,
	  XCK,LYR,XKWH,XKW,CGLX,CGR,KWH,KW,HH,WPH,
	  WPMC,GG,DW,SCPH,DJI,SL,JS,DJ,JE,BBM,
	  SLV,YJBM,PDLY,PH
	  
	  ) values
	  
	  (#{ZYH}, #{ZDRH}, #{SWLX},getdate(), #{GYSH},
 	   #{GYS}, #{GSH},#{CKH}, #{CK},#{XCKH}, 
 	   #{XCK},#{LYR},#{XKWH},#{XKW},#{CGLX}, 
	   #{CGR}, #{KWH},#{KW}, #{HH}, #{WPH},
	   #{WPMC}, #{GG},#{DW}, #{SCPH}, #{DJI},
	   #{SL}, #{JS},#{DJ}, #{JE}, #{BBM},
	   #{SLV},#{YJBM},#{PDLY}, #{PH})
	 
	</insert>

 

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