0
点赞
收藏
分享

微信扫一扫

学习SSM的第十天

酷子腿长一米八 2022-04-29 阅读 118
spring

文章目录


前言

一、MyBatis的Dao层实现

1.传统的开发方式
①编写UserMapper接口

public interface UserMapper {
    public List<User> findAll() throws IOException;
}

②编写UserMapperImpl实现

public class UserMapperImpl implements UserMapper {
    @Override
    public List<User> findAll() throws IOException {
        //获得核心配置文件
        InputStream inputStream = Resources.getResourceAsStream("sqlMapConfig.xml");
        //获得session工厂对象
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
        //获得session会话对象
        SqlSession sqlSession = sqlSessionFactory.openSession();
        //执行操作  参数:namespace+id
        List<User> userList = sqlSession.selectList("userMapper.findAll");
        //打印数据
        System.out.println(userList);
        //释放资源
        sqlSession.close();
        return userList;
    }
}

③测试传统方式

public class ServiceDemo {
    public static void main(String[] args) throws Exception{
        //创建Dao对象,当前Dao层是手动编写的
        UserMapper userMapper = new UserMapperImpl();
        List<User> userList = userMapper.findAll();
        System.out.println(userList);
    }
}

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

public interface UserMapper {
    public User findById(int id);
}
<mapper namespace="com.example.dao.UserMapper">
    <!--根据id进行查询-->
    <select id="findById" parameterType="int" resultType="user">
        select * from user where id = #{id}
    </select>
</mapper>

③测试

public class ServiceDemo {
    public static void main(String[] args) throws Exception{
        //获得核心配置文件
        InputStream inputStream = Resources.getResourceAsStream("sqlMapConfig.xml");
        //获得session工厂对象
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
        //获得session会话对象
        SqlSession sqlSession = sqlSessionFactory.openSession();
        //执行操作  参数:namespace+id
        UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
        User user = userMapper.findById(1);
        System.out.println(user);
        //释放资源
        sqlSession.close();
    }
}
举报

相关推荐

第十天学习

JS学习第十天

python(第十天)

JavaScript的第十天

【JavaSE 第十天】

web第十天

HCIP第十天

0 条评论