Mybatis两种开发方式

来源:互联网 发布:树洞外链美化源码 编辑:程序博客网 时间:2024/06/05 03:16

MyBatis是支持普通 SQL查询,存储过程和高级映射的优秀持久层框架,具有的特点,避免了JDBC对数据库进行频繁连接开启和关闭造成数据库资源浪费和硬编码现象的出现。

MyBatis开发dao具有两种开发方式,原始的dao开发和mapper代理的开发方式
Dao开发方式需要dao接口和dao实现类,向dao实现类中注入SqlSessionFactory,在方法体内通过SqlSessionFactory创建SqlSession

public interface UserDao {public User findUserById(int id) throws Exception;}

public class UserDaoImpl implements UserDao {private SqlSessionFactory sqlSessionFactory;public UserDaoImpl(SqlSessionFactory sqlSessionFactory) {this.sqlSessionFactory = sqlSessionFactory;}@Overridepublic User findUserById(int id) throws Exception {SqlSession sqlSession = sqlSessionFactory.openSession();User user = sqlSession.selectOne("User.findUserById", id);sqlSession.close();return user;}}

<?xml version="1.0" encoding="UTF-8" ?><!DOCTYPE mapperPUBLIC "-//mybatis.org//DTD Mapper 3.0//EN""http://mybatis.org/dtd/mybatis-3-mapper.dtd"><mapper namespace="User ">       <select id="findUserById" parameterType="int" resultType="cn.itcast.mybatis.po.User">SELECT * FROM USER WHERE id=#{value}</select></mapper>

public class UserDaoImplTest {private SqlSessionFactory sqlSessionFactory;@Beforepublic void setUp() throws Exception {String resource = "SqlMapConfig.xml";InputStream inputStream = Resources.getResourceAsStream(resource);sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);}@Testpublic void testFindUserById() throws Exception {UserDao userDao = new UserDaoImpl(sqlSessionFactory);User user = userDao.findUserById(1);}}

Dao开发方式的局限性主要在于dao接口实现类方法中存在冗余并且存在硬编码。


mapper代理的开发方式需要mapper.xml映射文件

<mapper namespace="cn.itcast.mybatis.mapper.UserMapper"><select id="findUserList" parameterType="cn.itcast.mybatis.po.UserQueryVo" resultType="cn.itcast.mybatis.po.UserCustom">SELECT * FROM USER WHERE id=#{value}</select><mappers>

public User findUserById(int id) throws Exception;

<mappers>     <mapper resource="sqlmap/User.xml"/></mappers>

 

@Testpublic void testFindUserById () throws Exception {SqlSession sqlSession = sqlSessionFactory.openSession();UserMapper userMapper = sqlSession.getMapper(UserMapper.class);List<User> list = userMapper.findUserById ("1");sqlSession.close();





0 0
原创粉丝点击