说明:注解就是利用接口实现的,因此转为面向接口编程,使用接口开发拓展性好、分层开发时上层不用管理具体的实现、****更加标准化更加规范、使得各个层的耦合度更低。
注:有了注释语句就不需要实体类的mapper文件了,因为mapper主要就是用来映射sql语句的
注解的实现如下:
1.编写一个dao的接口,例如:
//------------dao接口类------------//
public interface UserDaoInterface {
@Select("select * from users")
public List<User> getList();
@Insert("insert into user(username,password) values(#{username},#{pwd})")
public int insert(User user);
}
2.在核心配置文件中导入类,注意需要使用的是class属性,例如:
//------------映射文件------------//
<mappers>
<!-- 定义SQL语句的注释,利用一个接口类表示 -->
<mapper class="cn.lxy.dao.UserDaoInterface"/>
</mappers>
3.使用,例如:
public class test
{
public static void main(String[] args) throws IOException {
SqlSession session=MyBatisUtil.getSession();
//此处用session的映射方法实现接口,直接把接口类当作映射处理
UserDaoInterface userDaoInterface=session.getMapper(UserDaoInterface.class);
List<User> list=userDaoInterface.getList();
for(User u:list)
{
System.out.println(u);
}
}
}