Tag Archives: MybatisPlus

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

Some students encountered the problem of “Invalid bound statement (not found)” when building the mybatis plus project, it is essentially that the mapper interface and the mapper.xml is not mapped.

In this case, the common problems are as follows:

1, mapper.xml inside the namespace and the actual mapper class path is not consistent.
There is a quick way to detect this is to hold down the ctrl key, and then click the package name inside the namespace, if you can jump to the corresponding class, it means there is no problem, if you use the IDEA is the same way, IDEA package name can be segmented, as long as you can point in are no problem.

2, mapper interface function name and mapper.xml inside the label id is not consistent.
This problem is also very common, the best way is to paste and copy it, so as to ensure that there is no problem.

The first point and 2 points are about spelling errors.

3, the build did not go in, please see if these exist below the target folder, no please rebuild

4. Check whether package scanning is added. I added it to the spring boot startup class.

5. Check whether the configuration file is written incorrectly or not

#Is this place wrongly written?

mapper-locations: classpath:mybatis/mapper/**/*.xml

Mybatis-plus can be configured as an array:

mybatis-plus:
  mapper-locations:
    - classpath:mybatis/mapper/**/*.xml

Or

mybatis-plus:
  mapper-locations: classpath:mybatis/**/*Mapper.xml

Note that the key is mapper-locations and not mapper-locations:

Other configurations:


mybatis-plus:
  global-config:
    #primary-key-type 0: "Database ID self-incrementing", 1: "User input ID", 2: "Global unique ID (numeric unique ID)", 3: "Global unique ID UUID";
    id-type: 0
    #field-strategy 0: "Ignore judgment",1: "Non-NULL judgment"),2: "Non-Null judgment"
    field-strategy: 0
    #hump-underline conversion
    db-column-underline: true
    #refresh-mapper debugging artifact
    refresh-mapper: true
    #database capital-underline conversion
    #capital-mode: true 
    #sequence interface implementation class configuration    
	#key-generator: com.baomidou.springboot.xxx 
    #logic-delete-configuration (the following 3 configurations)
    #logic-delete-value: 0 # logical-delete value (default is 1)    
	#logic-not-delete-value: 1 # logical-not-delete value (default is 0)    
	# Custom fill policy interface implementation    
	#meta-object-handler: com.zhengqing.config.   
	#custom SQL injector   
	#sql-injector: com.baomidou.springboot.xxx configuration:      
    #SQL parsing cache, multi-tenant @SqlParser annotation takes effect when enabled
    #sql-parser-cache: true
  configuration:
    # hump conversion Similar mapping from database column names to Java property hump naming  
    map-underscore-to-camel-case: true
    # Whether to enable caching
    cache-enable: false
    # If the query contains a column with a null value, MyBatis will not map this field when mapping        
	#call-setters-on-nulls: true  
    # 打印sql
    log-impl: org.apache.ibatis.logging.stdout.StdOutImpl

[Solved] mybatisplus BaseMapper Error: required a single bean, but 2 were found

1. Error reporting

Two classes inherit com baomidou. mybatisplus. mapper. BaseMapper

Service startup error:

Field baseMapper in com.baomidou.mybatisplus.service.impl.ServiceImpl required a single bean, but 2 were found:

- UserDao: defined in file [D:\projects\test\UserDao.class]

- DepartmentDao: defined in file [D:\projects\test\DepartmentDao.class]

The code is as follows

public interface UserDao extends BaseMapper<UserInfo>{ }

public interface DepartmentDao extends BaseMapper{ }

2. Error reporting reason

Departmentdao did not specify a generic type when inheriting basemapper

3. Solution:

Specifying generics when departmentdao inherits basemapper

public interface DepartmentDao extends BaseMapper<DepartmentInfo>{ }

Bulk Update Error: #Cause: java.sql.SQLSyntaxErrorException: You have an error in your SQL syntax; check the m

Error:
mybatis plus foreach batch insert is OK. Change it to update and keep reporting errors. It is OK to copy the SQL and execute it separately.
reason:
the insert statement supports batch and can be written in one statement:

INSERT INTO table_name (column1,column2,column3,...) VALUES (value1,value2,value3,...), (value1,value2,value3,...), (value1,value2,value3,...), (value1,value2,value3,...), (value1,value2,value3,...),(value1,value2,value3,...);

Update does not support batch. There are multiple statements corresponding to cyclic batch

update table set c1=v1;
update table set c1=v2;
update table set c1=v3;
.
.
.
update table set c1=v...;

Mybatis does not support executing multiple statements (multiple semicolons) by default
solution:
add the allowmultiqueries = true parameter to the database connection

Allowmultiqueries = true function:
1. You can carry semicolons after SQL statements to realize multi statement execution
2. You can execute batch processing and issue multiple SQL statements at the same time

Mybatis-plus calls its own method error: Invalid bound statement

Mybatis plus calls its own method and reports an error invalid bound statement

1. Check for version conflicts

<dependency>
  <groupId>com.baomidou</groupId>
  <artifactId>mybatis-plus</artifactId>
  <version>3.4.3</version>
  <scope>compile</scope>
</dependency>

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

<dependency>
    <groupId>com.baomidou</groupId>
    <artifactId>mybatis-plus-extension</artifactId>
    <version>3.4.3</version>
    <scope>compile</scope>
</dependency>

2. Check the path and namespace correspondence

Check scan compile path

MybatisSqlSessionFactoryBean bean = new MybatisSqlSessionFactoryBean();
bean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath*:mapping/publicDB/**/*.xml"));

or

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

Check the incoming basemapper path

import com.baomidou.mybatisplus.core.mapper.BaseMapper;

Check the namespace and function name correspondence of the XML file to ensure that no error is reported during compilation, and remove the Chinese comments in the XML file

3. Use mybatissqlsessionfactory

/**
 * Create SqlSessionFactory
 */
@Bean(name = "primarySqlSessionFactory")
@Primary
public SqlSessionFactory testSqlSessionFactory(@Qualifier("primaryDataSource") DataSource dataSource) throws Exception {
    
    // Do not use the original of SqlSessionFactory instead of using MybatisSqlSessionFactory
    MybatisSqlSessionFactoryBean bean = new MybatisSqlSessionFactoryBean();
    bean.setDataSource(dataSource);
    bean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath*:mapping/publicDB/**/*.xml"));

    return bean.getObject();
}

Mybatisplusconfig configuration class configured in the original blog post:

import com.baomidou.mybatisplus.core.MybatisConfiguration;
import com.baomidou.mybatisplus.core.MybatisXMLLanguageDriver;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.baomidou.mybatisplus.extension.plugins.PaginationInterceptor;
import com.baomidou.mybatisplus.extension.spring.MybatisSqlSessionFactoryBean;
import org.apache.ibatis.mapping.DatabaseIdProvider;
import org.apache.ibatis.plugin.Interceptor;
import org.mybatis.spring.boot.autoconfigure.MybatisProperties;
import org.mybatis.spring.boot.autoconfigure.SpringBootVFS;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.DefaultResourceLoader;
import org.springframework.core.io.ResourceLoader;
import org.springframework.util.StringUtils;

import javax.sql.DataSource;

@Configuration
public class MybatisPlusConfig {
    @Autowired
    private DataSource dataSource;
    @Autowired
    private MybatisProperties properties;
    @Autowired
    private ResourceLoader resourceLoader = new DefaultResourceLoader();
    @Autowired(required = false)
    private Interceptor[] interceptors;
    @Autowired(required = false)
    private DatabaseIdProvider databaseIdProvider;

    /** mybatis-plus */
    @Bean
    public PaginationInterceptor paginationInterceptor() {
        PaginationInterceptor page = new PaginationInterceptor();
        page.setDialectType("mysql");
        return page;
    }

    /** All resources that are already loaded automatically by mybatis-autoconfigure are used here. Instead of manually specifying the <p> configuration file and mybatis-boot's configuration file synchronization @return */
    @Bean
    public MybatisSqlSessionFactoryBean mybatisSqlSessionFactoryBean() {
        MybatisSqlSessionFactoryBean mybatisPlus = new MybatisSqlSessionFactoryBean();
        mybatisPlus.setDataSource(dataSource);
        mybatisPlus.setVfs(SpringBootVFS.class);
        if (StringUtils.hasText(this.properties.getConfigLocation()))
            mybatisPlus.setConfigLocation(this.resourceLoader.getResource(this.properties.getConfigLocation()));
        if (!ObjectUtils.isEmpty(this.interceptors)) mybatisPlus.setPlugins(this.interceptors);
        MybatisConfiguration mc = new MybatisConfiguration();
        mc.setDefaultScriptingLanguage(MybatisXMLLanguageDriver.class);
        // Database field design for hump naming, the default open hump to underscore will report an error field can not be found
        mc.setMapUnderscoreToCamelCase(true);
        mybatisPlus.setConfiguration(mc);
        if (this.databaseIdProvider != null) mybatisPlus.setDatabaseIdProvider(this.databaseIdProvider);
        if (StringUtils.hasLength(this.properties.getTypeAliasesPackage()))
            mybatisPlus.setTypeAliasesPackage(this.properties.getTypeAliasesPackage());
        if (StringUtils.hasLength(this.properties.getTypeHandlersPackage()))
            mybatisPlus.setTypeHandlersPackage(this.properties.getTypeHandlersPackage());
        if (!ObjectUtils.isEmpty(this.properties.resolveMapperLocations()))
            mybatisPlus.setMapperLocations(this.properties.resolveMapperLocations());
        return mybatisPlus;
    }
}

org.apache.ibatis.type.TypeException: Error setting non null for parameter #4 with JdbcType null

preface

        The spring boot project uses the mybatis plus framework.

Phenomenon

        When I used mappr to execute the method updatebyid again, the following error occurred

nested exception is org.apache.ibatis.type.TypeException: Could not set parameters for mapping: ParameterMapping{property='et.props', mode=IN, javaType=class java.lang.Object, jdbcType=null, numericScale=null, resultMapId='null', jdbcTypeName='null', expression='null'}. Cause: org.apache.ibatis.type.TypeException: Error setting non null for parameter #4 with JdbcType null . Try setting a different JdbcType for this parameter or a different configuration property. Cause: org.apache.ibatis.type.TypeException: Error setting non null for parameter #4 with JdbcType null . Try setting a different JdbcType for this parameter or a different configuration property. Cause: org.postgresql.util.PSQLException: No hstore extension installed.
org.mybatis.spring.MyBatisSystemException: nested exception is org.apache.ibatis.type.TypeException: Could not set parameters for mapping: ParameterMapping{property='et.props', mode=IN, javaType=class java.lang.Object, jdbcType=null, numericScale=null, resultMapId='null', jdbcTypeName='null', expression='null'}. Cause: org.apache.ibatis.type.TypeException: Error setting non null for parameter #4 with JdbcType null . Try setting a different JdbcType for this parameter or a different configuration property. Cause: org.apache.ibatis.type.TypeException: Error setting non null for parameter #4 with JdbcType null . Try setting a different JdbcType for this parameter or a different configuration property. Cause: org.postgresql.util.PSQLException: No hstore extension installed.

Problem location

        Through the literal meaning of the exception, we can understand it as a mybatis type error.

        Following up with debug, we found that an exception occurred when setting typehandler for one of the fields, indicating that there is no type that can identify the field.

  Cause analysis

        We now check the type of this field in the entity class and find that it is a map type

          View the type of this field setting in the database  , You can see that the JSON type is stored in the database

  Solution

        Set typehandler and JDBC type for entity class

@TableField(el = "props,jdbcType=OTHER,typeHandler=com.embracesource.cloud.fsgw.entity.HashMapJsonTypeHandler")
private Map<String, Object> props;

        Hashmapjsontypehandler class

import com.alibaba.fastjson.JSON;
import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;
import org.postgresql.util.PGobject;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.Map;

public class HashMapJsonTypeHandler extends BaseTypeHandler<Map<String,Object>> {
    @Override
    public void setNonNullParameter(PreparedStatement ps, int i, Map<String,Object> parameter,
                                    JdbcType jdbcType) throws SQLException {
        PGobject jsonObject = new PGobject();
        jsonObject.setType("json");
        jsonObject.setValue(JSON.toJSONString(parameter));
        ps.setObject(i, jsonObject);
    }

    @Override
    public Map<String,Object> getNullableResult(ResultSet rs, String columnName)
            throws SQLException {

        return JSON.parseObject(rs.getString(columnName), HashMap.class);
    }

    @Override
    public Map<String,Object> getNullableResult(ResultSet rs, int columnIndex) throws SQLException {

        return JSON.parseObject(rs.getString(columnIndex), HashMap.class);
    }

    @Override
    public Map<String,Object> getNullableResult(CallableStatement cs, int columnIndex)
            throws SQLException {

        return JSON.parseObject(cs.getString(columnIndex), HashMap.class);
    }
}

         Start the project again and find the problem to be solved

Mybatis error,There is no getter for property named ‘xx’ in ‘class java.lang.String The solution

Today, I encountered a problem when using mybatis. When passing a string parameter, I encountered the following error:

Mapper.xml The code is as follows:

Error report when executing this method:

Maven is used for project jar management, and mybatis version is as follows (I use mybatis plus plug-in)

After browsing the data for half a day on the Internet, we found a solution. We need to use the_ The parameter is replaced uniformly. We modify the previous code as follows:

This is because of the version limitation of mybatis. You may not have this situation in some versions (I don’t understand very well here. Thank you )