mybatis
一,mytatis是什么
mybatis是一個持久層框架,其作用是:ORM將sql語句映射成實體類
特點:
1,簡單易學:本身就很小且簡單。沒有任何第三方依賴,最簡單安裝只要兩個jar文件+配置幾個sql映射文件易于學習,易于使用,通過文檔和源代碼,可以比較完全的掌握它的設計思路和實現。
2,靈活:mybatis不會對應用程序或者數據庫的現有設計強加任何影響。 sql寫在xml里,便于統一管理和優化。通過sql基本上可以實現我們不使用數據訪問框架可以實現的所有功能,或許更多。
3,解除sql與程序代碼的耦合:通過提供DAL層,將業務邏輯和數據訪問邏輯分離,使系統的設計更清晰,更易維護,更易單元測試。sql和代碼的分離,提高了可維護性。
4,提供映射標簽,支持對象與數據庫的orm字段關系映射
5,提供對象關系映射標簽,支持對象關系組建維護
6,提供xml標簽,支持編寫動態sql。
二,使用idea創建maven項目入門mybatis
1、創建mybatis-config.xml文件
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
<environments default="development">
<environment id="development">
<!--事務管理器-->
<transactionManager type="JDBC"/>
<!--數據源-->
<dataSource type="POOLED">
<property name="driver" value="com.mysql.jdbc.Driver"/>
<property name="url" value="jdbc:mysql:///world?useUnicode=true&characterEncoding=utf-8"/>
<property name="username" value="root"/>
<property name="password" value="12345678"/>
</dataSource>
</environment>
</environments>
<mappers>
<mapper resource="UserMapper.xml"/>
</mappers>
</configuration>
2、創建映射文件UserMapper.xml
?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="org.mybatis.example.BlogMapper">
<select id="selectBlog" resultType="com.tao.bean.User">
select * from user where uid = 1
</select>
</mapper>
3、獲取xml配置文件
InputStream inputStream = Resources.getResourceAsStream("mybatis-config.xml");
4、創建SqlSessionFactory
SqlSessionFactory factory=new SqlSessionFactoryBuilder().build(inputStream);
5、獲取SqlSession
SqlSession sqlSession = factory.openSession();
6、調用SqlSession的selectOne(命名空間.id名稱);
Object object = sqlSession.selectOne("user.selectUser");
7、關閉SqlSession
sqlSession.close();
三,mybatis原生用法
基礎的增刪改查
1,查
//一條
sqlSession.selectOne(sqlId,參數)
//多條
sqlSession.selectlist(sqlId,參數)
2.增