Mybatis两种开发方式

时间:2021-12-11 16:25:53

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;
}
}

<?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="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;
@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映射文件

<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>

 

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