閱讀目錄
原始Dao開發需要編寫Dao接口和Dao實現類,步驟如下:
public interface UserDao
{
public User findUserById(int id);
}
public class UserDaoImpl implements UserDao
{
SqlSessionFactory sqlSessionFactory;
public UserDaoImpl(SqlSessionFactory sqlSessionFactory)
{
this.sqlSessionFactory=sqlSessionFactory;
}
@Override
public User findUserById(int id)
{
SqlSession sqlSession=sqlSessionFactory.openSession();
User user=sqlSession.selectOne("test.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="test">
<select id="findUserById" parameterType="int" resultType="com.test.pojo.User">
select * from user where id=#{id}
</select>
</mapper>
<mappers>
<mapper resource="User.xml"/>
</mappers>
原始的Dao開發存在兩個問題:
1、Dao方法體存在重復代碼:通過SqlSessionFactory創建SqlSession。
2、調用sqlSession的數據庫操作方法需要指定statement的id,這裡存在硬編碼,不得於開發維護。
該種方式只需要編寫Mapper接口(相當於Dao接口),由Mybatis框架根據接口定義創建接口的動態代理對象,代理對象的方法體同上面的Dao接口實現類方法。
Mapper接口開發需要遵循的規范:
1、 Mapper.xml文件中的namespace與mapper接口的類路徑相同。
2、 Mapper接口方法名和Mapper.xml中定義的每個statement的id相同。
3、 Mapper接口方法的輸入參數類型和mapper.xml中定義的每個sql 的parameterType的類型相同。
4、 Mapper接口方法的輸出參數類型和mapper.xml中定義的每個sql的resultType的類型相同。
1、Mapper接口
注意:Mapper接口需要滿足上述2、3、4三個條件,內容如下:
2、Mapper.xml映射文件
新建UserMapper.xml文件,內容同User.xml,但是要修改namespace為mapper接口的類路徑。
<mappers>
<mapper resource="UserMapper.xml"/>
</mappers>
public class UserMapperTest
{
private SqlSessionFactory sqlSessionFactory;
@Before
public void setUp() throws IOException
{
String resource="SqlMapConfig.xml";
InputStream inputStream=Resources.getResourceAsStream(resource);
sqlSessionFactory=new SqlSessionFactoryBuilder().build(inputStream);
}
@Test
public void testFindUserById()
{
SqlSession sqlSession=sqlSessionFactory.openSession();
UserMapper userMapper=sqlSession.getMapper(UserMapper.class);
User user=userMapper.findUserById(5);
System.out.println(user);
sqlSession.close();
}
}
MyBatis入門學習教程 http://www.linuxidc.com/Linux/2015-02/113771.htm
Java實戰應用:Mybatis實現單表的增刪改 http://www.linuxidc.com/Linux/2014-06/103456.htm
[Java][Mybatis]物理分頁實現 http://www.linuxidc.com/Linux/2014-04/99889.htm
Mybatis快速入門教程 http://www.linuxidc.com/Linux/2013-06/85762.htm
Mybatis的關於批量數據操作的測試 http://www.linuxidc.com/Linux/2012-05/60863.htm
Mybatis中對List<Object> 對象List的批處理插入操作 http://www.linuxidc.com/Linux/2014-02/96916.htm
MyBatis 的詳細介紹:請點這裡
MyBatis 的下載地址:請點這裡