spring mybatis获取mapper的方式有哪些
spring-mybatis获取mapper方式汇总
项目背景:
pojo下面有一个user实体类
Dao包下面写了usermapper.xml 和usermapper.interface,其中只有一个方法查询数据库中所有的用户。
1.用实现类获取这个用户
mysql.jdbc.Driver"/>
实现类usermapperImpl:
public class UserMapperImpl implements UserMapper { private SqlSessionTemplate sqlSession; public ListselectAllUser() { return sqlSession.getMapper(UserMapper.class).selectAllUser(); } public void setSqlSession(SqlSessionTemplate sqlSession) { this.sqlSession = sqlSession; } }
test测试:
@Test public void test2(){ ApplicationContext app = new ClassPathXmlApplicationContext("spring-dao.xml"); UserMapperImpl userMapper = app.getBean(UserMapperImpl.class); Listusers = userMapper.selectAllUser(); for (User user : users) { System.out.println(user); } }
2.SqlSessionDaoSupport获取
public class UserMapperImpl1 extends SqlSessionDaoSupport implements UserMapper { public ListselectAllUser() { return getSqlSession().getMapper(UserMapper.class).selectAllUser(); } }
bean的注册:
3.MapperFactoryBean
测试:
@Test public void test3(){ ApplicationContext app = new ClassPathXmlApplicationContext("spring-dao.xml"); UserMapper userMapper = app.getBean(UserMapper.class); // UserMapper userMapper = app.getBean("userimpl"); Listusers = userMapper.selectAllUser(); for (User user : users) { System.out.println(user); } }
在使用这个MapperFactoryBean方式的时候,通过app有两种方式获取bean,一种是id然后强转,另一种是接口的类型class。
4.MapperScannerConfigurer
xml配置
test:
@Test public void test4(){ ApplicationContext app = new ClassPathXmlApplicationContext("spring-dao.xml"); UserMapper bean = app.getBean(UserMapper.class); for (User user : bean.selectAllUser()) { System.out.println(user); } }
mybatis的mapper注解
从mybatis3.4.0开始加入了@Mapper注解,目的就是为了不再写mapper映射文件(那个xml写的是真的无语。。。)。很恶心的一个事实是源码中并没有对于这个注解的详细解释
在 Spring 程序中,Mybatis 需要找到对应的 mapper,在编译的时候动态生成代理类,实现数据库查询功能,所以我们需要在接口上添加 @Mapper 注解。
@Mapper public interface UserDao { ... }
但是,仅仅使用@Mapper注解,我们会发现,在其他变量中依赖注入,IDEA 会提示错误,但是不影响运行(亲测~)。
因为我们没有显式标注这是一个 Bean,IDEA 认为运行的时候会找不到实例注入,所以提示我们错误。
如下图,会有红色波浪线。
尽管这个错误提示并不影响运行,但是看起来很不舒服,所以我们可以在对应的接口上添加 bean 的声明,如下:
@Repository // 也可以使用@Component,效果都是一样的,只是为了声明为bean @Mapper public interface UserDao { @Insert("insert into user(account, password, user_name) " + "values(#{user.account}, #{user.password}, #{user.name})") int insertUser(@Param("user") User user) throws RuntimeException; }
基于注解的开发也有其他手段帮助 Mybatis 找到 mapper,那就是 @MapperScan 注解,可以在启动类上添加该注解,自动扫描包路径下的所有接口。
@SpringBootApplication @MapperScan("com.scut.thunderlearn.dao") public class UserEurekaClientApplication { public static void main(String[] args) { SpringApplication.run(UserEurekaClientApplication.class, args); } }