Mybatis编写Dao层
主要有一下两种方式
- 原始的dao层开发方式
- mapper代理的方式
原始dao层开发(了解即可)
接口+实现类+映射文件(xml文件)
接口
public interface UserDao {
// 根据id查询用户信息
public User findUserById(int id) throws Exception;
}
实现类
public class UserDaoImpl implements UserDao {
// 需要向dao实现类中注入SqlSessionFactory
// 这里通过构造方法注入
private SqlSessionFactory sqlSessionFactory;
public UserDaoImpl(SqlSessionFactory sqlSessionFactory) {
this.sqlSessionFactory = sqlSessionFactory;
}
@Override
public User findUserById(int id) throws Exception {
SqlSession sqlSession = sqlSessionFactory.openSession();
//这里的test.findUserById是与下面的映射文件user.xml中的namespace+id有关。
User user = sqlSession.selectOne("test.findUserById", id);
// 释放资源
sqlSession.close();
return user;
}
}
映射文件
<mapper namespace="test">
<!-- 由于是传统方法,namespace不需要和接口对应,只需要保证唯一即可 -->
<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;
// 此方法是在执行testFindUserById之前执行
@Before
public void setUp() throws Exception {
// 创建sqlSessionFactory
// mybatis配置文件
String resource = "SqlMapConfig.xml";
// 得到配置文件流
InputStream inputStream = Resources.getResourceAsStream(resource);
// 创建会话工厂,传入mybatis的配置文件信息
sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
}
@Test
public void testUserDaoImpl() throws Exception{
// 创建UserDao的对象
UserDao userDao = new UserDaoImpl(sqlSessionFactory);
// 调用UserDao的方法
User user = userDao.findUserById(1);
System.out.println(user);
}
}
mapper代理
接口+mapper.xml
接口
public interface UserMapper {
// 根据id查询用户信息
public User findUserById(int id) throws Exception;
}
mapper.xml(直接相当于实现类+映射文件)
<mapper namespace="cn.itcast.mybatis.mapper.UserMapper">
<!--通过id查询用户表的记录 -->
<select id="findUserById" parameterType="int" resultType="cn.itcast.mybatis.po.User">
SELECT * FROM USER WHERE id=#{value}
</select>
</mapper>
注意点
- mapper.xml中的namespace必须和和接口的全类名一致
- mapper.xml中的sql(statement)的id必须和和接口中方法名一致
- mapper.xml中的parameterType指定的类型必须和接口中参数一致
- mapper.xml中的resultType指定的类型必须和接口中返回值一致
测试类
public class UserMapperTest {
private SqlSessionFactory sqlSessionFactory;
// 此方法是在执行testFindUserById之前执行
@Before
public void setUp() throws Exception {
// 创建sqlSessionFactory
// mybatis配置文件
String resource = "SqlMapConfig.xml";
// 得到配置文件流
InputStream inputStream = Resources.getResourceAsStream(resource);
// 创建会话工厂,传入mybatis的配置文件信息
sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
}
@Test
public void testFindUserById() throws Exception {
SqlSession sqlSession=sqlSessionFactory.openSession();
//创建UserMapper对象,mybatis自动生成mapper代理对象
UserMapper userMapper =sqlSession.getMapper(UserMapper.class);
//调用UserMapper的方法
User user=userMapper.findUserById(1);
System.out.println(user);
sqlSession.close();
}
}