Mybatis两种开发方式

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;
	}
	@Override
	public User findUserById(int id) throws Exception {
		SqlSession sqlSession = sqlSessionFactory.openSession();
		User user = sqlSession.selectOne("User.findUserById", id);
		sqlSession.close();
		return user;
	}
}





       

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

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


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




public User findUserById(int id) throws Exception;	


     

 

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





你可能感兴趣的:(Mybatis两种开发方式)