MyBatis 的简单应用

介绍
Java代码 复制代码  收藏代码
  1. 1.例子中包含了 mybatis 的常用sql的写法   
  2. 2.动态sql 的应用   
  3. 3.存储过程的使用  
1.例子中包含了 mybatis 的常用sql的写法
2.动态sql 的应用
3.存储过程的使用


目录


MyBatis-config.xml 中 set 的说明 []: 表示 可能的不太正确
Xml代码 复制代码  收藏代码
  1. <!-- 配置设置 -->  
  2.     <settings>  
  3.         <!-- 配置全局性 cache 的 ( 开 / 关) default:true -->  
  4.         <setting name="cacheEnabled" value="true"/>  
  5.            
  6.         <!-- 是否使用 懒加载 关联对象  同 hibernate中的延迟加载 一样  default:true -->  
  7.         <setting name="lazyLoadingEnabled" value="true"/>  
  8.            
  9.         <!-- [当对象使用延迟加载时 属性的加载取决于能被引用到的那些延迟属性,否则,按需加载(需要的是时候才去加载)] -->  
  10.         <setting name="aggressiveLazyLoading" value="true"/>  
  11.            
  12.         <!-- 是否允许单条sql 返回多个数据集  (取决于驱动的兼容性) default:true -->  
  13.         <setting name="multipleResultSetsEnabled" value="true"/>  
  14.            
  15.         <!-- 是否可以使用列的别名 (取决于驱动的兼容性) default:true-->  
  16.         <setting name="useColumnLabel" value="true"/>  
  17.            
  18.         <!--允许JDBC 生成主键。需要驱动器支持。如果设为了true,这个设置将强制使用被生成的主键,有一些驱动器不兼容不过仍然可以执行。  default:false-->  
  19.         <setting name="useGeneratedKeys" value="false"/>  
  20.            
  21.         <!--指定 MyBatis 如何自动映射 数据基表的列 NONE:不隐射 PARTIAL:部分  FULL:全部-->  
  22.         <setting name="autoMappingBehavior" value="PARTIAL"/>  
  23.            
  24.         <!-- 这是默认的执行类型    
  25.             SIMPLE :简单     
  26.             REUSE:执行器可能重复使用prepared statements 语句    
  27.             BATCH:执行器可以重复执行语句和批量更新   
  28.         -->  
  29.         <setting name="defaultExecutorType" value="SIMPLE"/>  
  30.            
  31.         <!-- 设置驱动等待数据响应的超时数  默认没有设置-->  
  32.         <setting name="defaultStatementTimeout" value="25000"/>  
  33.            
  34.         <!-- [是否启用 行内嵌套语句  defaut:false] -->  
  35.         <setting name="safeRowBoundsEnabled" value="false"/>  
  36.            
  37.         <!-- [是否 启用  数据中 A_column 自动映射 到 java类中驼峰命名的属性 default:fasle] -->  
  38.         <setting name="mapUnderscoreToCamelCase" value="false"/>  
  39.            
  40.         <!-- 设置本地缓存范围 session:就会有数据的共享  statement:语句范围 (这样就不会有数据的共享 ) defalut:session -->  
  41.         <setting name="localCacheScope" value="SESSION"/>  
  42.            
  43.         <!-- 设置但JDBC类型为空时,某些驱动程序 要指定值,default:other -->  
  44.         <setting name="jdbcTypeForNull" value="OTHER"/>  
  45.            
  46.         <!-- 设置触发延迟加载的方法  -->  
  47.         <setting name="lazyLoadTriggerMethods" value="equals,clone,hashCode,toString"/>  
  48.            
  49.     </settings>  


表,序列 ,存储过程 的创建

存储过程
Java代码 复制代码  收藏代码
  1. create or replace procedure pro_getAllStudent   
  2. (   
  3. v_sid number,   
  4. v_sname varchar2,   
  5. userList_cursor out sys_refcursor   
  6. )   
  7. as   
  8. begin   
  9.   update student set sname=v_sname where sid=v_sid;   
  10.   open userList_cursor for select* from student;   
  11. end;  
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;


测试
Java代码 复制代码  收藏代码
  1. SQL> declare   
  2.   2  v_student_row student%rowtype;   
  3.   3  v_sid student.sid%type:=11;   
  4.   4  v_sname student.sname%type:='张浩';   
  5.   5  v_student_rows sys_refcursor;   
  6.   6  begin   
  7.   7  pro_getAllStudent(v_sid,v_sname,v_student_rows);   
  8.   8  loop   
  9.   9  fetch v_student_rows into v_student_row;   
  10.  10  exit when v_student_rows%notfound;   
  11.  11  Dbms_Output.put_line('第'||v_student_rows%rowcount||'行,学生id'||v_student_row.sid||'--姓名:'||v_student_row.sname);   
  12.  12  end loop;   
  13.  13  close v_student_rows;   
  14.  14  end;   
  15.  15  /  
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  /

序列
Java代码 复制代码  收藏代码
  1. -- Create sequence    
  2. create sequence STUDENT_SEQ   
  3. minvalue 1  
  4. maxvalue 999999999999999999999999999  
  5. start with 32  
  6. increment by 1  
  7. cache 20;  
-- Create sequence 
create sequence STUDENT_SEQ
minvalue 1
maxvalue 999999999999999999999999999
start with 32
increment by 1
cache 20;


学生表
Java代码 复制代码  收藏代码
  1.   
  2. create table STUDENT   
  3. (   
  4.   SID    NUMBER(8) primary key not null,   
  5.   SNAME  VARCHAR2(20) not null,   
  6.   MAJOR  VARCHAR2(100),   
  7.   BIRTH  DATE,   
  8.   SCORE  NUMBER(6,2),   
  9.   CID    NUMBER(8),   
  10.   STATUS CHAR(3)   
  11. )  
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)
)


班级表
Java代码 复制代码  收藏代码
  1. -- Create table   
  2. create table CLASSES   
  3. (   
  4.   CID        NUMBER(8) primary key  not null,   
  5.   CNAME      VARCHAR2(20) not null,   
  6.   TEACHER    VARCHAR2(25),   
  7.   CREATEDATE DATE   
  8. )  
-- 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代码 复制代码  收藏代码
  1. <?xml version="1.0" encoding="UTF-8"?>  
  2. <!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN"   
  3.   "http://mybatis.org/dtd/mybatis-3-config.dtd">  
  4. <configuration>  
  5.   
  6.     <!-- 配置的元素顺序 properties?, settings?, typeAliases?, typeHandlers?,    
  7.     objectFactory?, objectWrapperFactory?, proxyFactory?, plugins?,    
  8.     environments?, databaseIdProvider?, mappers -->  
  9.         
  10.     <!-- 使用属性文件 而且可以在这里这是 覆盖文件中的值 -->  
  11.     <properties resource="mybatis-config.properties">  
  12.         <!--    
  13.         <property name="username" value="admin"/>  
  14.         <property name="password" value="123456"/>  
  15.          -->  
  16.     </properties>  
  17.       
  18.        
  19.     <!-- 别名的配置 -->  
  20.     <typeAliases>  
  21.         <typeAlias type="com.mybatis.student.Student" alias="Student"/>  
  22.         <typeAlias type="com.mybatis.classes.Classes" alias="Classes"/>  
  23.         <!--    
  24.             也可以使用 包范围来配置   
  25.             <package name="com.mybatis"/>  
  26.          -->  
  27.     </typeAliases>  
  28.        
  29.     <environments default="development">  
  30.         <environment id="development">  
  31.             <transactionManager type="JDBC"/>  
  32.             <dataSource type="POOLED">  
  33.                 <property name="driver" value="${driver}"/>  
  34.                 <property name="url" value="${url}"/>  
  35.                 <property name="username" value="${username}"/>  
  36.                 <property name="password" value="${password}"/>  
  37.             </dataSource>  
  38.         </environment>  
  39.     </environments>  
  40.        
  41.     <mappers>  
  42.         <mapper resource="com/mybatis/student/StudentMapper.xml"/>  
  43.         <mapper resource="com/mybatis/classes/ClassesMapper.xml"/>  
  44.     </mappers>  
  45.        
  46. </configuration>  


mybatis-config.properties
Xml代码 复制代码  收藏代码
  1. driver=oracle.jdbc.driver.OracleDriver   
  2. url=jdbc:oracle:thin:@127.0.0.1:1521:orcl   
  3. username=luob  
  4. password=luob  


Student.java
Java代码 复制代码  收藏代码
  1. package com.mybatis.student;   
  2.   
  3. import java.io.Serializable;   
  4. import java.util.Date;   
  5.   
  6. import com.mybatis.classes.Classes;   
  7.   
  8. @SuppressWarnings("serial")   
  9. public class Student implements Serializable {   
  10. private int sid;   
  11. private String sname;   
  12. private String major;   
  13. private Date birth;   
  14. private float score;   
  15. private int cid;   
  16. private int status;   
  17. //get set  
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代码 复制代码  收藏代码
  1. <?xml version="1.0" encoding="UTF-8"?>  
  2. <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"   
  3.  "http://mybatis.org/dtd/mybatis-3-mapper.dtd">  
  4.  <mapper namespace="com.mybatis.student">  
  5.     <!-- <!ELEMENT mapper (   
  6.         cache-ref | cache | resultMap* | parameterMap* | sql*    
  7.         | insert* | update* | delete* | select* )+> -->  
  8.        
  9.     <!-- 设置缓存 如果用户需要登录 需要设置这种类型 type=org.mybatis.caches.oscache.LoggingOSCache-->  
  10.     <cache eviction="FIFO" readOnly="true" size="256" flushInterval="60000"/>  
  11.         
  12.     <!-- 定义可以重用的sql 代码片段  -->  
  13.     <sql id="studentColumns">sid,sname,score</sql>  
  14.   
  15.     <!-- 自定义结果集 -->      
  16.     <resultMap type="Student" id="studentResultMap">  
  17.         <id property="sid" column="SID"/>  
  18.         <result property="sname" column="SNAME"/>  
  19.         <result property="score" column="SCORE"/>  
  20.     </resultMap>  
  21.        
  22.     <resultMap type="Student" id="studentAllResultMap">  
  23.         <id property="sid" column="SID"/>  
  24.         <result property="sname" column="SNAME"/>  
  25.         <result property="major" column="MAJOR"/>  
  26.         <result property="birth" column="BIRTH"/>  
  27.         <result property="score" column="SCORE"/>  
  28.         <result property="cid" column="CID"/>  
  29.         <result property="status" column="STATUS"/>  
  30.     </resultMap>  
  31.        
  32.     <!-- 只用构造函数 创建对象 对于那些 比较少的列 -->  
  33.     <resultMap type="Student" id="studentAndClassesResultMap">  
  34.         <constructor>  
  35.             <idArg column="SID" javaType="int"/>  
  36.             <arg column="SNAME" javaType="String"/>  
  37.             <arg column="SCORE" javaType="float"/>  
  38.         </constructor>  
  39.         <association property="classes" javaType="Classes" resultMap="com.mybatis.classes.classesResultMap"/>  
  40.     </resultMap>  
  41.     
  42.     
  43.     <select id="selectStudentAndClassBySname" parameterType="String" resultMap="studentAndClassesResultMap">  
  44.         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}   
  45.     </select>  
  46.     
  47.     <insert id="addStudentBySequence" parameterType="Student" >  
  48.     <selectKey keyProperty="sid" resultType="int" order="BEFORE">  
  49.         select STUDENT_SEQ.nextVal from dual   
  50.     </selectKey>  
  51.         insert into student(sid,sname,major,birth,score)   
  52.         values (#{sid},#{sname},#{major},#{birth},#{score})   
  53.     </insert>  
  54.        
  55.     <insert id="addStudent" parameterType="Student">  
  56.         insert into student(sid,sname,major,birth,score)   
  57.         values (#{sid},#{sname},#{major},#{birth},#{score})   
  58.     </insert>  
  59.        
  60.     <delete id="delStudentById" parameterType="int">  
  61.         delete student where sid=#{sid}   
  62.     </delete>  
  63.        
  64.     <select id="queryAllStudent" resultType="Student" useCache="true" flushCache="false" timeout="10000">  
  65.         select * from student   
  66.     </select>  
  67.        
  68.     <!-- 参数可以指定一个特定的数据类型  还可以使用自定类型处理: typeHandler=MyTypeHandler -->  
  69.     <select id="queryStudentByName" resultType="Student" parameterType="String">  
  70.         select * from student where sname like #{property,javaType=String,jdbcType=VARCHAR}   
  71.     </select>  
  72.        
  73.     <!-- 参数可以指定一个特定的数据类型 对于数字类型 ,numericScale=2  用于设置小数类型  -->  
  74.     <select id="queryStudentById" resultType="Student" parameterType="int">  
  75.         select * from student where sid=#{property,javaType=int,jdbcType=NUMERIC}   
  76.     </select>  
  77.        
  78.        
  79.     <update id="updStudentById" parameterType="Student">  
  80.         update student    
  81.         <trim prefix="SET" suffixOverrides=",">  
  82.             <if test="sname !=null">sname=#{sname},</if>  
  83.             <if test="major !=null">majoir=#{major},</if>  
  84.             <if test="birth !=null">birth=#{birth},</if>  
  85.             <if test="score !=null">score=#{score}</if>  
  86.         </trim>  
  87.         where sid=#{sid}   
  88.     </update>  
  89.        
  90.     <!-- 在这里 利用了 可重用的sql代码片段 -->  
  91.     <select id="selectMapResult" resultMap="studentResultMap" parameterType="String">  
  92.         select <include refid="studentColumns"/> from STUDENT where sname like #{sname}   
  93.     </select>    
  94.        
  95.     <!-- Dynamic  Sql 使用  if -->  
  96.     <select id="selectStudentByDynamicSql" parameterType="Student" resultType="Student">  
  97.         select * from student    
  98.         <where>  
  99.             <if test="sname !=null">  
  100.                 sname like #{sname}   
  101.             </if>  
  102.             <if test="sid !=null">  
  103.                 AND sid=#{sid}   
  104.             </if>  
  105.         </where>  
  106.     </select>  
  107.        
  108.     <!-- 采用 OGNL 表达式  来配置动态sql 使用trim 去掉 where 中多余的  and 或者 or  where  choose  when otherwise-->  
  109.     <select id="selectStudentByDynamicSqlChoose" parameterType="Student" resultType="Student">  
  110.         select * from student    
  111.         <trim prefix="WHERE" prefixOverrides="AND | OR ">  
  112.             <choose>  
  113.                 <when test=" sname !=null and sname.length() >0 ">    
  114.                     sname like #{sname}   
  115.                 </when>  
  116.                 <when test="sid !=null and sid>0">  
  117.                     AND sid = #{sid}   
  118.                 </when>  
  119.                 <otherwise>  
  120.                     AND status='1'  
  121.                 </otherwise>  
  122.             </choose>  
  123.         </trim>  
  124.     </select>  
  125.        
  126.     <!-- 使用foreach 遍历list  只能小写-->  
  127.     <select id="selectStudentByIds" resultType="Student">  
  128.         select * from student    
  129.         where sid in   
  130.         <foreach collection="list" item="itm" index="index" open="(" separator="," close=")">  
  131.             #{itm}   
  132.         </foreach>  
  133.     </select>  
  134.        
  135.     <!-- 使用foreach 遍历arry 只能小写 -->  
  136.     <select id="selectStudentByIdArray" resultType="Student">  
  137.         select * from student    
  138.         where sid in   
  139.         <foreach collection="array" item="itm" index="index" open="(" separator="," close=")">  
  140.             #{itm}   
  141.         </foreach>  
  142.     </select>  
  143.        
  144.     <parameterMap type="map" id="procedureParam">  
  145.         <parameter property="sid" javaType="int" jdbcType="NUMERIC" mode="IN" />  
  146.         <parameter property="sname" javaType="String" jdbcType="VARCHAR" mode="IN" />  
  147.         <parameter property="studentList" javaType="ResultSet" jdbcType="CURSOR" mode="OUT" resultMap="studentAllResultMap"/>    
  148.     </parameterMap>  
  149.     <!--传入map集合参数 ,调用  待用游标存储过程(先执行 修改后然后查询所有)  -->  
  150.     <select id="getAllStudentAfterupdate" statementType="CALLABLE" useCache="true" parameterMap="procedureParam">  
  151.         {call LUOB.pro_getallstudent(?,?,?)}   
  152.     </select>  
  153.        
  154.       
  155.  </mapper>  


Classes.java
Java代码 复制代码  收藏代码
  1. package com.mybatis.classes;   
  2.   
  3. import java.sql.Date;   
  4. import java.util.List;   
  5.   
  6. import com.mybatis.student.Student;   
  7.   
  8. public class Classes {   
  9.     private int cid;   
  10.     private String cname;   
  11.     private String teacher;   
  12.     private Date createDate;   
  13.   
  14.     private List<Student> students;   
  15.     //get set   
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代码 复制代码  收藏代码
  1. <?xml version="1.0" encoding="UTF-8"?>  
  2. <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"   
  3.  "http://mybatis.org/dtd/mybatis-3-mapper.dtd">  
  4.  <mapper namespace="com.mybatis.classes">  
  5.        
  6.     <!-- 设置 缓存共享 -->  
  7.     <cache-ref namespace="com.mybatis.student"/>  
  8.        
  9.     <resultMap type="Classes" id="classesResultMap">  
  10.         <id column="CID" property="cid"/>  
  11.         <result column="CNAME" property="cname"/>  
  12.         <result column="TEACHER" property="teacher"/>  
  13.         <result column="CREATEDATE" property="createDate"/>  
  14.     </resultMap>  
  15.        
  16.     <!-- columnPrefix:别名前缀 -->  
  17.     <resultMap type="Classes" id="classesAndStudentListResultMap">  
  18.         <id column="CID" property="cid"/>  
  19.         <result column="CNAME" property="cname"/>  
  20.         <result column="TEACHER" property="teacher"/>  
  21.         <result column="CREATEDATE" property="createDate"/>  
  22.         <collection property="students" ofType="Student" resultMap="com.mybatis.student.studentResultMap" columnPrefix="stu_"/>  
  23.     </resultMap>  
  24.        
  25.     <!-- 下面采用了 别名 stu_ 来区分列名 -->  
  26.     <select id="selectClassAndStudentListById" resultMap="classesAndStudentListResultMap" parameterType="int">  
  27.         select    
  28.             c.cid,   
  29.             c.cname,   
  30.             c.teacher,   
  31.             c.createdate,   
  32.             s.sid stu_sid,   
  33.             s.sname stu_sname,   
  34.             s.score stu_score   
  35.         from student s right join classes c on s.cid=c.cid where c.cid=#{cid}   
  36.     </select>  
  37.        
  38.  </mapper>  


TestStudentAndClasses.java
Java代码 复制代码  收藏代码
  1. package com.mybatis.student;   
  2.   
  3. import java.io.IOException;   
  4. import java.io.Reader;   
  5. import java.sql.CallableStatement;   
  6. import java.sql.Connection;   
  7. import java.sql.Date;   
  8. import java.sql.DriverManager;   
  9. import java.sql.ResultSet;   
  10. import java.util.ArrayList;   
  11. import java.util.HashMap;   
  12. import java.util.List;   
  13. import java.util.Map;   
  14.   
  15. import org.apache.ibatis.io.Resources;   
  16. import org.apache.ibatis.session.SqlSession;   
  17. import org.apache.ibatis.session.SqlSessionFactory;   
  18. import org.apache.ibatis.session.SqlSessionFactoryBuilder;   
  19. import org.junit.Before;   
  20. import org.junit.Test;   
  21.   
  22. import com.mybatis.classes.Classes;   
  23.   
  24.   
  25. public class TestStudentAndClasses {   
  26.   
  27.     private SqlSessionFactory sqlSessionFactory;   
  28.     @Before  
  29.     public void init() throws IOException{   
  30.         Reader reader = Resources.getResourceAsReader("mybatis-config.xml");    
  31.         sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader);    
  32.     }   
  33.        
  34.     /**  
  35.      * 测试新增  手动给 sid  
  36.      */  
  37.     @Test  
  38.     public void testAddStudent(){   
  39.         SqlSession session=sqlSessionFactory.openSession();   
  40.         Student student =new Student();   
  41.         student.setSid(35);   
  42.         student.setSname("Guider");   
  43.         student.setScore(100);   
  44.         student.setMajor("Games");   
  45.         student.setBirth(Date.valueOf("2008-08-08"));   
  46.         session.insert("com.mybatis.student.addStudent", student);   
  47.         session.commit();   
  48.         session.close();   
  49.     }   
  50.     /**  
  51.      * 测试新增 采用序列 给sid  
  52.      */  
  53.     @Test  
  54.     public void testAddStudentBySequence(){   
  55.         SqlSession session=sqlSessionFactory.openSession();   
  56.         Student student =new Student();   
  57.         student.setSname("Provdwer");   
  58.         student.setScore(100);   
  59.         student.setMajor("Games");   
  60.         student.setBirth(Date.valueOf("2008-08-08"));   
  61.         session.insert("com.mybatis.student.addStudentBySequence", student);   
  62.         session.commit();   
  63.         session.close();   
  64.     }   
  65.        
  66.     /**  
  67.      * 测试删除  
  68.      */  
  69.     @Test  
  70.     public void testDelStudentById(){   
  71.         SqlSession session=sqlSessionFactory.openSession();   
  72.         session.delete("com.mybatis.student.delStudentById"12);   
  73.         session.commit();   
  74.         session.close();   
  75.     }   
  76.        
  77.     /**  
  78.      * 测试根据 sid更新  
  79.      */  
  80.     @Test  
  81.     public void testUpdStudentById(){   
  82.         SqlSession session=sqlSessionFactory.openSession();   
  83.         Student student =new Student();   
  84.         student.setSid(0);   
  85.         student.setSname("Sandy");   
  86.         student.setScore(100);   
  87.         student.setMajor("sandy");   
  88.         student.setBirth(Date.valueOf("2008-08-08"));   
  89.         session.update("com.mybatis.student.addStudentBySequence", student);   
  90.         session.commit();   
  91.         session.close();   
  92.            
  93.     }   
  94.     /**  
  95.      * 测试查询所有  
  96.      */  
  97.     @Test  
  98.     public void testQueryAllStudent(){   
  99.         List<Student> stuList=new ArrayList<Student>();   
  100.         SqlSession session=sqlSessionFactory.openSession();    
  101.         stuList=session.selectList("com.mybatis.student.queryAllStudent");   
  102.         session.commit();   
  103.         session.close();   
  104.         for (Student student : stuList) {   
  105.             System.out.println(student);   
  106.         }   
  107.     }   
  108.        
  109.     /**  
  110.      * 测试根据 name 模糊查询  
  111.      */  
  112.     @Test  
  113.     public void testQueryStudentByName(){   
  114.         List<Student> stuList=new ArrayList<Student>();   
  115.         SqlSession session=sqlSessionFactory.openSession();   
  116.         stuList=session.selectList("com.mybatis.student.queryStudentByName","%l%");   
  117.         session.commit();   
  118.         session.close();   
  119.         for (Student student : stuList) {   
  120.             System.out.println(student);   
  121.         }   
  122.     }   
  123.        
  124.     /**  
  125.      * 测个根据sid查找一个对象  
  126.      */  
  127.     @Test  
  128.     public void testQueryStudentById(){   
  129.         SqlSession session=sqlSessionFactory.openSession();   
  130.         Student student=(Student)session.selectOne("com.mybatis.student.queryStudentById",1);   
  131.         session.close();   
  132.         System.out.println(student);   
  133.     }   
  134.        
  135.     /**  
  136.      * 测试 使用resultMap 自定返回值集合  
  137.      */  
  138.     @Test  
  139.     public void testStudentResultMap(){   
  140.         List<Student> stuList=new ArrayList<Student>();   
  141.         SqlSession session=sqlSessionFactory.openSession();   
  142.         stuList=session.selectList("com.mybatis.student.selectMapResult","%l%");   
  143.         session.close();   
  144.         for (Student student : stuList) {   
  145.             System.out.println(student);   
  146.         }   
  147.     }   
  148.        
  149.     /**  
  150.      * 测试 左连接查  一对一 的 关系  
  151.      */  
  152.     @Test  
  153.     public void testSelectStudentAndClassBySname(){   
  154.         List<Student> stuList=new ArrayList<Student>();   
  155.         SqlSession session=sqlSessionFactory.openSession();   
  156.         stuList=session.selectList("com.mybatis.student.selectStudentAndClassBySname","luob");   
  157.         session.close();   
  158.         for (Student student : stuList) {   
  159.             System.out.println(student+"//--"+student.getClasses());   
  160.         }   
  161.     }   
  162.        
  163.     /**  
  164.      * 测试 多对一的 关系的 右连接的查询  
  165.      */  
  166.     @Test  
  167.     public void testSelectClassAndStudentListById(){   
  168.         SqlSession session=sqlSessionFactory.openSession();   
  169.         Classes classes=(Classes)session.selectOne("com.mybatis.classes.selectClassAndStudentListById",1);   
  170.         session.close();   
  171.         System.out.println(classes);   
  172.         for (Student student : classes.getStudents()) {   
  173.             System.out.println(student+"//--"+student.getClasses());   
  174.         }   
  175.     }   
  176.        
  177.     /**  
  178.      * 测试 动态sql 的 应用 where if  ognl  
  179.      */  
  180.     @Test  
  181.     public void testSelectStudentByDynamicSql(){   
  182.         Student pstudent=new Student();   
  183.         pstudent.setSid(1);   
  184.         List<Student> stuList=new ArrayList<Student>();   
  185.         SqlSession session=sqlSessionFactory.openSession();   
  186.         stuList=session.selectList("com.mybatis.student.selectStudentByDynamicSql",pstudent);   
  187.         session.close();   
  188.         for (Student student : stuList) {   
  189.             System.out.println(student+"//--"+student.getClasses());   
  190.         }   
  191.     }   
  192.        
  193.     /**  
  194.      * 测试 动态sql 的choose  where when otherwise  
  195.      */  
  196.     @Test  
  197.     public void testSelectStudentByDynamicSqlChoose(){   
  198.         Student pstudent=new Student();   
  199.         pstudent.setSid(1);   
  200.         //pstudent.setSname("luob");   
  201.         List<Student> stuList=new ArrayList<Student>();   
  202.         SqlSession session=sqlSessionFactory.openSession();   
  203.         stuList=session.selectList("com.mybatis.student.selectStudentByDynamicSqlChoose",pstudent);   
  204.         session.close();   
  205.         for (Student student : stuList) {   
  206.             System.out.println(student+"//--"+student.getClasses());   
  207.         }   
  208.     }   
  209.        
  210.     /**  
  211.      * 测试 动态sql 中foreach 的使用 传入 集合list 参数   
  212.      */  
  213.     @Test  
  214.     public void testSelectStudentByIds(){   
  215.         ArrayList<Integer> ids=new ArrayList<Integer>();   
  216.         ids.add(1);   
  217.         ids.add(6);   
  218.         ids.add(21);   
  219.         ids.add(23);   
  220.         List<Student> stuList=new ArrayList<Student>();   
  221.   
  222.         SqlSession session=sqlSessionFactory.openSession();   
  223.         stuList=session.selectList("com.mybatis.student.selectStudentByIds",ids);   
  224.         session.close();   
  225.         for (Student student : stuList) {   
  226.             System.out.println(student+"//--"+student.getClasses());   
  227.         }   
  228.            
  229.     }   
  230.     /**  
  231.      * 测试 动态sql 中foreach 的使用 传入 数组array 参数   
  232.      */  
  233.     @Test  
  234.     public void testSelectStudentByIdArray(){   
  235.            
  236.         List<Student> stuList=new ArrayList<Student>();   
  237.         Integer[] idArry=new Integer[]{1,6,21,23};   
  238.         SqlSession session=sqlSessionFactory.openSession();   
  239.         stuList=session.selectList("com.mybatis.student.selectStudentByIdArray",idArry);   
  240.         session.close();   
  241.         for (Student student : stuList) {   
  242.             System.out.println(student+"//--"+student.getClasses());   
  243.         }   
  244.            
  245.     }   
  246.        
  247.     /**  
  248.      * 测试调用 存储过程   里面有游标哦   返回多个结果   
  249.      */  
  250.     @Test  
  251.     public void testGetAllStudentAfterupdate(){   
  252.         List<Student> stuList=new ArrayList<Student>();   
  253.         Map map = new HashMap();   
  254.         map.put("sid"10);   
  255.         map.put("sname""张翰");   
  256.         map.put("studentList",stuList);   
  257.         SqlSession session=sqlSessionFactory.openSession();   
  258.            
  259.         session.selectOne("com.mybatis.student.getAllStudentAfterupdate",map);   
  260.         stuList=(ArrayList<Student>)map.get("studentList");   
  261.         for (Student student : stuList) {   
  262.             System.out.println(student+"//--"+student.getClasses());   
  263.         }   
  264.         session.close();   
  265.     }   
  266.        
  267.     /**  
  268.      * 使用jdbc 测试 游标的创建是否成功   
  269.      */  
  270.     @Test  
  271.     public void testJdbcProcedure(){   
  272.            
  273.         Connection con=null;   
  274.            
  275.         try {   
  276.             Class.forName("oracle.jdbc.driver.OracleDriver");   
  277.             con=DriverManager.getConnection("jdbc:oracle:thin:@127.0.0.1:1521:orcl","luob","luob");   
  278.             CallableStatement cs=con.prepareCall("{call LUOB.pro_getallstudent(?,?,?)}");   
  279.             cs.setInt(110);   
  280.             cs.setString(2,"张翰");   
  281.             //!!! 注意这里 type 在Types中 没有这个类型   
  282.             cs.registerOutParameter(3,oracle.jdbc.OracleTypes.CURSOR);   
  283.             cs.execute();   
  284.             ResultSet rs=(ResultSet)cs.getObject(3);   
  285.             while(rs.next()){   
  286.                 Student student=new Student();   
  287.                 student.setSid(rs.getInt(1));   
  288.                 student.setSname(rs.getString(2));   
  289.                 student.setMajor(rs.getString(3));   
  290.                 student.setBirth(rs.getDate(4));   
  291.                 student.setScore(rs.getFloat(5));   
  292.                 student.setCid(rs.getInt(6));   
  293.                 student.setStatus(rs.getInt(7));   
  294.                 System.out.println(student);   
  295.             }   
  296.                
  297.         } catch (Exception e) {   
  298.             e.printStackTrace();   
  299.         }   
  300.     }   
  301. }  
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();
		}
	}
}

  • 大小: 57 KB
转自 http://takeme.iteye.com/blog/1732801 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值