個人筆記,如有錯誤,懇請批評指正。
MyBatis 世界上流行最廣泛的基于SQL語句的ORM框架,由Clinton Begin 在2002 年創建,其后,捐獻給了Apache基金會,成立了iBatis 項目。MyBatis 本是apache的一個開源項目iBatis, 2010年這個項目由apache software foundation 遷移到了google code,并且改名為MyBatis 。2013年11月遷移到Github。
a. 學習成本:MyBatis簡單易學(特別是有SQL語法基礎的人),較接近JDBC b. 程序靈活性:MyBatis直接使用SQL,靈活性高 c. 程序執行效律:MyBatis效律高 d. 可移植性:hibernate較好(與數據庫關聯在配置中完成,HQL語句與數據庫無關)
mybatis提供一種“半自動化”的ORM實現。 這里的“半自動化”,是相對Hibernate等提供了全面的數據庫封裝機制的“全自動化”ORM實現而言,“全自動”ORM實現了POJO和數據庫表之間的映射,以及SQL的自動生成和執行。而mybatis的著力點,則在于POJO與SQL之間的映射關系。
MyBatis是一個靈活的DAO層解決方案,滿足較高的性能要求,可以在很多場合使用,但一般以下場合不建議使用: a. 需要支持多種數據庫或數據庫有移植要求 b. 完全動態sql,例如:字段要動態生成 c. 使用的不是關系數據庫
sql映射文件建立了POJO與SQL之間的依賴關系。 此時需要更新myBatis-config.xml中對sql映射配置的應用。 - 修改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"> ………… </environments> <mappers> <mapper resource="cn/itcast/entity/DeptMapper.xml" /> </mappers></configuration>編寫數據庫操作 包括操作接口及實現,接口略,實現類為:DeptDaoImpl.javapublic class DeptDaoImpl { private Sqlsession session = null; /* *1.讀取配置文件信息 *2.構建session工廠 *3.創建session *4.開啟事務 *5.處理數據 *6.提交/回滾數據 *7.關閉session */ @Deprecated public int save(Dept dept){ int i = 0; String path = "mybatis-config.xml"; SqlSession session = null; Reader reader = null; try { reader = Resources.getResourceAsReader(path); SqlSessionFactory sessionFactory = new SqlSessionFactoryBuilder().build(reader); session = sessionFactory.openSession(); //參數1:定義的sql 參數2:sql的值// SQL映射文件定義的命名空間+SQL語句的ID定位SQL語句 i = session.insert("cn.ustb.entity.DeptMapper.insertDept", dept); session.commit(); } catch (Exception e) { e.printStackTrace(); session.rollback(); } finally{ if(reader != null){ try { reader.close(); } catch (IOException e) { e.printStackTrace(); } } if(session != null){ session.close(); } } return i; }編寫測試類 需要導入junit包public class DeptTest { private static DeptDaoImpl deptDaoImpl; @BeforeClass public static void setUpBeforeClass() throws Exception { deptDaoImpl=new DeptDaoImpl(); } @AfterClass public static void tearDownAfterClass() throws Exception { deptDaoImpl=null; } @Test public void testInsert() { Dept dept=new Dept(); dept.setDeptName("市場部"); dept.setDeptAddress("深圳"); int i=deptDaoImpl.insert(dept); System.out.println("受影響行數:"+i); }}在myBatis的主配置文件給cn.itcast.entity.Dept類創建別名Dept,后繼的DeptMapper.xml配置文件中可以使用別名
<!-- 通過別名簡化對類的使用 --><typeAliases> <typeAlias type="cn.ustb.entity.Dept" alias="Dept" /></typeAliases>封裝了獲取及關閉session的操作,并保證在線程池中始終只有一份session,節省了資源。
public class MybatisSessionFactory { private static final ThreadLocal<SqlSession> threadLocal = new ThreadLocal<SqlSession>(); private static SqlSessionFactory sqlSessionFactory = null; private static String CONFIG_FILE_LOCATION = "myBatis-config.xml"; private static String configFile = CONFIG_FILE_LOCATION; static{ buildSessionFactory(); } public static SqlSession getSession() throws Exception{ SqlSession session = threadLocal.get(); if(session == null){ if(sqlSessionFactory == null){ buildSessionFactory(); } session = (sqlSessionFactory!=null)? sqlSessionFactory.openSession():null; threadLocal.set(session); } return session; } public static void closeSession(){ SqlSession session = threadLocal.get(); threadLocal.set(null); if(session != null ){ session.close(); System.out.println("***Success Session Closing***"); } } public static void buildSessionFactory(){ Reader reader = null; try { reader = Resources.getResourceAsReader(CONFIG_FILE_LOCATION); sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader); } catch (Exception e) { e.printStackTrace(); System.out.println("%%%%Create sessionFactory error%%%%"); }finally{ if(reader!=null){ try { reader.close(); System.out.println("***Success reader Closing***"); } catch (Exception e) { System.out.println("%%%% Closing sessionFactory error %%%%"); e.printStackTrace(); } } } }}修改DeptMapper.xml配置insert語句(使用之前配置好的別名)
<!--parameterType="Dept"不寫時,也能自動根據代碼傳遞的參數Dept自動匹配 內容--><insert id="insert" parameterType="Dept"> insert into dept(dept_name) values(#{deptName});</insert>修改DeptDaoImpl.java新增方法(使用MyBatisUtil.java工具類):
public int save2(Dept dept){ int i = 0; SqlSession session = null; try { session = MybatisSessionFactory.getSession(); //參數1:定義的sql 參數2:sql的值 i = session.insert("cn.ustb.entity.DeptMapper.insertDept", dept); session.commit(); } catch (Exception e) { e.printStackTrace(); session.rollback(); } finally{ MybatisSessionFactory.closeSession(); } return i; }修改配置文件deptMapper.xml,添加
<delete id="delete" parameterType="Dept"> delete from dept where dept_id=#{deptId}</delete>修改DeptDaoImpl.java,添加delete方法:
public boolean delete(Integer id){ boolean state = false; try { session = MybatisSessionFactory.getSession(); int i = session.delete("cn.ustb.entity.DeptMapper.deleteDept",id); session.commit(); if(i!=0)state = true; } catch (Exception e) { e.printStackTrace(); session.rollback(); state = false; }finally{ MybatisSessionFactory.closeSession(); } return state;}修改配置文件deptMapper.xml,添加update語句。傳入的值用spel表達式#{}獲取
<update id="update" parameterType="Dept"> update dept set dept_name=#{deptName} ,dept_address=#{deptAddress} where dept_id=#{deptId} </update>修改DeptDaoImpl.java,添加update方法:
public int update (Dept dept){ int i = 0; try { session = MybatisSessionFactory.getSession(); i = session.update("cn.ustb.entity.DeptMapper.updateDept", dept); session.commit();//necessary } catch (Exception e) { e.printStackTrace(); session.rollback(); }finally{ MybatisSessionFactory.closeSession(); } return i;}修改DeptDaoImpl.java,添加selectOne方法:
public Dept selectOne(Integer id){ Dept dept = null; try { session = MybatisSessionFactory.getSession(); dept = session.selectOne("cn.ustb.entity.DeptMapper.selectDept",id); session.commit(); } catch (Exception e) { e.printStackTrace(); session.rollback(); }finally{ MybatisSessionFactory.closeSession(); } return dept;}查詢操作(返回多條記錄) 修改配置文件deptMapper.xml,添加<!-- 返回多條記錄,返回結果配置的不是集合類型,而是集合元素的類型;參數也可以通過Map等方式封裝 --> <!-- 多個查詢 --><!-- 如果返回的是list,resultMap指定的值是list集合里面的類型 --><select id="selectMultiDept" parameterType="String" resultMap="deptResultMap"> select * from dept where dept_address = #{deptAddress}</select><!-- 參數類型用map的多個查詢 --><select id="selectMultiDeptUseMapParamter" parameterType="Map" resultMap="deptResultMap"> select * from dept where dept_address like #{deptAddress}</select>修改DeptDaoImpl.java,添加selectList方法:
public List<Dept> selectMulti(String deptAddress){ List<Dept> list = null; try { session = MybatisSessionFactory.getSession(); list = session.selectList("cn.ustb.entity.DeptMapper.selectMultiDept", deptAddress); session.commit(); } catch (Exception e) { e.printStackTrace(); session.rollback(); } return list; } /* * 模糊查詢在sql中添加like,在傳入條件中添加% */ public List<Dept> selectMultiUserMapParameter(Map deptAddresses){ List<Dept> list = null; try { session = MybatisSessionFactory.getSession(); list = session.selectList("cn.ustb.entity.DeptMapper.selectMultiDeptUseMapParamter", deptAddresses); session.commit(); } catch (Exception e) { e.printStackTrace(); session.rollback(); } return list; }測試類代碼:
@Test public void testSelectList() { Map map=new HashMap(); map.put("deptName", "%研%"); List<Dept> depts=deptDaoImpl.selectList(map); for(Dept dept:depts){ System.out.println("dept:"+dept); }}新聞熱點
疑難解答