mybatis中dao层的实现

1.传统方式实现dao层

package com.shenhao.dao;

import com.shenhao.domain.User;

public interface UserDao {
    User findById(int id);
}
package com.shenhao.dao.impl;

import com.shenhao.dao.UserDao;
import com.shenhao.domain.User;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

public class UserDaoImpl implements UserDao {
    @Override
    public User findById(int id) {
        SqlSessionFactoryBuilder builder = new SqlSessionFactoryBuilder();

        SqlSessionFactory sqlSessionFactory = builder.build(UserDaoImpl.class.getClassLoader().getResourceAsStream("SqlMapper.xml"));

        SqlSession sqlSession = sqlSessionFactory.openSession();

        return sqlSession.selectOne("user.findById",id);
    }
}
    @Test
    public void testFindById(){
        UserDao userDao = new UserDaoImpl();

        User user = userDao.findById(1);

        System.out.println(user);
    }

2.使用动态代理的方式实现dao层
Mapper动态代理开发方式只需要程序员开发Mapper接口(相当于Dao接口),Mybatis框架会根据接口定义创建接口的动态代理对象,代理对象的方法同Dao接口实现类中的方法。

Mapper接口开发需要遵循以下4个规范:
 Mapper映射文件中的namespace与mapper接口的类路径相同。
 Mapper接口方法名和Mapper映射文件中定义的每个Sql的id相同
 Mapper接口方法的输入参数类型和Mapper映射文件中定义的每个Sql的ParameterType的类型相同
 Mapper接口方法的输出参数类型和Mapper映射文件中定义的每个Sql的resultType的类型相同

    @Test
    public void testFindById(){
        SqlSessionFactoryBuilder builder = new SqlSessionFactoryBuilder();

        SqlSessionFactory sqlSessionFactory = builder.build(AppTest.class.getClassLoader().getResourceAsStream("SqlMapConfig.xml"));

        SqlSession sqlSession = sqlSessionFactory.openSession();

        UserDao userDao = sqlSession.getMapper(UserDao.class);

        User user = userDao.findById(1);

        System.out.println(user);
    }