简体   繁体   English

带有Java Config和XML映射器的MyBatis-Spring

[英]MyBatis-Spring with Java Config and XML mappers

I'm setting up a MyBatis project with mybatis-spring, and I'd like to use Java configuration for everything except the actual SQL (eg no @Select annotations in the mapper interfaces). 我正在使用mybatis-spring设置一个MyBatis项目,我希望将Java配置用于除实际SQL之外的所有内容(例如,mapper接口中没有@Select注释)。

I've got the following setup, which works, but it uses @Select: 我有以下设置,它有效,但它使用@Select:

DataSource Beans: DataSource Bean:

@Configuration
public class DataSourceConfig {

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

MyBatis Beans: 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). 我正在寻找一种方法将@Select注释中的SQL语句移动到XML文件(但是为所有bean维护Java配置,并且仍然使用@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. 我正在寻找的缺失链接是将映射器接口与定义SQL语句的XML“映射器”配对的方法。

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: 你可以在myproject.persistence包下的PersonMapper.xml中定义你的sql(注意:接口应该与xml在同一个包中)。

<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. mybatis将自动查找您在xml文件中定义的方法。

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;
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM