1. 将上一篇的拷贝一份,进行改进(注解)。由于使用注解配置,所以不需要xml了,删掉resources中的com文件
下面是com中IUserDao.xml里面的内容:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.itheima.dao.IUserDao">
<!--配置查询所有-->
<select id="findAll" resultType="com.itheima.domain.User">
select * from user
</select>
</mapper>
由于删掉了 IUserDao.xml ,所以主配置文件中指定映射配置文件的位置就消失了:
<!--指定映射配置文件的位置,映射配置文件指的是每个dao独立的配置文件-->
<mappers>
<mapper resource="com/itheima/dao/IUserDao.xml"/>
</mappers>
需要改为:
<!--指定映射配置文件的位置,映射配置文件指的是每个dao独立的配置文件-->
<!--如果是用注解来配置,此处应该使用class属性指定被注解的dao全限定类名-->
<mappers>
<mapper class="com.itheima.dao.IUserDao"/>
</mappers>
由于删掉了 IUserDao.xml ,所以查询语句需要重新写。在IUserDao接口中加入@Select(“select * from user”)。
public interface IUserDao {
//查询所有操作
@Select("select * from user")
List<User> findAll();
}
然后运行,依然可行。
2. 对1的总结
将xml配置改为注解配置的步骤:
① 删掉 resources 中的映射配置文件 IUserDao.xml
② 将主配置文件中的 mappers 内容改为:
<mappers>
<mapper class="com.itheima.dao.IUserDao"/>
</mappers>
即在主配置文件中的mappers中使用class属性指定dao接口的全限定类名。
③ 在 IUserDao 接口中采用注解的方式添加查询语句:
public interface IUserDao {
//查询所有操作
@Select("select * from user")
List<User> findAll();
}