mybatis获取oracle xmltype_Mybatis【入门】
什么是MyBatis
MyBatis 本是apache的一個開源項目iBatis, 2010年這個項目由apache software foundation 遷移到了google code,并且改名為MyBatis。是一個基于Java的持久層框架
為什么我們要用Mybatis?
無論是Mybatis、Hibernate都是ORM的一種實現框架,都是對JDBC的一種封裝!
這里寫圖片描述到目前為止,我們已經在持久層中學了幾種技術了…
- Hibernate 
- jdbc 
- SpringDAO 
那我們為啥還要學Mybatis呢???現在Mybatis在業內大行其道,那為啥他能那么火呢??
Hibernate是一個比較老舊的框架,用過他的同學都知道,只要你會用,用起來十分舒服…啥sql代碼都不用寫…但是呢,它也是有的缺點::處理復雜業務時,靈活度差, 復雜的HQL難寫難理解,例如多表查詢的HQL語句
而JDBC很容易理解,就那么幾個固定的步驟,就是開發起來太麻煩了,因為什么都要我們自己干..
而SpringDAO其實就是JDBC的一層封裝,就類似于dbutils一樣,沒有特別出彩的地方….
我們可以認為,Mybatis就是jdbc和Hibernate之間的一個平衡點…畢竟現在業界都是用這個框架,我們也不能不學呀!
Mybatis快速入門
其實我們已經學過了Hibernate了,對于Mybatis入門其實就非常類似的。因此就很簡單就能掌握基本的開發了…
導入開發包
導入Mybatis開發包
- mybatis-3.1.1.jar 
- commons-logging-1.1.1.jar 
- log4j-1.2.16.jar 
- cglib-2.2.2.jar 
- asm-3.3.1.jar 
導入mysql/oracle開發包
- mysql-connector-java-5.1.7-bin.jar 
- Oracle 11g 11.2.0.1.0 JDBC_ojdbc6.jar 
準備測試工作
創建一張表
create table students(?id ?int(5) primary key,
?name varchar(10),
?sal double(8,2)
);
創建實體:
/*** Created by ozc on 2017/7/21.
*/
public class Student {
? ?private Integer id;
? ?private String name;
? ?private Double sal;
? ?public Student() {
? ?}
? ?public Integer getId() {
? ? ? ?return id;
? ?}
? ?public void setId(Integer id) {
? ? ? ?this.id = id;
? ?}
? ?public String getName() {
? ? ? ?return name;
? ?}
? ?public void setName(String name) {
? ? ? ?this.name = name;
? ?}
? ?public Double getSal() {
? ? ? ?return sal;
? ?}
? ?public void setSal(Double sal) {
? ? ? ?this.sal = sal;
? ?}
}
創建mybatis配置文件
創建mybatis的配置文件,配置數據庫的信息….數據庫我們可以配置多個,但是默認的只能用一個…
<?xml version="1.0" encoding="UTF-8"?>br />"http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
? ?
? ?<properties resource="db.properties"/>
? ?
? ?<environments default="mysql_developer">
? ? ? ?
? ? ? ?<environment id="mysql_developer">
? ? ? ? ? ?
? ? ? ? ? ?<transactionManager type="jdbc"/>
? ? ? ? ? ?
? ? ? ? ? ?<dataSource type="pooled">
? ? ? ? ? ? ? ?
? ? ? ? ? ? ? ?<property name="driver" value="${mysql.driver}"/>
? ? ? ? ? ? ? ?<property name="url" value="${mysql.url}"/>
? ? ? ? ? ? ? ?<property name="username" value="${mysql.username}"/>
? ? ? ? ? ? ? ?<property name="password" value="${mysql.password}"/>
? ? ? ? ? ?dataSource>
? ? ? ?environment>
? ? ? ?
? ? ? ?<environment id="oracle_developer">
? ? ? ? ? ?
? ? ? ? ? ?<transactionManager type="jdbc"/>
? ? ? ? ? ?
? ? ? ? ? ?<dataSource type="pooled">
? ? ? ? ? ? ? ?
? ? ? ? ? ? ? ?<property name="driver" value="${oracle.driver}"/>
? ? ? ? ? ? ? ?<property name="url" value="${oracle.url}"/>
? ? ? ? ? ? ? ?<property name="username" value="${oracle.username}"/>
? ? ? ? ? ? ? ?<property name="password" value="${oracle.password}"/>
? ? ? ? ? ?dataSource>
? ? ? ?environment>
? ?environments>
configuration>
編寫工具類測試是否獲取到連接
使用Mybatis的API來創建一個工具類,通過mybatis配置文件與數據庫的信息,得到Connection對象
package cn.itcast.javaee.mybatis.util;import java.io.IOException;
import java.io.Reader;
import java.sql.Connection;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
/**
* 工具類
* @author AdminTC
*/
public class MybatisUtil {
? ?private static ThreadLocal threadLocal = new ThreadLocal();private static SqlSessionFactory sqlSessionFactory;/**
? ? * 加載位于src/mybatis.xml配置文件
? ? */static{try {
? ? ? ? ? ?Reader reader = Resources.getResourceAsReader("mybatis.xml");
? ? ? ? ? ?sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader);
? ? ? ?} catch (IOException e) {
? ? ? ? ? ?e.printStackTrace();throw new RuntimeException(e);
? ? ? ?}
? ?}/**
? ? * 禁止外界通過new方法創建
? ? */private MybatisUtil(){}/**
? ? * 獲取SqlSession
? ? */public static SqlSession getSqlSession(){//從當前線程中獲取SqlSession對象
? ? ? ?SqlSession sqlSession = threadLocal.get();//如果SqlSession對象為空if(sqlSession == null){//在SqlSessionFactory非空的情況下,獲取SqlSession對象
? ? ? ? ? ?sqlSession = sqlSessionFactory.openSession();//將SqlSession對象與當前線程綁定在一起
? ? ? ? ? ?threadLocal.set(sqlSession);
? ? ? ?}//返回SqlSession對象return sqlSession;
? ?}/**
? ? * 關閉SqlSession與當前線程分開
? ? */public static void closeSqlSession(){//從當前線程中獲取SqlSession對象
? ? ? ?SqlSession sqlSession = threadLocal.get();//如果SqlSession對象非空if(sqlSession != null){//關閉SqlSession對象
? ? ? ? ? ?sqlSession.close();//分開當前線程與SqlSession對象的關系,目的是讓GC盡早回收
? ? ? ? ? ?threadLocal.remove();
? ? ? ?}
? ?} ? /**
? ? * 測試
? ? */public static void main(String[] args) {
? ? ? ?Connection conn = MybatisUtil.getSqlSession().getConnection();
? ? ? ?System.out.println(conn!=null?"連接成功":"連接失敗");
? ?}
}
創建實體與映射關系文件
配置實體與表的映射關系
<?xml version="1.0" encoding="UTF-8" ?>br />"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="cn.itcast.javaee.mybatis.app04.Student"> ? ?
? ?
? ?<resultMap type="student" id="studentMap">
? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?
? ? ? ?<id property="id" column="id"/>
? ? ? ?<result property="name" column="name"/>
? ? ? ?<result property="sal" column="sal"/>
? ?resultMap>
mapper>
現在我們已經有了Mybatis的配置文件和表與實體之前的映射文件了,因此我們要將配置文件和映射文件關聯起來
? ?<mappers>? ? ? ?<mapper resource="StudentMapper.xml"/>
? ?mappers>
在測試類上,我們是可以獲取得到連接的
這里寫圖片描述編寫DAO
public class StudentDao {? ?public void add(Student student) throws Exception {
? ? ? ?//得到連接對象
? ? ? ?SqlSession sqlSession = MybatisUtil.getSqlSession();
? ? ? ?sqlSession.insert();
? ?}
? ?public static void main(String[] args) throws Exception {
? ? ? ?StudentDao studentDao = new StudentDao();
? ? ? ?Student student = new Student(1, "zhongfucheng", 10000D);
? ? ? ?studentDao.add(student);
? ?}
}
到現在為止,我們實體與表的映射文件僅僅映射了實體屬性與表的字段的關系…
我們在Hibernate中如果想要插入數據什么的,只要調用save()方法就行了。Hibernate是自動化屏蔽掉了數據庫的差異,而我們Mybatis是需要自己手動編寫SQL代碼的…
那么SQL代碼是寫在哪里的呢???明顯地,我們作為一個框架,不可能在程序中寫SQL,我們是在實體與表的映射文件中寫的!
Mybatis實體與表的映射文件中提供了insert標簽【SQL代碼片段】供我們使用
? ?//在JDBC中我們通常使用?號作為占位符,而在Mybatis中,我們是使用#{}作為占位符? ?//parameterType我們指定了傳入參數的類型
? ?//#{}實際上就是調用了Student屬性的get方法
? ?<insert id="add" parameterType="Student">
? ? ? ?INSERT INTO ZHONGFUCHENG.STUDENTS (ID, NAME, SAL) VALUES (#{id},#{name},#{sal});
? ?insert>
在程序中調用映射文件的SQL代碼片段
? ?public void add(Student student) throws Exception {? ? ? ?//得到連接對象
? ? ? ?SqlSession sqlSession = MybatisUtil.getSqlSession();
? ? ? ?try{
? ? ? ? ? ?//映射文件的命名空間.SQL片段的ID,就可以調用對應的映射文件中的SQL
? ? ? ? ? ?sqlSession.insert("StudentID.add", student);
? ? ? ? ? ?sqlSession.commit();
? ? ? ?}catch(Exception e){
? ? ? ? ? ?e.printStackTrace();
? ? ? ? ? ?sqlSession.rollback();
? ? ? ? ? ?throw e;
? ? ? ?}finally{
? ? ? ? ? ?MybatisUtil.closeSqlSession();
? ? ? ?}
? ?}
值得注意的是:Mybatis中的事務是默認開啟的,因此我們在完成操作以后,需要我們手動去提交事務!
Mybatis工作流程
- 通過Reader對象讀取Mybatis配置文件 
- 通過SqlSessionFactoryBuilder對象創建SqlSessionFactory對象 
- 獲取當前線程的SQLSession 
- 事務默認開啟 
- 通過SQLSession讀取映射文件中的操作編號,從而讀取SQL語句 
- 提交事務 
- 關閉資源 
完成CRUD操作
我們在上面中已經簡單知道了Mybatis是怎么使用的以及工作流程了,這次我們使用Mybatis來完成CRUD的操作,再次鞏固Mybatis的開發步驟以及一些細節
包與類之間的結構
這里寫圖片描述增加學生
配置文件
<?xml version="1.0" encoding="UTF-8"?>br />"http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
? ?
? ?<properties resource="db.properties"/>
? ?
? ?<environments default="mysql_developer">
? ? ? ?
? ? ? ?<environment id="mysql_developer">
? ? ? ? ? ?
? ? ? ? ? ?<transactionManager type="jdbc"/>
? ? ? ? ? ?
? ? ? ? ? ?<dataSource type="pooled">
? ? ? ? ? ? ? ?
? ? ? ? ? ? ? ?<property name="driver" value="${mysql.driver}"/>
? ? ? ? ? ? ? ?<property name="url" value="${mysql.url}"/>
? ? ? ? ? ? ? ?<property name="username" value="${mysql.username}"/>
? ? ? ? ? ? ? ?<property name="password" value="${mysql.password}"/>
? ? ? ? ? ?dataSource>
? ? ? ?environment>
? ? ? ?
? ? ? ?<environment id="oracle_developer">
? ? ? ? ? ?
? ? ? ? ? ?<transactionManager type="jdbc"/>
? ? ? ? ? ?
? ? ? ? ? ?<dataSource type="pooled">
? ? ? ? ? ? ? ?
? ? ? ? ? ? ? ?<property name="driver" value="${oracle.driver}"/>
? ? ? ? ? ? ? ?<property name="url" value="${oracle.url}"/>
? ? ? ? ? ? ? ?<property name="username" value="${oracle.username}"/>
? ? ? ? ? ? ? ?<property name="password" value="${oracle.password}"/>
? ? ? ? ? ?dataSource>
? ? ? ?environment>
? ?environments>
? ?<mappers>
? ? ? ?<mapper resource="zhongfucheng/StudentMapper.xml"/>
? ?mappers>
configuration>
映射文件
<mapper namespace="StudentID">
? ?
? ?<resultMap type="zhongfucheng.Student" id="studentMap">
? ? ? ?
? ? ? ?<id property="id" column="id"/>
? ? ? ?<result property="name" column="name"/>
? ? ? ?<result property="sal" column="sal"/>
? ?resultMap>
? ?<insert id="add" parameterType="zhongfucheng.Student">
? ? ? ?INSERT INTO ZHONGFUCHENG.STUDENTS (ID, NAME, SAL) VALUES (#{id},#{name},#{sal});
? ?insert>
mapper>
插入數據
public class StudentDao {? ?public void add(Student student) throws Exception {
? ? ? ?//得到連接對象
? ? ? ?SqlSession sqlSession = MybatisUtil.getSqlSession();
? ? ? ?try{
? ? ? ? ? ?//映射文件的命名空間.SQL片段的ID,就可以調用對應的映射文件中的SQL
? ? ? ? ? ?sqlSession.insert("StudentID.add", student);
? ? ? ? ? ?sqlSession.commit();
? ? ? ?}catch(Exception e){
? ? ? ? ? ?e.printStackTrace();
? ? ? ? ? ?sqlSession.rollback();
? ? ? ? ? ?throw e;
? ? ? ?}finally{
? ? ? ? ? ?MybatisUtil.closeSqlSession();
? ? ? ?}
? ?}
? ?public static void main(String[] args) throws Exception {
? ? ? ?StudentDao studentDao = new StudentDao();
? ? ? ?Student student = new Student(3, "zhong3", 10000D);
? ? ? ?studentDao.add(student);
? ?}
}
這里寫圖片描述
根據ID查詢數據
增加select標簽
? ?? ?<select id="findById" parameterType="int" resultMap="studentMap">
? ? ? ?SELECT * FROM STUDENTS WHERE id = #{id};
? ?select>
查詢出來的結果是一個Student對象,我們調用SelectOne方法
? ?public Student findById(int id) throws Exception {? ? ? ?//得到連接對象
? ? ? ?SqlSession sqlSession = MybatisUtil.getSqlSession();
? ? ? ?try{
? ? ? ? ? ?//映射文件的命名空間.SQL片段的ID,就可以調用對應的映射文件中的SQL
? ? ? ? ? ?return sqlSession.selectOne("StudentID.findById",id);
? ? ? ?}catch(Exception e){
? ? ? ? ? ?e.printStackTrace();
? ? ? ? ? ?sqlSession.rollback();
? ? ? ? ? ?throw e;
? ? ? ?}finally{
? ? ? ? ? ?MybatisUtil.closeSqlSession();
? ? ? ?}
? ?}
? ?public static void main(String[] args) throws Exception {
? ? ? ?StudentDao studentDao = new StudentDao();
? ? ? ?Student student = studentDao.findById(1);
? ? ? ?System.out.println(student.getName());
? ?}
這里寫圖片描述
查詢所有數據
? ?? ?<select id="findAll" resultMap="studentMap">
? ? ? ?SELECT * FROM STUDENTS;
? ?select>
我們查詢出來的結果不單單只有一個對象了,因此我們使用的是SelectList這個方法
?public ListfindAll() throws Exception {? ? ? ?//得到連接對象
? ? ? ?SqlSession sqlSession = MybatisUtil.getSqlSession();
? ? ? ?try{
? ? ? ? ? ?//映射文件的命名空間.SQL片段的ID,就可以調用對應的映射文件中的SQL
? ? ? ? ? ?return sqlSession.selectList("StudentID.findAll");
? ? ? ?}catch(Exception e){
? ? ? ? ? ?e.printStackTrace();
? ? ? ? ? ?sqlSession.rollback();
? ? ? ? ? ?throw e;
? ? ? ?}finally{
? ? ? ? ? ?MybatisUtil.closeSqlSession();
? ? ? ?}
? ?}
? ?public static void main(String[] args) throws Exception {
? ? ? ?StudentDao studentDao = new StudentDao();
? ? ? ?List students = studentDao.findAll();
? ? ? ?System.out.println(students.size());
? ?}
根據id刪除
? ?? ?<delete id="delete" parameterType="int">
? ? ? ?DELETE FROM STUDENTS WHERE id=#{id};
? ?delete>
調用delete方法刪除
? ?public void delete(int id ) throws Exception {? ? ? ?//得到連接對象
? ? ? ?SqlSession sqlSession = MybatisUtil.getSqlSession();
? ? ? ?try{
? ? ? ? ? ?//映射文件的命名空間.SQL片段的ID,就可以調用對應的映射文件中的SQL
? ? ? ? ? ?sqlSession.delete("StudentID.delete", id);
? ? ? ? ? ?sqlSession.commit();
? ? ? ?}catch(Exception e){
? ? ? ? ? ?e.printStackTrace();
? ? ? ? ? ?sqlSession.rollback();
? ? ? ? ? ?throw e;
? ? ? ?}finally{
? ? ? ? ? ?MybatisUtil.closeSqlSession();
? ? ? ?}
? ?}
? ?public static void main(String[] args) throws Exception {
? ? ? ?StudentDao studentDao = new StudentDao();
? ? ? ?studentDao.delete(1);
? ?}
這里寫圖片描述
修改
? ?? ?<update id="update" parameterType="zhongfucheng.Student">
? ? ? ?update students set name=#{name},sal=#{sal} where id=#{id};
? ?update>
查詢出對應的對象,對其進行修改
? ?public void update(Student student ) throws Exception {? ? ? ?//得到連接對象
? ? ? ?SqlSession sqlSession = MybatisUtil.getSqlSession();
? ? ? ?try{
? ? ? ? ? ?//映射文件的命名空間.SQL片段的ID,就可以調用對應的映射文件中的SQL
? ? ? ? ? ?sqlSession.update("StudentID.update", student);
? ? ? ? ? ?sqlSession.commit();
? ? ? ?}catch(Exception e){
? ? ? ? ? ?e.printStackTrace();
? ? ? ? ? ?sqlSession.rollback();
? ? ? ? ? ?throw e;
? ? ? ?}finally{
? ? ? ? ? ?MybatisUtil.closeSqlSession();
? ? ? ?}
? ?}
? ?public static void main(String[] args) throws Exception {
? ? ? ?StudentDao studentDao = new StudentDao();
? ? ? ?Student student = studentDao.findById(2);
? ? ? ?student.setName("fucheng");
? ? ? ?student.setSal(2000D);
? ? ? ?studentDao.update(student);
? ?}
這里寫圖片描述
小細節
? ?--? ? ? ?注意:這個insert/update/delete標簽只是一個模板,在做操作時,其實是以SQL語句為核心的
? ? ? ? ? ? 即在做增/刪/時,insert/update/delete標簽可通用,
? ? ? ? ? ? 但做查詢時只能用select標簽
? ? ? ? ? ? 我們提倡什么操作就用什么標簽
? ?-->
Mybatis分頁
分頁是一個非常實用的技術點,我們也來學習一下使用Mybatis是怎么分頁的…
我們的分頁是需要多個參數的,并不是像我們之前的例子中只有一個參數。當需要接收多個參數的時候,我們使用Map集合來裝載!
? ?public List ?pagination(int start ,int end) throws Exception {? ? ? ?//得到連接對象
? ? ? ?SqlSession sqlSession = MybatisUtil.getSqlSession();
? ? ? ?try{
? ? ? ? ? ?//映射文件的命名空間.SQL片段的ID,就可以調用對應的映射文件中的SQL
? ? ? ? ? ?/**
? ? ? ? ? ? * 由于我們的參數超過了兩個,而方法中只有一個Object參數收集
? ? ? ? ? ? * 因此我們使用Map集合來裝載我們的參數
? ? ? ? ? ? */
? ? ? ? ? ?Map map = new HashMap();
? ? ? ? ? ?map.put("start", start);
? ? ? ? ? ?map.put("end", end);return sqlSession.selectList("StudentID.pagination", map);
? ? ? ?}catch(Exception e){
? ? ? ? ? ?e.printStackTrace();
? ? ? ? ? ?sqlSession.rollback();throw e;
? ? ? ?}finally{
? ? ? ? ? ?MybatisUtil.closeSqlSession();
? ? ? ?}
? ?}public static void main(String[] args) throws Exception {
? ? ? ?StudentDao studentDao = new StudentDao();
? ? ? ?List students = studentDao.pagination(0, 3);for (Student student : students) {
? ? ? ? ? ?System.out.println(student.getId());
? ? ? ?}
? ?}
那么在實體與表映射文件中,我們接收的參數就是map集合
? ?? ?<select id="pagination" parameterType="map" resultMap="studentMap">
? ? ? ?/*根據key自動找到對應Map集合的value*/
? ? ? ?select * from students limit #{start},#{end};
? ?select>
這里寫圖片描述
動態SQL
何為動態SQL??回顧一下我們之前寫的SSH項目中,有多條件查詢的情況,如下圖
這里寫圖片描述我們當時剛開始做的時候,是需要在Controller中判斷SQL是否已經有條件了,因為SQL語句需要拼接起來….這樣干的話,就非常容易出錯的。
如下的代碼,如果有多個條件的話,那么拼接起來很容易出錯!
?public String listUI() {? ? ? ?//查詢語句
? ? ? ?String hql = "FROM Info i ";
? ? ? ?List objectList ?= new ArrayList<>();//根據info是否為null來判斷是否是條件查詢。如果info為空,那么是查詢所有。if (info != null) {if (StringUtils.isNotBlank(info.getTitle())) {
? ? ? ? ? ? ? ?hql += "where i.title like ?";
? ? ? ? ? ? ? ?objectList.add("%" + info.getTitle() + "%");
? ? ? ? ? ?}
? ? ? ?}
? ? ? ?infoList = infoServiceImpl.findObjects(hql,objectList);
? ? ? ?ActionContext.getContext().getContextMap().put("infoTypeMap", Info.INFO_TYPE_MAP);return "listUI";
? ?}
后來,我們覺得這樣不好,于是就專門寫了一個查詢助手類:
package zhongfucheng.core.utils;import java.util.ArrayList;
import java.util.List;
/**
* Created by ozc on 2017/6/7.
*/
public class QueryHelper {
? ?private String fromClause = "";
? ?private String whereClause = "";
? ?private String orderbyClause = "";
? ?private List objectList;public static String ORDER_BY_ASC = "asc";public static String ORDER_BY_DESC = "desc";//FROM子句只出現一次/**
? ? * 構建FROM字句,并設置查詢哪張表
? ? * @param aClass 用戶想要操作的類型
? ? * @param alias ?別名
? ? */public QueryHelper(Class aClass, String alias) {
? ? ? ?fromClause = " ?FROM " + aClass.getSimpleName() + " ?" + alias;
? ?}//WHERE字句可以添加多個條件,但WHERE關鍵字只出現一次/**
? ? * 構建WHERE字句
? ? * @param condition
? ? * @param objects
? ? * @return
? ? */public QueryHelper addCondition(String condition, Object... objects) {//如果已經有字符了,那么就說明已經有WHERE關鍵字了if (whereClause.length() > 0) {
? ? ? ? ? ?whereClause += " AND ?" + condition;
? ? ? ?} else {
? ? ? ? ? ?whereClause += " WHERE" + condition;
? ? ? ?}//在添加查詢條件的時候,?對應的查詢條件值if (objects == null) {
? ? ? ? ? ?objectList = new ArrayList<>();
? ? ? ?}for (Object object : objects) {
? ? ? ? ? ?objectList.add(object);
? ? ? ?}return this;
? ?}/**
? ? *
? ? * @param property 要排序的屬性
? ? * @param order 是升序還是降序
? ? * @return
? ? */public QueryHelper orderBy(String property, String order) {//如果已經有字符了,那么就說明已經有ORDER關鍵字了if (orderbyClause.length() > 0) {
? ? ? ? ? ?orderbyClause += " , ?" + property +" ? " + order;
? ? ? ?} else {
? ? ? ? ? ?orderbyClause += " ?ORDER BY " + property+" ? " + order;
? ? ? ?}return this;
? ?}/**
? ? * 返回HQL語句
? ? */public String returnHQL() {return fromClause + whereClause + orderbyClause;
? ?}/**
? ? * 得到參數列表
? ? * @return
? ? */public List getObjectList() {return objectList;
? ?}
}
這樣一來的話,我們就不用自己手動拼接了,給我們的查詢助手類去拼接就好了。
而如果我們使用Mybatis的話,就可以免去查詢助手類了。因為Mybatis內部就有動態SQL的功能【動態SQL就是自動拼接SQL語句】!
動態查詢
? ?? ?
? ?
? ?<select id="findByCondition" resultMap="studentMap" parameterType="map">
? ? ? ?select * from students
? ? ? ?<where>
? ? ? ? ? ?<if test="name!=null">
? ? ? ? ? ? ? ?and name=#{name}
? ? ? ? ? ?if>
? ? ? ? ? ?<if test="sal!=null">
? ? ? ? ? ? ? ?and sal < #{sal}if>
? ? ? ?where>
? ?select>
查詢出來小于9000塊的人
? public ListfindByCondition(String name,Double sal) throws Exception {? ? ? ?//得到連接對象
? ? ? ?SqlSession sqlSession = MybatisUtil.getSqlSession();
? ? ? ?try{
? ? ? ? ? ?//映射文件的命名空間.SQL片段的ID,就可以調用對應的映射文件中的SQL
? ? ? ? ? ?/**
? ? ? ? ? ? * 由于我們的參數超過了兩個,而方法中只有一個Object參數收集
? ? ? ? ? ? * 因此我們使用Map集合來裝載我們的參數
? ? ? ? ? ? */
? ? ? ? ? ?Map map = new HashMap();
? ? ? ? ? ?map.put("name", name);
? ? ? ? ? ?map.put("sal", sal);return sqlSession.selectList("StudentID.findByCondition", map);
? ? ? ?}catch(Exception e){
? ? ? ? ? ?e.printStackTrace();
? ? ? ? ? ?sqlSession.rollback();throw e;
? ? ? ?}finally{
? ? ? ? ? ?MybatisUtil.closeSqlSession();
? ? ? ?}
? ?}public static void main(String[] args) throws Exception {
? ? ? ?StudentDao studentDao = new StudentDao();
? ? ? ?List students = studentDao.findByCondition(null,9000D);for (Student student : students) {
? ? ? ? ? ?System.out.println(student.getId() + "---" + student.getName() + "----" + student.getSal());
? ? ? ?}
? ?}這里寫圖片描述
動態更新
這里寫圖片描述 ? ?? ?
? ?<update id="updateByConditions" parameterType="map">
? ? ? ?update students
? ? ? ?<set>
? ? ? ? ? ?<if test="name!=null">
? ? ? ? ? ? ? ? name = #{name},
? ? ? ? ? ?if>
? ? ? ? ? ?<if test="sal!=null">
? ? ? ? ? ? ? ? sal = #{sal},
? ? ? ? ? ?if>
? ? ? ?set>
? ? ? ?where id = #{id}
? ?update>
給出三個更新的字段
? ?public void updateByConditions(int id,String name,Double sal) throws Exception {? ? ? ?//得到連接對象
? ? ? ?SqlSession sqlSession = MybatisUtil.getSqlSession();
? ? ? ?try{
? ? ? ? ? ?//映射文件的命名空間.SQL片段的ID,就可以調用對應的映射文件中的SQL
? ? ? ? ? ?/**
? ? ? ? ? ? * 由于我們的參數超過了兩個,而方法中只有一個Object參數收集
? ? ? ? ? ? * 因此我們使用Map集合來裝載我們的參數
? ? ? ? ? ? */
? ? ? ? ? ?Map map = new HashMap();
? ? ? ? ? ?map.put("id", id);
? ? ? ? ? ?map.put("name", name);
? ? ? ? ? ?map.put("sal", sal);
? ? ? ? ? ?sqlSession.update("StudentID.updateByConditions", map);
? ? ? ? ? ?sqlSession.commit();
? ? ? ?}catch(Exception e){
? ? ? ? ? ?e.printStackTrace();
? ? ? ? ? ?sqlSession.rollback();throw e;
? ? ? ?}finally{
? ? ? ? ? ?MybatisUtil.closeSqlSession();
? ? ? ?}
? ?}public static void main(String[] args) throws Exception {
? ? ? ?StudentDao studentDao = new StudentDao();
? ? ? ?studentDao.updateByConditions(2,"haha",500D);
? ?}這里寫圖片描述
動態刪除
這里寫圖片描述以前我們使用JDBC也好,Hibernate也好,想要批量刪除的時候,總是使用的是循環刪除。而我們現在使用的是Mybatis,SQL語句是自己寫的。所以我們可以寫下如下的SQL來進行刪除delete from students where id in (?,?,?,?);
而我們的Mybatis又支持動態SQL,所以刪除起來就非常方便了!
? ?<delete id="deleteByConditions" parameterType="int">? ? ? ?
? ? ? ?delete from students where id in
? ? ? ? <foreach collection="array" open="(" close=")" separator="," item="ids">
? ? ? ? ? ? #{ids}
? ? ? ? foreach>
? ?delete>
刪除編號為2,3,4的記錄
? ?public void deleteByConditions(int... ids) throws Exception {? ? ? ?//得到連接對象
? ? ? ?SqlSession sqlSession = MybatisUtil.getSqlSession();
? ? ? ?try{
? ? ? ? ? ?//映射文件的命名空間.SQL片段的ID,就可以調用對應的映射文件中的SQL
? ? ? ? ? ?/**
? ? ? ? ? ? * 由于我們的參數超過了兩個,而方法中只有一個Object參數收集
? ? ? ? ? ? * 因此我們使用Map集合來裝載我們的參數
? ? ? ? ? ? */
? ? ? ? ? ?sqlSession.delete("StudentID.deleteByConditions", ids);
? ? ? ? ? ?sqlSession.commit();
? ? ? ?}catch(Exception e){
? ? ? ? ? ?e.printStackTrace();
? ? ? ? ? ?sqlSession.rollback();
? ? ? ? ? ?throw e;
? ? ? ?}finally{
? ? ? ? ? ?MybatisUtil.closeSqlSession();
? ? ? ?}
? ?}
? ?public static void main(String[] args) throws Exception {
? ? ? ?StudentDao studentDao = new StudentDao();
? ? ? ?studentDao.deleteByConditions(2,3,4);
? ?}
這里寫圖片描述
動態插入
我們要想動態插入的話,就比其他的DML語句稍微復雜一點,因為它有兩部分是不確定的,平常的SQL語句是這樣的:
insert into student(id,name,sal) values(?,?,?)這里寫圖片描述
SQL代碼塊是不能像之前那樣幫我們自動去除多余的逗號的,因此我們需要使用trim標簽來自己手動去除…
編寫insertSQL語句的時候,不要忘了寫()括號。
? ?? ?<sql id="key">
? ? ? ?<trim suffixOverrides=",">
? ? ? ? ? ?<if test="id!=null">
? ? ? ? ? ? ? ?id,
? ? ? ? ? ?if>
? ? ? ? ? ?<if test="id!=null">
? ? ? ? ? ? ? ?name,
? ? ? ? ? ?if>
? ? ? ? ? ?<if test="id!=null">
? ? ? ? ? ? ? ?sal,
? ? ? ? ? ?if>
? ? ? ?trim>
? ?sql>
? ?<sql id="value">
? ? ? ?<trim suffixOverrides=",">
? ? ? ? ? ?<if test="id!=null">
? ? ? ? ? ? ? ?#{id},
? ? ? ? ? ?if>
? ? ? ? ? ?<if test="id!=null">
? ? ? ? ? ? ? ?#{name},
? ? ? ? ? ?if>
? ? ? ? ? ?<if test="id!=null">
? ? ? ? ? ? ? ?#{sal},
? ? ? ? ? ?if>
? ? ? ?trim>
? ?sql>
? ?
? ?<insert id="insertByConditions" parameterType="zhongfucheng.Student">
? ? ? ?insert into students (<include refid="key"/>) values
? ? ? ?(<include refid="value"/>)
? ?insert>
測試三個不同內容的數據
? ?public void insertByConditions(Student student) throws Exception {? ? ? ?//得到連接對象
? ? ? ?SqlSession sqlSession = MybatisUtil.getSqlSession();
? ? ? ?try{
? ? ? ? ? ?//映射文件的命名空間.SQL片段的ID,就可以調用對應的映射文件中的SQL
? ? ? ? ? ?sqlSession.insert("StudentID.insertByConditions", student);
? ? ? ? ? ?sqlSession.commit();
? ? ? ?}catch(Exception e){
? ? ? ? ? ?e.printStackTrace();
? ? ? ? ? ?sqlSession.rollback();
? ? ? ? ? ?throw e;
? ? ? ?}finally{
? ? ? ? ? ?MybatisUtil.closeSqlSession();
? ? ? ?}
? ?}
? ?public static void main(String[] args) throws Exception {
? ? ? ?StudentDao studentDao = new StudentDao();
? ? ? ?studentDao.insertByConditions(new Student(55, null, null));//name和sal為空
? ? ? ?studentDao.insertByConditions(new Student(66, "haxi", null));//sal為空
? ? ? ?studentDao.insertByConditions(new Student(77, null, 3999d));//name為空
? ?}
這里寫圖片描述
總結
- Mybatis的準備工作與Hibernate差不多,都需要一個總配置文件、一個映射文件。 
- Mybatis的SQLSession工具類使用ThreadLocal來對線程中的Session來進行管理。 
- Mybatis的事務默認是開啟的,需要我們手動去提交事務。 
- Mybatis的SQL語句是需要手寫的,在程序中通過映射文件的命名空間.sql語句的id來進行調用! 
- 在Mybatis中,增刪改查都是需要我們自己寫SQL語句的,然后在程序中調用即可了。SQL由于是我們自己寫的,于是就相對Hibernate靈活一些。 
- 如果需要傳入多個參數的話,那么我們一般在映射文件中用Map來接收。 
- 由于我們在開發中會經常用到條件查詢,在之前,我們是使用查詢助手來幫我們完成對SQL的拼接的。而Mybatis的話,我們是自己手寫SQL代碼的。 
- Mybatis也支持一些判斷標簽,于是我們就可以通過這些標簽來完成動態CRUD的操作了。 
- 值得注意的是,我們的sql片段代碼是需要我們自己手動去分割,號的。 
如果文章有錯的地方歡迎指正,大家互相交流。習慣在微信看技術文章,想要獲取更多的Java資源的同學,可以關注微信公眾號:Java3y
總結
以上是生活随笔為你收集整理的mybatis获取oracle xmltype_Mybatis【入门】的全部內容,希望文章能夠幫你解決所遇到的問題。
 
                            
                        - 上一篇: docker选择安装位置_如何使用doc
- 下一篇: ccd相机好修吗_「CCD购买指南 」C
