Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 (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.

like image 432
Chris Clark Avatar asked Nov 12 '13 01:11

Chris Clark


1 Answers

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.

like image 98
Rhain Avatar answered Oct 27 '22 00:10

Rhain