1.MyBatis的Dao层实现
1.1 传统开发方式
1.编写UserDao接口
public interface UserDao {
List<User> findAll() throws IOException;
}
1.2 代理开发方式
1. 代理开发方式介绍
采用MyBatis的代理开发方式实现DAO层的开发,这种方式是企业开发的主流
Mapper接口开发方法只需要程序员编写Mapper接口(相当于Dao接口),由Mybatis框架根据接口定义创建接口的动态代理对象,代理对象的方法同Dao接口实现类方法。
Mapper接口开发需要遵循以下规范:
- Mapper.xml文件中的namespace与mapper接口的全限定名相同
- Mapper接口方法名和Mapper.xml中定义的每个statement的id相同
- Mapper接口方法的输入参数类型和mapper.xml中定义的每个sql的parameterType的类型相同
- Mapper接口方法的输出参数类型和mapper.xml中定义的每个sql的resultType的类型相同
2. 编写UserMapper接口
public interface UserMapper {
public List<User> findAll() throws IOException;
public User findById(int id);
}
3. 测试代理方式
@Test
public void tstProxyDao() throws IOException {
InputStream resourceAsStream = Resources.getResourceAsStream("SqlMapConfig.xml");
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(resourceAsStream);
SqlSession sqlSession = sqlSessionFactory.openSession();
//获取MyBatis框架生成的UserMapper接口的实现类
UserMaper userMapper = sqlSession.getMapper(UserMapper.class);
//查询全部
List<User> users = userMapper.findAll();
//根据id查询单个user
User user = userMapper.findById(1);
System.out.println(user);
sqlSession.close();
}