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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With