Question

I'm setting up a MyBatis project with mybatis-spring, and I'd like to use Java configuration for everything except the actual SQL (e.g. no @Select annotations in the mapper interfaces).

I've got the following setup, which works, but it uses @Select:

DataSource Beans:

@Configuration
public class DataSourceConfig {

    @Bean
    public DataSource devDataSource() {
        ... set up data source
        return dataSource;
    }
}

MyBatis Beans:

@Configuration
@MapperScan("myproject.persistence")
public class MyBatisConfig {

    @Autowired
    DataSource dataSource;

    @Bean
    public SqlSessionFactory sqlSessionFactory() throws Exception {
        final SqlSessionFactoryBean sessionFactory = new SqlSessionFactoryBean();
        sessionFactory.setDataSource(dataSource);
        return sessionFactory.getObject();
    }
}

Mapper Interface:

package myproject.persistence;

public interface PersonMapper {

    @Select("SELECT * FROM PersonTable WHERE PersonTable.LAST_NAME = #{lastName}")
    List<Person> getByLastName(@Param("lastName") String lastName);
}

A Service:

@Service
public class PeopleService {

    @Autowired
    PersonMapper personMapper;

    public List<Person> getByLastName(final String lastName) {
        return personMapper.getByLastName(lastName);
    }
}

I'm looking for a way to move the SQL statement in the @Select annotation to an XML file (but maintain Java configuration for all beans, and still use @MapperScan). The missing link I'm looking for would be the method to pair the mapper interface with an XML "mapper" that defines SQL statements.

Was it helpful?

Solution

you can define you sql in your PersonMapper.xml under myproject.persistence package (notice:the interface should be in the same package with the xml ).like blow:

<mapper namespace="myproject.persistence.PersonMapper">
   <select id="getByLastName" parameterType="string" resultType="myproject.domain.Person">
      SELECT * FROM PersonTable WHERE PersonTable.LAST_NAME = #{lastName}
   </select>

mybatis will auto look for the method you defined in the xml files.

OTHER TIPS

package cn.fruitd.config;

import com.alibaba.druid.pool.DruidDataSource;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.annotation.MapperScan;
import org.mybatis.spring.mapper.MapperScannerConfigurer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.EnvironmentAware;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;
import org.springframework.core.io.AbstractResource;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;

import javax.sql.DataSource;
import java.io.IOException;
import java.io.InputStream;

@Configuration
@MapperScan("cv.fruitd.dao")
public class DBConfig implements EnvironmentAware {

    @Autowired
    Environment env;


    /**
     * 配置数据源
     *
     * @return
     */
    @Bean(initMethod = "init", destroyMethod = "close")
    public DataSource dataSource() {
        DruidDataSource dataSource = new DruidDataSource();
        dataSource.setUrl(env.getProperty("db-url"));
        dataSource.setUsername(env.getProperty("db-username"));
        dataSource.setPassword(env.getProperty("db-password"));
        dataSource.setAsyncInit(Boolean.parseBoolean(env.getProperty("db-asyncInit", "true")));
        dataSource.setMinIdle(Integer.parseInt(env.getProperty("db-minIdle", "1")));
        dataSource.setMaxActive(Integer.parseInt(env.getProperty("db-maxActive", "20")));
        dataSource.setMaxWait(Long.parseLong(env.getProperty("db-maxWait", "60000")));
        return dataSource;
    }


    @Bean
    @Autowired
    public SqlSessionFactoryBean sqlSessionFactoryBean(DataSource dataSource) throws IOException {
        SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
        sqlSessionFactoryBean.setDataSource(dataSource);
        PathMatchingResourcePatternResolver pathM3R = new PathMatchingResourcePatternResolver();
        sqlSessionFactoryBean.setMapperLocations(pathM3R.getResources("classpath*:mybatis/*.xml"));
        return sqlSessionFactoryBean;
    }

    @Bean
    public MapperScannerConfigurer mapperScannerConfigurer() {
        MapperScannerConfigurer mapperScannerConfigurer =
                new MapperScannerConfigurer();
        mapperScannerConfigurer.setBasePackage("cn.fruitd.dao");
        mapperScannerConfigurer.setSqlSessionFactoryBeanName("sqlSessionFactoryBean");
        return mapperScannerConfigurer;
    }


    @Override
    public void setEnvironment(Environment environment) {
        this.env = environment;
    }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top