MyBatis —— 第二十八章 MyBatis 的 DAO 层实现
1. 传统开发方式
1.1. 编写 UserMapp 接口
/**
* @author gregPerlinLi
* @since 2021-10-08
*/
public interface UserMapper (
/**
* FInd all
*
* @return User list
* @throws IOException exception
*/
List<User> findAll() throws IOException;
)
1.2. 编写 UserMapperImperl 实现
/**
* @author gregPerlinLi
* @since 2021-10-08
*/
public class UserMapperImpl implements UserMapper {
@Override
public List<User> findAll() throws IOException {
InputStream resourceAsStream = Resources.getResourceAsStream("sqlMapConfig.xml");
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(resourceAsStream);
SqlSession sqlSession = sqlSessionFactory.openSession();
return sqlSession.selectList("userMapper.findAll");
}
}
1.3. 编写 Service 层
/**
* @author gregPerlinLi
* @since 2021-10-08
*/
public class ServiceDemo {
public static void main(String[] args) throws IOException {
// Create Dao layer object, the current Dao layer implementation is manual creation
UserMapper userMapper = new UserMapperImpl();
List<User> all = userMapper.findAll();
System.out.println(all);
}
}
2. 代理开发方式
2.1. 代理开发方式介绍
采用 MyBatis 的代理开发方式实现 DAO 层的开发,这种方式是我们后面进入企业的主流。
Mapper 接口开发方法只需要程序员编写 Mapper 接口(相当于 DAO 接口),由 MyBatis 框架根据接口定义创建接口的动态代理对象,代理对象的方法同上边 DAO 接口实现类方法。
Mapper 接口开发需要遵循以下规范:
mapper.xml文件中的namespace与 Mapper 接口的全限定名相同- Mapper 接口方法名和
mapper.xml中定义的每个 SQL 的id相同 - Mapper 接口方法的输入参数类型和
mapper.xml中定义的每个 SQL 的parameterType的类型相同 - Mapper 接口方法的输出参数类型和
mapper.xml中定义的每个 SQL 的resultType的类型相同
2.2. 编写 UserMapper 接口
<mapper namespace="com.yourname.mapper.UserMapper">
<select id="findById" parameterType="int" resultType="user">
select * from user where id = #{id}
</select>
</mapper>
public interface UserMapper {
User findById(int id);
}
2.3. 测试代理方式
@Test
public void testProxyDao() throws IOException {
InputStream resourceAsStream = Resources.getResourceAsStream("SqlMapConfig.xml");
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(resourceAsStream);
SqlSession sqlSession = sqlSessionFactory.openSession();
// Gets the implementation class of the UserMapper interface generated by the mybatis framework
UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
User user = userMapper.findById(1);
System.out.println(user);
sqlSession.close();
}
3. 知识要点
MyBatis 的 DAO 层实现的两种方式:
手动对 DAO 进行实现: 传统开发方式
代理方式对 DAO 进行实现:
UserMapper userMapper = sqlSession.getMapper(UserMapper.class);