Mybatis学习 三
思考:能否只写接口,不写实现类。只编写接口和Mapper.xml即可?
因为在dao(mapper)的实现类中对sqlsession的使用方式很类似。因此mybatis提供了接口的动态代理。
一:新建dao包并创建接口UserDao
二:在mapper下新建UserDao.xml文件,并编写update语句
三:在mybatis配置文件下<mappers>标签下新增UserDao.xml的应用
<mapper resource="com/founderit/mapper/UserDao.xml"/>
四:测试
可以看出程序报错了,报错信息如下
Exception in thread "main" org.apache.ibatis.binding.BindingException: Type interface com.founderit.dao.UserDao is not known to the MapperRegistry.
at org.apache.ibatis.binding.MapperRegistry.getMapper(MapperRegistry.java:47)
at org.apache.ibatis.session.Configuration.getMapper(Configuration.java:745)
at org.apache.ibatis.session.defaults.DefaultSqlSession.getMapper(DefaultSqlSession.java:292)
at com.founderit.main.TestMain.main(TestMain.java:35)
具体报错信息为该行
UserDao userDao=sqlSession.getMapper(UserDao.class);
mybatis会根据反射机制获取代理,但框架没找到mapper,这是由于上一篇提过Mapper中Namespace的定义本身是没有限制的,只要不重复即可,但如果使用Mybatis的DAO接口动态代理,则namespace必须为DAO接口的全路径,修改UserDao.xml中的namespace属性为com.founderit.dao.UserDao,再次执行测试
测试成功