一、创建接口类
1.新建包cn.mybatis.mapper
2.在包中新建接口,创建演示接口DemoMapper
public interface DemoMapper {
//下面的方法就是使用Mybatis实现的查询方法了
//不需要编写实现类
@Select("select username from vrduser where id=1")
public String select();
}
二、添加SqlSessionFactory
1.在MyBaits的配置类中添加SqlSessionFactory类
2.SqlSessionFactory类的简介
a.SqlSessionFactory类在MyBatis框架中非常重要,SqlSessionFactory类可以根据接口中声明的信息自动实现这个类的接口类,并将这个类注入到Spring容器中来供我们使用
@Bean
public SqlSessionFactory sqlSessionFactory(
DataSource dataSource) throws Exception {
SqlSessionFactoryBean bean=
new SqlSessionFactoryBean();
bean.setDataSource(dataSource);
return bean.getObject();
}
3.在MyBaits的配置类上方添加注解
@PropertySource("classpath:jdbc.properties") //注入数据库连接的配置文件
@MapperScan("cn.mybaits.mapper") //注入这是存放接口的包名,表示指定qlSessionFactory类要扫描并生成实现类的包
三、测试,执行接口中方法
//测试SqlSessionFactory,查看是否这个类是否成功
@Test
public void testFactory(){
SqlSessionFactory factory=ctx.getBean(
"sqlSessionFactory",SqlSessionFactory.class);
System.out.println(factory);
}
//执行Mapper接口中的方法
@Test
public void testUsername(){
DemoMapper mapper=ctx.getBean(
"demoMapper",DemoMapper.class);
String name=mapper.hello();
System.out.println(name);
}