Mybatis的Dao层实现

tech2022-08-22  122

传统开发方式

1.编写UserDao接口
public interface UserDao { List<User> findAll() throws IOException; }
2.编写UserDaoImpl实现
public class UserDaoImpl implements UserDao { public List<User> findAll() throws IOException { InputStream resourceAsStream = Resources.getResourceAsStream("SqlMapConfig.xml"); SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(resourceAsStream); SqlSession sqlSession = sqlSessionFactory.openSession(); List<User> userList = sqlSession.selectList("userMapper.findAll"); sqlSession.close(); return userList; } }
3.测试传统方式
@Test public void testTraditionDao() throws IOException { UserDao userDao = new UserDaoImpl(); List<User> all = userDao.findAll(); System.out.println(all); }

代理开发方式

1.代理开发方式介绍

Mapper 接口开发方法只需要程序员编写Mapper 接口(相当于Dao 接口),由Mybatis 框架根据接口定义创建接口的动态代理对象,代理对象的方法体同上边Dao接口实现类方法

2.Mapper 接口开发需要遵循以下规范:
Mapper.xml文件中的namespace与mapper接口的全限定名相同Mapper接口方法名和Mapper.xml中定义的每个statement的id相同Mapper接口方法的输入参数类型和mapper.xml中定义的每个sql的parameterType的类型相同Mapper接口方法的输出参数类型和mapper.xml中定义的每个sql的resultType的类型相同 参考如图:
3.测试代理方式
@Test public void testProxyDao() throws IOException { InputStream resourceAsStream = Resources.getResourceAsStream("SqlMapConfig.xml"); SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(resourceAsStream); SqlSession sqlSession = sqlSessionFactory.openSession(); //获得MyBatis框架生成的UserMapper接口的实现类 UserMapper userMapper = sqlSession.getMapper(UserMapper.class); User user = userMapper.findById(1); System.out.println(user); sqlSession.close(); }
最新回复(0)