- 首先创建数据库访问接口DemoMapper,MyBatis会自动的创建这个接口的具体子类实例,利用这个实例就可以访问数据库了。
DemoMapper接口
public interface DemoMapper {
@Select("select 'Hello world'")
String hello();
}
- select用来声明sql语句
MyBatisConfig.java
@MapperScan("cn.tedu.mapper")
public class MyBatisConfig {
@Bean
public SqlSessionFactory sqlSessionFactory(DataSource dataSource) throws Exception {
SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
bean.setDataSource(dataSource);
return bean.getObject();
}
}
- 添加组件扫描@MapperScan(“cn.tedu.mapper”)
- 定义SqlSessionFactory
测试
@Test
public void testHelloWorld(){
DemoMapper mapper = ctx.getBean("demoMapper",DemoMapper.class);
String str = mapper.hello();
System.out.println(str);
}
|