Mybatis的dao层实现的两种开发方式

传统开发方式

// 1. 编写UserMapper接口
public interface UserMapper {
    public List<User> findAll() throws IOException;
}

// 2. 在xml映射文件中补充sql语句
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="userMapper">
    <select id="findAll" resultType="user">
       select * from user
    </select>
</mapper>

// 3. 编写UserMapperImpl实现
public class UserMapperImpl implements UserMapper {
    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;
    }
}
// 4.测试
public class ServiceDemo {
    public static void main(String[] args) throws IOException {
        UserMapperImpl userMapper = new UserMapperImpl();
        List<User> userList = userMapper.findAll();
        System.out.println(userList);
    }
}

代理开发方式

采用 Mybatis 的代理开发方式实现 DAO 层的开发,这种方式是我们后面进入企业的主流。
Mapper 接口开发方法只需要程序员编写Mapper 接口(相当于Dao 接口),由Mybatis 框架根据接口定义创建接口的动态代理对象,代理对象的方法体同上边Dao接口实现类方法。
Mapper 接口开发需要遵循以下规范:
1、 Mapper.xml文件中的namespace与mapper接口的全限定名相同
2、 Mapper接口方法名和Mapper.xml中定义的每个statement的id相同
3、 Mapper接口方法的输入参数类型和mapper.xml中定义的每个sql的parameterType的类型相同
4、 Mapper接口方法的输出参数类型和mapper.xml中定义的每个sql的resultType的类型相同
Mybatis的dao层实现的两种开发方式_第1张图片

// 1. 编写UserMapper接口
public interface UserMapper {
    public List<User> findAll() throws IOException;
    public User findById(int id);
}

// 2. 在xml映射文件中补充sql语句
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.itheima.dao.UserMapper">
    <select id="findById" parameterType="int" resultType="com.itheima.domain.User">
        select * from USER where id=#{id}
    </select>

    <select id="findAll" resultType="user">
       select * from user
    </select>
</mapper>

// 测试
public class ServiceDemo {
    public static void main(String[] args) throws IOException {
        // 查询所有
        InputStream resourceAsStream = Resources.getResourceAsStream("sqlMapConfig.xml");
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(resourceAsStream);
        SqlSession sqlSession = sqlSessionFactory.openSession();
        UserMapper mapper = sqlSession.getMapper(UserMapper.class);
        List<User> all = mapper.findAll();
        System.out.println(all);
        System.out.println("===============");
        // 根据id进行查询
        User user = mapper.findById(8);
        System.out.println(user);
        sqlSession.close();
    }
}


你可能感兴趣的:(框架)