MyBatis 的簡單應用
阿新 • • 發佈:2019-01-30
介紹
目錄
MyBatis-config.xml 中 set 的說明 []: 表示 可能的不太正確
表,序列 ,儲存過程 的建立
儲存過程
測試
序列
學生表
班級表
mybatis-config.xml
mybatis-config.properties
Student.java
StudentMapper.xml
Classes.java
ClassesMapper.xml
TestStudentAndClasses.java
1.例子中包含了 mybatis 的常用sql的寫法
2.動態sql 的應用
3.儲存過程的使用
目錄
MyBatis-config.xml 中 set 的說明 []: 表示 可能的不太正確
<!-- 配置設定 --> <settings> <!-- 配置全域性性 cache 的 ( 開 / 關) default:true --> <setting name="cacheEnabled" value="true"/> <!-- 是否使用 懶載入 關聯物件 同 hibernate中的延遲載入 一樣 default:true --> <setting name="lazyLoadingEnabled" value="true"/> <!-- [當物件使用延遲載入時 屬性的載入取決於能被引用到的那些延遲屬性,否則,按需載入(需要的是時候才去載入)] --> <setting name="aggressiveLazyLoading" value="true"/> <!-- 是否允許單條sql 返回多個數據集 (取決於驅動的相容性) default:true --> <setting name="multipleResultSetsEnabled" value="true"/> <!-- 是否可以使用列的別名 (取決於驅動的相容性) default:true--> <setting name="useColumnLabel" value="true"/> <!--允許JDBC 生成主鍵。需要驅動器支援。如果設為了true,這個設定將強制使用被生成的主鍵,有一些驅動器不相容不過仍然可以執行。 default:false--> <setting name="useGeneratedKeys" value="false"/> <!--指定 MyBatis 如何自動對映 資料基表的列 NONE:不隱射 PARTIAL:部分 FULL:全部--> <setting name="autoMappingBehavior" value="PARTIAL"/> <!-- 這是預設的執行型別 SIMPLE :簡單 REUSE:執行器可能重複使用prepared statements 語句 BATCH:執行器可以重複執行語句和批量更新 --> <setting name="defaultExecutorType" value="SIMPLE"/> <!-- 設定驅動等待資料響應的超時數 預設沒有設定--> <setting name="defaultStatementTimeout" value="25000"/> <!-- [是否啟用 行內巢狀語句 defaut:false] --> <setting name="safeRowBoundsEnabled" value="false"/> <!-- [是否 啟用 資料中 A_column 自動對映 到 java類中駝峰命名的屬性 default:fasle] --> <setting name="mapUnderscoreToCamelCase" value="false"/> <!-- 設定本地快取範圍 session:就會有資料的共享 statement:語句範圍 (這樣就不會有資料的共享 ) defalut:session --> <setting name="localCacheScope" value="SESSION"/> <!-- 設定但JDBC型別為空時,某些驅動程式 要指定值,default:other --> <setting name="jdbcTypeForNull" value="OTHER"/> <!-- 設定觸發延遲載入的方法 --> <setting name="lazyLoadTriggerMethods" value="equals,clone,hashCode,toString"/> </settings>
表,序列 ,儲存過程 的建立
儲存過程
create or replace procedure pro_getAllStudent
(
v_sid number,
v_sname varchar2,
userList_cursor out sys_refcursor
)
as
begin
update student set sname=v_sname where sid=v_sid;
open userList_cursor for select* from student;
end;
測試
SQL> declare 2 v_student_row student%rowtype; 3 v_sid student.sid%type:=11; 4 v_sname student.sname%type:='張浩'; 5 v_student_rows sys_refcursor; 6 begin 7 pro_getAllStudent(v_sid,v_sname,v_student_rows); 8 loop 9 fetch v_student_rows into v_student_row; 10 exit when v_student_rows%notfound; 11 Dbms_Output.put_line('第'||v_student_rows%rowcount||'行,學生id'||v_student_row.sid||'--姓名:'||v_student_row.sname); 12 end loop; 13 close v_student_rows; 14 end; 15 /
序列
-- Create sequence
create sequence STUDENT_SEQ
minvalue 1
maxvalue 999999999999999999999999999
start with 32
increment by 1
cache 20;
學生表
create table STUDENT ( SID NUMBER(8) primary key not null, SNAME VARCHAR2(20) not null, MAJOR VARCHAR2(100), BIRTH DATE, SCORE NUMBER(6,2), CID NUMBER(8), STATUS CHAR(3) )
班級表
-- Create table
create table CLASSES
(
CID NUMBER(8) primary key not null,
CNAME VARCHAR2(20) not null,
TEACHER VARCHAR2(25),
CREATEDATE DATE
)
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> <!-- 配置的元素順序 properties?, settings?, typeAliases?, typeHandlers?, objectFactory?, objectWrapperFactory?, proxyFactory?, plugins?, environments?, databaseIdProvider?, mappers --> <!-- 使用屬性檔案 而且可以在這裡這是 覆蓋檔案中的值 --> <properties resource="mybatis-config.properties"> <!-- <property name="username" value="admin"/> <property name="password" value="123456"/> --> </properties> <!-- 別名的配置 --> <typeAliases> <typeAlias type="com.mybatis.student.Student" alias="Student"/> <typeAlias type="com.mybatis.classes.Classes" alias="Classes"/> <!-- 也可以使用 包範圍來配置 <package name="com.mybatis"/> --> </typeAliases> <environments default="development"> <environment id="development"> <transactionManager type="JDBC"/> <dataSource type="POOLED"> <property name="driver" value="${driver}"/> <property name="url" value="${url}"/> <property name="username" value="${username}"/> <property name="password" value="${password}"/> </dataSource> </environment> </environments> <mappers> <mapper resource="com/mybatis/student/StudentMapper.xml"/> <mapper resource="com/mybatis/classes/ClassesMapper.xml"/> </mappers> </configuration>
mybatis-config.properties
driver=oracle.jdbc.driver.OracleDriver url=jdbc:oracle:thin:@127.0.0.1:1521:orcl username=luob password=luob
Student.java
package com.mybatis.student;
import java.io.Serializable;
import java.util.Date;
import com.mybatis.classes.Classes;
@SuppressWarnings("serial")
public class Student implements Serializable {
private int sid;
private String sname;
private String major;
private Date birth;
private float score;
private int cid;
private int status;
//get set
StudentMapper.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="com.mybatis.student"> <!-- <!ELEMENT mapper ( cache-ref | cache | resultMap* | parameterMap* | sql* | insert* | update* | delete* | select* )+> --> <!-- 設定快取 如果使用者需要登入 需要設定這種型別 type=org.mybatis.caches.oscache.LoggingOSCache--> <cache eviction="FIFO" readOnly="true" size="256" flushInterval="60000"/> <!-- 定義可以重用的sql 程式碼片段 --> <sql id="studentColumns">sid,sname,score</sql> <!-- 自定義結果集 --> <resultMap type="Student" id="studentResultMap"> <id property="sid" column="SID"/> <result property="sname" column="SNAME"/> <result property="score" column="SCORE"/> </resultMap> <resultMap type="Student" id="studentAllResultMap"> <id property="sid" column="SID"/> <result property="sname" column="SNAME"/> <result property="major" column="MAJOR"/> <result property="birth" column="BIRTH"/> <result property="score" column="SCORE"/> <result property="cid" column="CID"/> <result property="status" column="STATUS"/> </resultMap> <!-- 只用建構函式 建立物件 對於那些 比較少的列 --> <resultMap type="Student" id="studentAndClassesResultMap"> <constructor> <idArg column="SID" javaType="int"/> <arg column="SNAME" javaType="String"/> <arg column="SCORE" javaType="float"/> </constructor> <association property="classes" javaType="Classes" resultMap="com.mybatis.classes.classesResultMap"/> </resultMap> <select id="selectStudentAndClassBySname" parameterType="String" resultMap="studentAndClassesResultMap"> select s.sid,s.sname,s.score,c.cid,c.cname,c.teacher,c.createdate from student s left join classes c on s.cid=c.cid where s.sname=#{sname} </select> <insert id="addStudentBySequence" parameterType="Student" > <selectKey keyProperty="sid" resultType="int" order="BEFORE"> select STUDENT_SEQ.nextVal from dual </selectKey> insert into student(sid,sname,major,birth,score) values (#{sid},#{sname},#{major},#{birth},#{score}) </insert> <insert id="addStudent" parameterType="Student"> insert into student(sid,sname,major,birth,score) values (#{sid},#{sname},#{major},#{birth},#{score}) </insert> <delete id="delStudentById" parameterType="int"> delete student where sid=#{sid} </delete> <select id="queryAllStudent" resultType="Student" useCache="true" flushCache="false" timeout="10000"> select * from student </select> <!-- 引數可以指定一個特定的資料型別 還可以使用自定型別處理: typeHandler=MyTypeHandler --> <select id="queryStudentByName" resultType="Student" parameterType="String"> select * from student where sname like #{property,javaType=String,jdbcType=VARCHAR} </select> <!-- 引數可以指定一個特定的資料型別 對於數字型別 ,numericScale=2 用於設定小數型別 --> <select id="queryStudentById" resultType="Student" parameterType="int"> select * from student where sid=#{property,javaType=int,jdbcType=NUMERIC} </select> <update id="updStudentById" parameterType="Student"> update student <trim prefix="SET" suffixOverrides=","> <if test="sname !=null">sname=#{sname},</if> <if test="major !=null">majoir=#{major},</if> <if test="birth !=null">birth=#{birth},</if> <if test="score !=null">score=#{score}</if> </trim> where sid=#{sid} </update> <!-- 在這裡 利用了 可重用的sql程式碼片段 --> <select id="selectMapResult" resultMap="studentResultMap" parameterType="String"> select <include refid="studentColumns"/> from STUDENT where sname like #{sname} </select> <!-- Dynamic Sql 使用 if --> <select id="selectStudentByDynamicSql" parameterType="Student" resultType="Student"> select * from student <where> <if test="sname !=null"> sname like #{sname} </if> <if test="sid !=null"> AND sid=#{sid} </if> </where> </select> <!-- 採用 OGNL 表示式 來配置動態sql 使用trim 去掉 where 中多餘的 and 或者 or where choose when otherwise--> <select id="selectStudentByDynamicSqlChoose" parameterType="Student" resultType="Student"> select * from student <trim prefix="WHERE" prefixOverrides="AND | OR "> <choose> <when test=" sname !=null and sname.length() >0 "> sname like #{sname} </when> <when test="sid !=null and sid>0"> AND sid = #{sid} </when> <otherwise> AND status='1' </otherwise> </choose> </trim> </select> <!-- 使用foreach 遍歷list 只能小寫--> <select id="selectStudentByIds" resultType="Student"> select * from student where sid in <foreach collection="list" item="itm" index="index" open="(" separator="," close=")"> #{itm} </foreach> </select> <!-- 使用foreach 遍歷arry 只能小寫 --> <select id="selectStudentByIdArray" resultType="Student"> select * from student where sid in <foreach collection="array" item="itm" index="index" open="(" separator="," close=")"> #{itm} </foreach> </select> <parameterMap type="map" id="procedureParam"> <parameter property="sid" javaType="int" jdbcType="NUMERIC" mode="IN" /> <parameter property="sname" javaType="String" jdbcType="VARCHAR" mode="IN" /> <parameter property="studentList" javaType="ResultSet" jdbcType="CURSOR" mode="OUT" resultMap="studentAllResultMap"/> </parameterMap> <!--傳入map集合引數 ,呼叫 待用遊標儲存過程(先執行 修改後然後查詢所有) --> <select id="getAllStudentAfterupdate" statementType="CALLABLE" useCache="true" parameterMap="procedureParam"> {call LUOB.pro_getallstudent(?,?,?)} </select> </mapper>
Classes.java
package com.mybatis.classes;
import java.sql.Date;
import java.util.List;
import com.mybatis.student.Student;
public class Classes {
private int cid;
private String cname;
private String teacher;
private Date createDate;
private List<Student> students;
//get set
ClassesMapper.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="com.mybatis.classes"> <!-- 設定 快取共享 --> <cache-ref namespace="com.mybatis.student"/> <resultMap type="Classes" id="classesResultMap"> <id column="CID" property="cid"/> <result column="CNAME" property="cname"/> <result column="TEACHER" property="teacher"/> <result column="CREATEDATE" property="createDate"/> </resultMap> <!-- columnPrefix:別名字首 --> <resultMap type="Classes" id="classesAndStudentListResultMap"> <id column="CID" property="cid"/> <result column="CNAME" property="cname"/> <result column="TEACHER" property="teacher"/> <result column="CREATEDATE" property="createDate"/> <collection property="students" ofType="Student" resultMap="com.mybatis.student.studentResultMap" columnPrefix="stu_"/> </resultMap> <!-- 下面採用了 別名 stu_ 來區分列名 --> <select id="selectClassAndStudentListById" resultMap="classesAndStudentListResultMap" parameterType="int"> select c.cid, c.cname, c.teacher, c.createdate, s.sid stu_sid, s.sname stu_sname, s.score stu_score from student s right join classes c on s.cid=c.cid where c.cid=#{cid} </select> </mapper>
TestStudentAndClasses.java
package com.mybatis.student;
import java.io.IOException;
import java.io.Reader;
import java.sql.CallableStatement;
import java.sql.Connection;
import java.sql.Date;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.junit.Before;
import org.junit.Test;
import com.mybatis.classes.Classes;
public class TestStudentAndClasses {
private SqlSessionFactory sqlSessionFactory;
@Before
public void init() throws IOException{
Reader reader = Resources.getResourceAsReader("mybatis-config.xml");
sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader);
}
/**
* 測試新增 手動給 sid
*/
@Test
public void testAddStudent(){
SqlSession session=sqlSessionFactory.openSession();
Student student =new Student();
student.setSid(35);
student.setSname("Guider");
student.setScore(100);
student.setMajor("Games");
student.setBirth(Date.valueOf("2008-08-08"));
session.insert("com.mybatis.student.addStudent", student);
session.commit();
session.close();
}
/**
* 測試新增 採用序列 給sid
*/
@Test
public void testAddStudentBySequence(){
SqlSession session=sqlSessionFactory.openSession();
Student student =new Student();
student.setSname("Provdwer");
student.setScore(100);
student.setMajor("Games");
student.setBirth(Date.valueOf("2008-08-08"));
session.insert("com.mybatis.student.addStudentBySequence", student);
session.commit();
session.close();
}
/**
* 測試刪除
*/
@Test
public void testDelStudentById(){
SqlSession session=sqlSessionFactory.openSession();
session.delete("com.mybatis.student.delStudentById", 12);
session.commit();
session.close();
}
/**
* 測試根據 sid更新
*/
@Test
public void testUpdStudentById(){
SqlSession session=sqlSessionFactory.openSession();
Student student =new Student();
student.setSid(0);
student.setSname("Sandy");
student.setScore(100);
student.setMajor("sandy");
student.setBirth(Date.valueOf("2008-08-08"));
session.update("com.mybatis.student.addStudentBySequence", student);
session.commit();
session.close();
}
/**
* 測試查詢所有
*/
@Test
public void testQueryAllStudent(){
List<Student> stuList=new ArrayList<Student>();
SqlSession session=sqlSessionFactory.openSession();
stuList=session.selectList("com.mybatis.student.queryAllStudent");
session.commit();
session.close();
for (Student student : stuList) {
System.out.println(student);
}
}
/**
* 測試根據 name 模糊查詢
*/
@Test
public void testQueryStudentByName(){
List<Student> stuList=new ArrayList<Student>();
SqlSession session=sqlSessionFactory.openSession();
stuList=session.selectList("com.mybatis.student.queryStudentByName","%l%");
session.commit();
session.close();
for (Student student : stuList) {
System.out.println(student);
}
}
/**
* 測個根據sid查詢一個物件
*/
@Test
public void testQueryStudentById(){
SqlSession session=sqlSessionFactory.openSession();
Student student=(Student)session.selectOne("com.mybatis.student.queryStudentById",1);
session.close();
System.out.println(student);
}
/**
* 測試 使用resultMap 自定返回值集合
*/
@Test
public void testStudentResultMap(){
List<Student> stuList=new ArrayList<Student>();
SqlSession session=sqlSessionFactory.openSession();
stuList=session.selectList("com.mybatis.student.selectMapResult","%l%");
session.close();
for (Student student : stuList) {
System.out.println(student);
}
}
/**
* 測試 左連線查 一對一 的 關係
*/
@Test
public void testSelectStudentAndClassBySname(){
List<Student> stuList=new ArrayList<Student>();
SqlSession session=sqlSessionFactory.openSession();
stuList=session.selectList("com.mybatis.student.selectStudentAndClassBySname","luob");
session.close();
for (Student student : stuList) {
System.out.println(student+"//--"+student.getClasses());
}
}
/**
* 測試 多對一的 關係的 右連線的查詢
*/
@Test
public void testSelectClassAndStudentListById(){
SqlSession session=sqlSessionFactory.openSession();
Classes classes=(Classes)session.selectOne("com.mybatis.classes.selectClassAndStudentListById",1);
session.close();
System.out.println(classes);
for (Student student : classes.getStudents()) {
System.out.println(student+"//--"+student.getClasses());
}
}
/**
* 測試 動態sql 的 應用 where if ognl
*/
@Test
public void testSelectStudentByDynamicSql(){
Student pstudent=new Student();
pstudent.setSid(1);
List<Student> stuList=new ArrayList<Student>();
SqlSession session=sqlSessionFactory.openSession();
stuList=session.selectList("com.mybatis.student.selectStudentByDynamicSql",pstudent);
session.close();
for (Student student : stuList) {
System.out.println(student+"//--"+student.getClasses());
}
}
/**
* 測試 動態sql 的choose where when otherwise
*/
@Test
public void testSelectStudentByDynamicSqlChoose(){
Student pstudent=new Student();
pstudent.setSid(1);
//pstudent.setSname("luob");
List<Student> stuList=new ArrayList<Student>();
SqlSession session=sqlSessionFactory.openSession();
stuList=session.selectList("com.mybatis.student.selectStudentByDynamicSqlChoose",pstudent);
session.close();
for (Student student : stuList) {
System.out.println(student+"//--"+student.getClasses());
}
}
/**
* 測試 動態sql 中foreach 的使用 傳入 集合list 引數
*/
@Test
public void testSelectStudentByIds(){
ArrayList<Integer> ids=new ArrayList<Integer>();
ids.add(1);
ids.add(6);
ids.add(21);
ids.add(23);
List<Student> stuList=new ArrayList<Student>();
SqlSession session=sqlSessionFactory.openSession();
stuList=session.selectList("com.mybatis.student.selectStudentByIds",ids);
session.close();
for (Student student : stuList) {
System.out.println(student+"//--"+student.getClasses());
}
}
/**
* 測試 動態sql 中foreach 的使用 傳入 陣列array 引數
*/
@Test
public void testSelectStudentByIdArray(){
List<Student> stuList=new ArrayList<Student>();
Integer[] idArry=new Integer[]{1,6,21,23};
SqlSession session=sqlSessionFactory.openSession();
stuList=session.selectList("com.mybatis.student.selectStudentByIdArray",idArry);
session.close();
for (Student student : stuList) {
System.out.println(student+"//--"+student.getClasses());
}
}
/**
* 測試呼叫 儲存過程 裡面有遊標哦 返回多個結果
*/
@Test
public void testGetAllStudentAfterupdate(){
List<Student> stuList=new ArrayList<Student>();
Map map = new HashMap();
map.put("sid", 10);
map.put("sname", "張翰");
map.put("studentList",stuList);
SqlSession session=sqlSessionFactory.openSession();
session.selectOne("com.mybatis.student.getAllStudentAfterupdate",map);
stuList=(ArrayList<Student>)map.get("studentList");
for (Student student : stuList) {
System.out.println(student+"//--"+student.getClasses());
}
session.close();
}
/**
* 使用jdbc 測試 遊標的建立是否成功
*/
@Test
public void testJdbcProcedure(){
Connection con=null;
try {
Class.forName("oracle.jdbc.driver.OracleDriver");
con=DriverManager.getConnection("jdbc:oracle:thin:@127.0.0.1:1521:orcl","luob","luob");
CallableStatement cs=con.prepareCall("{call LUOB.pro_getallstudent(?,?,?)}");
cs.setInt(1, 10);
cs.setString(2,"張翰");
//!!! 注意這裡 type 在Types中 沒有這個型別
cs.registerOutParameter(3,oracle.jdbc.OracleTypes.CURSOR);
cs.execute();
ResultSet rs=(ResultSet)cs.getObject(3);
while(rs.next()){
Student student=new Student();
student.setSid(rs.getInt(1));
student.setSname(rs.getString(2));
student.setMajor(rs.getString(3));
student.setBirth(rs.getDate(4));
student.setScore(rs.getFloat(5));
student.setCid(rs.getInt(6));
student.setStatus(rs.getInt(7));
System.out.println(student);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}