国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 學院 > 開發設計 > 正文

MyBatis學習筆記(一)

2019-11-08 02:58:12
字體:
來源:轉載
供稿:網友

MyBatis學習筆記(一)

mybatis介紹,快速入門

個人筆記,如有錯誤,懇請批評指正。

1. Mybatis介紹

enter image description here MyBatis 世界上流行最廣泛的基于SQL語句的ORM框架,由Clinton Begin 在2002 年創建,其后,捐獻給了Apache基金會,成立了iBatis 項目。MyBatis 本是apache的一個開源項目iBatis, 2010年這個項目由apache software foundation 遷移到了google code,并且改名為MyBatis 。2013年11月遷移到Github。

2. 與Hibernate比較

a. 學習成本:MyBatis簡單易學(特別是有SQL語法基礎的人),較接近JDBC b. 程序靈活性:MyBatis直接使用SQL,靈活性高 c. 程序執行效律:MyBatis效律高 d. 可移植性:hibernate較好(與數據庫關聯在配置中完成,HQL語句與數據庫無關)

mybatis提供一種“半自動化”的ORM實現。 這里的“半自動化”,是相對Hibernate等提供了全面的數據庫封裝機制的“全自動化”ORM實現而言,“全自動”ORM實現了POJO和數據庫表之間的映射,以及SQL的自動生成和執行。而mybatis的著力點,則在于POJO與SQL之間的映射關系。

3. 適用場所

MyBatis是一個靈活的DAO層解決方案,滿足較高的性能要求,可以在很多場合使用,但一般以下場合不建議使用: a. 需要支持多種數據庫或數據庫有移植要求 b. 完全動態sql,例如:字段要動態生成 c. 使用的不是關系數據庫

4. 開發步驟

新建java項目或WEB項目部署jar包(包括數據庫驅動包):使用MyBatis需要先下載jar包:下載地址http://code.google.com/p/mybatis編寫主配置文件 myBatis-config.xml創建數據庫及表(如已創建,可省略)newfile.sql創建實體類及SQL映射文件 XXXMapper.xml編寫數據庫接口及實現編寫測試類及測試

5. 開發示例

新建項目導包 導入mybatis和數據庫驅動包、日志包(配置日志配置文件)。創建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"><!--事務管理類型主要有jdbc和managed,前者依賴于數據源獲得的連接,后者依賴于容器 --> <transactionManager type="JDBC" /> <dataSource type="POOLED"> <PRoperty name="driver" value="com.MySQL.jdbc.Driver" /> <!-- 如果數據庫設置為UTF-8,則URL參數連接需要添加?useUnicode=true&amp;characterEncoding=UTF-8,如下 --> <property name="url" value="jdbc:mysql://localhost:3306/mybatis?useUnicode=true&amp;characterEncoding=UTF-8" /> <property name="username" value="root" /> <property name="passWord" value="root" /> </dataSource> </environment> </environments></configuration>sql建表drop database if exists mybatis;create database mybatis CHARACTER SET UTF8;use mybatis;create table dept( dept_id int primary key auto_increment, dept_name varchar(50), dept_address varchar(50));insert into dept(dept_name,dept_address) values('研發部一部','北京');insert into dept(dept_name,dept_address) values('研發部二部','廣州');insert into dept(dept_name,dept_address) values('研發部三部','深圳');select * from dept;創建實體類:Dept.java創建SQL映射文件及修改主配置文件 SQL映射文件:DeptMapper.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="cn.itcast.entity.DeptMapper"> <!-- 一般在查詢時使用--> <resultMap type="cn.itcast.entity.Dept" id="deptResultMap"> <id property="deptId" column="dept_id"/> <result property="deptName" column="dept_name"/> <result property="deptAddress" column="dept_address"/> </resultMap> <!-- 定義插入的sql語句,通過命名空間+id方式被定位 --> <insert id="insert" parameterType="cn.itcast.entity.Dept"> insert into dept(dept_name,dept_address) values(#{deptName},#{deptAddress}); </insert></mapper>

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

6. 基本的CRUD操作

準備工作(繼續使用前面的庫表和代碼)別名與自定義別名內置別名 對常用的 java 類型,已經內置了一些別名支持。這些別名都是不區分大小寫的。(詳細參看用戶手冊)

自定義別名

在myBatis的主配置文件給cn.itcast.entity.Dept類創建別名Dept,后繼的DeptMapper.xml配置文件中可以使用別名

<!-- 通過別名簡化對類的使用 --><typeAliases> <typeAlias type="cn.ustb.entity.Dept" alias="Dept" /></typeAliases>

MyBatisUtil工具類

封裝了獲取及關閉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(); } } } }}

新增操作:INSERT

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

刪除操作:DELETE

修改配置文件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;}

修改操作:UPDATE

修改配置文件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;}

查詢操作:SELECT

查詢操作(返回單條記錄) 配置deptMapper.xml文件的resultMap元素及SQL查詢語句<!-- 表字段和實體屬性命名一致時可以不配置 --> <resultMap id="deptResultMap" type="Dept"> <id property="deptId" column="dept_id"/> <result property="deptName" column="dept_name"/> <result property="deptAddress" column="dept_address"/> </resultMap><!—省略其它的配置信息 --> <!—返回單條記錄,表字段和對應實體屬性命名一致時可以不使用resultMap屬性配置,直接使用resultType="返回的全類名或別名",建議使用前者;查詢結果為所有字段時,也可以用*表示 --><!-- 單個查詢 --><!-- *號理論可以,但會降低性能,*轉字段需要過程 --><select id="selectDept" parameterType="integer" resultMap="deptResultMap"><!-- 指定返回的類型,按照Map定義的規則封裝對象 --> select dept_id,dept_name,dept_address from dept where dept_id = #{deptId}</select>

修改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); }}
發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 大宁县| 巴塘县| 临洮县| 屏南县| 黑水县| 包头市| 会同县| 八宿县| 收藏| 寻甸| 和田县| 湖南省| 开封市| 介休市| 彰化县| 花垣县| 满洲里市| 开江县| 福海县| 宁德市| 潞城市| 海晏县| 营口市| 阳江市| 福泉市| 武川县| 陈巴尔虎旗| 兴仁县| 维西| 丽江市| 安龙县| 淄博市| 马山县| 绥化市| 嵊州市| 孝义市| 泸西县| 历史| 从化市| 吴堡县| 遂川县|