spring-boot mybatis mapper生成sql有问题

J2EE 码拜 9年前 (2016-03-13) 1658次浏览
datasource

package com.grass.config;
import com.alibaba.druid.pool.DruidDataSource;
import com.github.pagehelper.PageHelper;
import com.grass.common.interceptor.PerformanceInterceptor;
import org.apache.ibatis.plugin.Interceptor;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.SqlSessionTemplate;
import org.mybatis.spring.annotation.MapperScan;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.EnvironmentAware;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order;
import org.springframework.core.env.Environment;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import javax.sql.DataSource;
import java.util.Properties;
/**
 * Created by on 2016/4/18.
 */
@Configuration
@EnableTransactionManagement
//@MapperScan("com.grass.module.**.mapper")
@Order(2)
public class DataSourceConfig implements EnvironmentAware {
    @Value("${spring.datasource.driver-class-name}")
    private String driverClassName;
    @Value("${spring.datasource.url}")
    private String url;
    @Value("${spring.datasource.username}")
    private String username;
    @Value("${spring.datasource.password}")
    private String password;
    @Value("${spring.datasource.max-active}")
    private int maxActive;
    @Value("${spring.datasource.initial-size}")
    private int initialSize;
    @Value("${spring.datasource.max-wait}")
    private int maxWait;
    @Value("${spring.datasource.min-idle}")
    private int minIdle;
    @Value("${spring.datasource.time-between-eviction-runs-millis}")
    private int timeBetweenEvictionRunsMillis;
    @Value("${spring.datasource.min-evictable-idle-time-millis}")
    private long minEvictableIdleTimeMillis;
    @Value("${spring.datasource.validation-query}")
    private String validationQuery;
    @Value("${spring.datasource.test-while-idle}")
    private boolean testWhileIdle;
    @Value("${spring.datasource.test-on-borrow}")
    private boolean testOnBorrow;
    @Value("${spring.datasource.test-on-return}")
    private boolean testOnReturn;
    @Value("${spring.datasource.pool-prepared-statements}")
    private boolean poolPreparedStatements;
    @Value("${spring.datasource.max-open-prepared-statements}")
    private int maxOpenPreparedStatements;
    @Value("${mybatis.typeAliasesPackage}")
    private String typeAliasesPackage;
    @Value("${mybatis.mapperLocations}")
    private String mapperLocations;
    @Value("${spring.datasource.filters}")
    private String filters;
    private static Logger logger = LoggerFactory.getLogger(DataSourceConfig.class);
    @Bean
    public DataSource dataSource() {
        logger.info("grass--DataSourceConfig--dataSource--init");
        logger.info("grass--DataSourceConfig--dataSource--driverClassName:" + this.driverClassName);
        logger.info("grass--DataSourceConfig--dataSource--url:" + this.url);
        logger.info("grass--DataSourceConfig--dataSource--username:" + this.username);
        logger.info("grass--DataSourceConfig--dataSource--password:" + this.password);
        DruidDataSource dataSource = new DruidDataSource();
        dataSource.setUrl(this.url);
        dataSource.setDriverClassName(this.driverClassName);
        dataSource.setUsername(this.username);
        dataSource.setPassword(this.password);
        dataSource.setMaxActive(this.maxActive);
        dataSource.setMinIdle(this.minIdle);
        dataSource.setTimeBetweenEvictionRunsMillis(this.timeBetweenEvictionRunsMillis);
        dataSource.setMinEvictableIdleTimeMillis(this.minEvictableIdleTimeMillis);
        dataSource.setValidationQuery(this.validationQuery);
        dataSource.setTestWhileIdle(this.testWhileIdle);
        dataSource.setTestOnBorrow(this.testOnBorrow);
        dataSource.setTestOnReturn(this.testOnReturn);
        dataSource.setPoolPreparedStatements(this.poolPreparedStatements);
        dataSource.setMaxOpenPreparedStatements(this.maxOpenPreparedStatements);
        try {
            dataSource.setFilters(this.filters);
        } catch (Exception e) {
            e.printStackTrace();
            return dataSource;
        }
        return dataSource;
    }
    @Bean(name = "transactionManager")
    public DataSourceTransactionManager transactionManager(DataSource dataSource) {
        logger.info("grass--DataSourceConfig--transactionManager--init");
        DataSourceTransactionManager dataSourceTransactionManager = new DataSourceTransactionManager(dataSource);
        return dataSourceTransactionManager;
    }
    @Bean
    public SqlSessionTemplate sqlSessionTemplate(SqlSessionFactory sqlSessionFactory) {
        return new SqlSessionTemplate(sqlSessionFactory);
    }
    @Bean(name = "sqlSessionFactory")
    public SqlSessionFactory sqlSessionFactory(DataSource dataSource) throws Exception {
        logger.info("grass--DataSourceConfig--sqlSessionFactory--init");
        SqlSessionFactoryBean sessionFactory = new SqlSessionFactoryBean();
        sessionFactory.setDataSource(dataSource);
        Interceptor[] interceptors = new Interceptor[2];
        PageHelper pageHelper = new PageHelper();
        Properties properties = new Properties();
//      <!-- 4.0.0以后版本可以不设置该参数 -->
//        <property name="dialect" value="mysql"/>
//        <!-- 该参数默认为false -->
//        <!-- 设置为true时,会将RowBounds第一个参数offset当成pageNum页码使用 -->
//        <!-- 和startPage中的pageNum效果一样-->
//        <property name="offsetAsPageNum" value="true"/>
//        <!-- 该参数默认为false -->
//        <!-- 设置为true时,使用RowBounds分页会进行count查询 -->
//        <property name="rowBoundsWithCount" value="true"/>
//        <!-- 设置为true时,假如pageSize=0或RowBounds.limit = 0就会查询出全部的结果 -->
//        <!-- (相当于没有执行分页查询,但是返回结果仍然是Page类型)-->
//        <property name="pageSizeZero" value="true"/>
//        <!-- 3.3.0版本可用 - 分页参数合理化,默认false禁用 -->
//        <!-- 启用合理化时,假如pageNum<1会查询第一页,假如pageNum>pages会查询最后一页 -->
//        <!-- 禁用合理化时,假如pageNum<1或pageNum>pages会返回空数据 -->
//        <property name="reasonable" value="false"/>
//        <!-- 3.5.0版本可用 - 为了支持startPage(Object params)方法 -->
//        <!-- 增加了一个`params`参数来配置参数映射,用于从Map或ServletRequest中取值 -->
//        <!-- 可以配置pageNum,pageSize,count,pageSizeZero,reasonable,orderBy,不配置映射的用默认值 -->
//        <!-- 不理解该含义的前提下,不要随便复制该配置 -->
//        <property name="params" value="pageNum=start;pageSize=limit;"/>
//        <!-- 支持通过Mapper接口参数来传递分页参数 -->
//        <property name="supportMethodsArguments" value="true"/>
//        <!-- always总是返回PageInfo类型,check检查返回类型能否为PageInfo,none返回Page -->
//        <property name="returnPageInfo" value="check"/>
        properties.put("dialect", "mysql");
        properties.put("rowBoundsWithCount", true);
        properties.put("pageSizeZero", false);
        properties.put("reasonable", true);
        properties.put("supportMethodsArguments", true);
        properties.put("returnPageInfo", "check");
        properties.put("mapUnderscoreToCamelCase", true);
        properties.put("cacheEnabled", true);
        properties.put("mappers", "tk.mybatis.mapper.common.Mapper");
        PerformanceInterceptor performanceInterceptor = new PerformanceInterceptor();
        interceptors[0] = performanceInterceptor;
        interceptors[1] = pageHelper;
        sessionFactory.setPlugins(interceptors);
        sessionFactory.setConfigurationProperties(properties);
        sessionFactory.setTypeAliasesPackage(this.typeAliasesPackage);
        sessionFactory.setMapperLocations(new PathMatchingResourcePatternResolver().getResources(this.mapperLocations));
        return sessionFactory.getObject();
    }
    @Override
    public void setEnvironment(Environment environment) {
    }
}

MyBatisMapperScannerConfig

package com.grass.config;
import com.grass.common.persistence.BaseMapper;
import org.springframework.boot.autoconfigure.AutoConfigureAfter;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import tk.mybatis.mapper.common.Mapper;
import tk.mybatis.spring.mapper.MapperScannerConfigurer;
import java.util.Properties;
/**
 * 〈一句话功能简述〉
 * 〈功能详细描述〉
 *
 * @author 
 * @version [v1.0, 2016/6/30]
 * @since [v1.0]
 */
@Configuration
//注意,由于MapperScannerConfigurer执行的比较早,所以必须有下面的注解
@AutoConfigureAfter(DataSourceConfig.class)
public class MyBatisMapperScannerConfig {
    @Bean
    public MapperScannerConfigurer mapperScannerConfigurer() {
        MapperScannerConfigurer mapperScannerConfigurer = new MapperScannerConfigurer();
        mapperScannerConfigurer.setSqlSessionFactoryBeanName("sqlSessionFactory");
        mapperScannerConfigurer.setBasePackage("com.grass.module.**.mapper");
        Properties properties = new Properties();
        properties.setProperty("mappers", BaseMapper.class.getName());
        properties.setProperty("notEmpty", "false");
        properties.setProperty("IDENTITY", "MYSQL");
        mapperScannerConfigurer.setProperties(properties);
        return mapperScannerConfigurer;
    }
}

使用公共的selectByPrimaryKey方法,生成的sql是SELECT ID,NAME,AGE FROM TEST WHERE ID = 1 AND NAME = 1 AND AGE = 1,应该是SELECT ID,NAME,AGE FROM TEST WHERE ID = 1
使用selectByExample方法
报错

There is no getter for property named "distinct" in "class com.grass.module.test.entity.TestEntity"

但是本人没有没有这个属性,这应该是还是生成sql的错

解决方案

13

本人用generator mybatis 这个可以生成sql,你可以试试,http://www.cnblogs.com/smileberry/p/4145872.html

13

用的xml文件
http://www.milletblog.com/2016/07/MyBatisGenerator%E8%AF%A6%E8%A7%A3-49/
http://www.milletblog.com/2016/07/MyBatisGeneratorgeneratorConfigxml%E9%85%8D%E7%BD%AE%E8%AF%A6%E8%A7%A3-76/
可以看一下看看有帮助没

14

distinct  找找看看

CodeBye 版权所有丨如未注明 , 均为原创丨本网站采用BY-NC-SA协议进行授权 , 转载请注明spring-boot mybatis mapper生成sql有问题
喜欢 (0)
[1034331897@qq.com]
分享 (0)