小男孩‘自慰网亚洲一区二区,亚洲一级在线播放毛片,亚洲中文字幕av每天更新,黄aⅴ永久免费无码,91成人午夜在线精品,色网站免费在线观看,亚洲欧洲wwwww在线观看

分享

MyBatis詳解 與配置MyBatis+Spring+MySql

 昵稱30220109 2016-01-17
MyBatis 是一個(gè)可以自定義SQL、存儲過程和高級映射的持久層框架。MyBatis 摒除了大部分的JDBC代碼、手工設(shè)置參數(shù)和結(jié)果集重獲。MyBatis 只使用簡單的XML 和注解來配置和映射基本數(shù)據(jù)類型、Map 接口和POJO 到數(shù)據(jù)庫記錄。相對Hibernate和Apache OJB等“一站式”O(jiān)RM解決方案而言,Mybatis 是一種“半自動(dòng)化”的ORM實(shí)現(xiàn)。
需要使用的Jar包:mybatis-3.0.2.jar(mybatis核心包)。mybatis-spring-1.0.0.jar(與Spring結(jié)合包)。
MyBatis簡介
      MyBatis 是一個(gè)可以自定義SQL、存儲過程和高級映射的持久層框架。MyBatis 摒除了大部分的JDBC代碼、手工設(shè)置參數(shù)和結(jié)果集重獲。MyBatis 只使用簡單的XML 和注解來配置和映射基本數(shù)據(jù)類型、Map 接口和POJO 到數(shù)據(jù)庫記錄。相對Hibernate和Apache OJB等“一站式”O(jiān)RM解決方案而言,Mybatis 是一種“半自動(dòng)化”的ORM實(shí)現(xiàn)。
需要使用的Jar包:mybatis-3.0.2.jar(mybatis核心包)。mybatis-spring-1.0.0.jar(與Spring結(jié)合包)。

下載地址:
http://ibatis./tools/ibator
http://code.google.com/p/mybatis/



1.2MyBatis+Spring+MySql簡單配置
1.2.1搭建Spring環(huán)境
1,建立maven的web項(xiàng)目;
2,加入Spring框架、配置文件;
3,在pom.xml中加入所需要的jar包(spring框架的、mybatis、mybatis-spring、junit等);
4,更改web.xml和spring的配置文件;
5,添加一個(gè)jsp頁面和對應(yīng)的Controller;
6,測試。

可參照:http://limingnihao./blog/830409。使用Eclipse的Maven構(gòu)建SpringMVC項(xiàng)目


1.2.2建立MySql數(shù)據(jù)庫
建立一個(gè)學(xué)生選課管理數(shù)據(jù)庫。
表:學(xué)生表、班級表、教師表、課程表、學(xué)生選課表。
邏輯關(guān)系:每個(gè)學(xué)生有一個(gè)班級;每個(gè)班級對應(yīng)一個(gè)班主任教師;每個(gè)教師只能當(dāng)一個(gè)班的班主任;

使用下面的sql進(jìn)行建數(shù)據(jù)庫,先建立學(xué)生表,插入數(shù)據(jù)(2條以上)。

更多sql請下載項(xiàng)目源文件,在resource/sql中。

Sql代碼
 
CREATE DATABASE STUDENT_MANAGER; 
USE STUDENT_MANAGER; 
 
 
CREATE TABLE STUDENT_TBL 
   STUDENT_ID         VARCHAR(255) PRIMARY KEY, 
   STUDENT_NAME       VARCHAR(10) NOT NULL, 
   STUDENT_SEX        VARCHAR(10), 
   STUDENT_BIRTHDAY   DATE, 
   CLASS_ID           VARCHAR(255) 
); 
 
 
INSERT INTO STUDENT_TBL (STUDENT_ID, 
                         STUDENT_NAME, 
                         STUDENT_SEX, 
                         STUDENT_BIRTHDAY, 
                         CLASS_ID) 
  VALUES   (123456, 
            '某某某', 
            '女', 
            '1980-08-01', 
            121546 
            ) 



創(chuàng)建連接MySql使用的配置文件mysql.properties。

Mysql.properties代碼
jdbc.driverClassName=com.mysql.jdbc.Driver 
jdbc.url=jdbc:mysql://localhost:3306/student_manager?user=root&password=limingnihao&useUnicode=true&characterEncoding=UTF-8 


1.2.3搭建MyBatis環(huán)境
順序隨便,現(xiàn)在的順序是因?yàn)榭梢员M量的少的修改寫好的文件。


1.2.3.1創(chuàng)建實(shí)體類: StudentEntity
Java代碼
public class StudentEntity implements Serializable { 
 
    private static final long serialVersionUID = 3096154202413606831L; 
    private ClassEntity classEntity; 
    private Date studentBirthday; 
    private String studentID; 
    private String studentName; 
    private String studentSex; 
     
    public ClassEntity getClassEntity() { 
        return classEntity; 
    } 
 
    public Date getStudentBirthday() { 
        return studentBirthday; 
    } 
 
    public String getStudentID() { 
        return studentID; 
    } 
 
    public String getStudentName() { 
        return studentName; 
    } 
 
    public String getStudentSex() { 
        return studentSex; 
    } 
 
    public void setClassEntity(ClassEntity classEntity) { 
        this.classEntity = classEntity; 
    } 
 
    public void setStudentBirthday(Date studentBirthday) { 
        this.studentBirthday = studentBirthday; 
    } 
 
    public void setStudentID(String studentID) { 
        this.studentID = studentID; 
    } 
 
    public void setStudentName(String studentName) { 
        this.studentName = studentName; 
    } 
 
    public void setStudentSex(String studentSex) { 
        this.studentSex = studentSex; 
    } 
1.2.3.2創(chuàng)建數(shù)據(jù)訪問接口
Student類對應(yīng)的dao接口:StudentMapper。

Java代碼
public interface StudentMapper { 
     
    public StudentEntity getStudent(String studentID); 
     
    public StudentEntity getStudentAndClass(String studentID); 
     
    public List<StudentEntity> getStudentAll(); 
     
    public void insertStudent(StudentEntity entity); 
     
    public void deleteStudent(StudentEntity entity); 
     
    public void updateStudent(StudentEntity entity); 
1.2.3.3創(chuàng)建SQL映射語句文件

Student類的sql語句文件StudentMapper.xml
resultMap標(biāo)簽:表字段與屬性的映射。
Select標(biāo)簽:查詢sql。

Xml代碼
<?xml version="1.0" encoding="UTF-8" ?> 
<!DOCTYPE mapper PUBLIC "-////DTD Mapper 3.0//EN" "http:///dtd/mybatis-3-mapper.dtd"> 
<mapper namespace="com.manager.data.StudentMapper"> 
 
    <resultMap type="StudentEntity" id="studentResultMap"> 
        <id property="studentID" column="STUDENT_ID"/> 
        <result property="studentName" column="STUDENT_NAME"/> 
        <result property="studentSex" column="STUDENT_SEX"/> 
        <result property="studentBirthday" column="STUDENT_BIRTHDAY"/> 
    </resultMap> 
     
    <!-- 查詢學(xué)生,根據(jù)id --> 
    <select id="getStudent" parameterType="String" resultType="StudentEntity" resultMap="studentResultMap"> 
        <![CDATA[
            SELECT * from STUDENT_TBL ST
                WHERE ST.STUDENT_ID = #{studentID} 
        ]]>  
    </select> 
     
    <!-- 查詢學(xué)生列表 --> 
    <select id="getStudentAll"  resultType="com.manager.data.model.StudentEntity" resultMap="studentResultMap"> 
        <![CDATA[
            SELECT * from STUDENT_TBL
        ]]>  
    </select> 
     
</mapper> 


1.2.3.4創(chuàng)建MyBatis的mapper配置文件
在src/main/resource中創(chuàng)建MyBatis配置文件:mybatis-config.xml。
typeAliases標(biāo)簽:給類起一個(gè)別名。com.manager.data.model.StudentEntity類,可以使用StudentEntity代替。
Mappers標(biāo)簽:加載MyBatis中實(shí)體類的SQL映射語句文件。



Xml代碼
<?xml version="1.0" encoding="UTF-8" ?> 
<!DOCTYPE configuration PUBLIC "-////DTD Config 3.0//EN" "http:///dtd/mybatis-3-config.dtd"> 
<configuration> 
    <typeAliases> 
        <typeAlias alias="StudentEntity" type="com.manager.data.model.StudentEntity"/> 
    </typeAliases> 
    <mappers> 
        <mapper resource="com/manager/data/maps/StudentMapper.xml" /> 
    </mappers> 
</configuration>   
1.2.3.5修改Spring 的配置文件
主要是添加SqlSession的制作工廠類的bean:SqlSessionFactoryBean,(在mybatis.spring包中)。需要指定配置文件位置和dataSource。
和數(shù)據(jù)訪問接口對應(yīng)的實(shí)現(xiàn)bean。通過MapperFactoryBean創(chuàng)建出來。需要執(zhí)行接口類全稱和SqlSession工廠bean的引用。

Xml代碼
<!-- 導(dǎo)入屬性配置文件 --> 
<context:property-placeholder location="classpath:mysql.properties" /> 
 
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource"> 
    <property name="driverClassName" value="${jdbc.driverClassName}" /> 
    <property name="url" value="${jdbc.url}" /> 
</bean> 
 
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> 
    <property name="dataSource" ref="dataSource" /> 
</bean> 
 
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"> 
    <property name="configLocation" value="classpath:mybatis-config.xml" /> 
    <property name="dataSource" ref="dataSource" /> 
</bean> 
 
<!— mapper bean --> 
<bean id="studentMapper" class="org.mybatis.spring.MapperFactoryBean"> 
    <property name="mapperInterface" value="com.manager.data.StudentMapper" /> 
    <property name="sqlSessionFactory" ref="sqlSessionFactory" /> 
</bean> 


1.2.4測試StudentMapper
使用SpringMVC測試,創(chuàng)建一個(gè)TestController,配置tomcat,訪問index.do頁面進(jìn)行測試:

Java代碼
@Controller 
public class TestController { 
 
    @Autowired 
    private StudentMapper studentMapper; 
     
    @RequestMapping(value = "index.do") 
    public void indexPage() {    
        StudentEntity entity = studentMapper.getStudent("10000013"); 
        System.out.println("name:" + entity.getStudentName()); 
    }    


使用Junit測試:

Java代碼
使用Junit測試: 
Java代碼 
@RunWith(value = SpringJUnit4ClassRunner.class) 
@ContextConfiguration(value = "test-servlet.xml") 
public class StudentMapperTest { 
     
    @Autowired 
    private ClassMapper classMapper; 
     
    @Autowired 
    private StudentMapper studentMapper; 
     
    @Transactional 
    public void getStudentTest(){ 
        StudentEntity entity = studentMapper.getStudent("10000013"); 
        System.out.println("" + entity.getStudentID() + entity.getStudentName()); 
         
        List<StudentEntity> studentList = studentMapper.getStudentAll(); 
        for( StudentEntity entityTemp : studentList){ 
            System.out.println(entityTemp.getStudentName()); 
        } 
         
    } 


         更詳細(xì)的功能源代碼http://limingnihao./admin/blogs/782190頁面最下面;

二、SQL語句映射文件(1)resultMap
SQL 映射XML 文件是所有sql語句放置的地方。需要定義一個(gè)workspace,一般定義為對應(yīng)的接口類的路徑。寫好SQL語句映射文件后,需要在MyBAtis配置文件mappers標(biāo)簽中引用,例如:



Xml代碼
<mappers> 
    <mapper resource="com/liming/manager/data/mappers/UserMapper.xml" /> 
    <mapper resource="com/liming/manager/data/mappers/StudentMapper.xml" /> 
    <mapper resource="com/liming/manager/data/mappers/ClassMapper.xml" /> 
    <mapper resource="com/liming/manager/data/mappers/TeacherMapper.xml" /> 
</mappers> 


SQL 映射XML 文件一些初級的元素:


1. cache – 配置給定模式的緩存
2. cache-ref – 從別的模式中引用一個(gè)緩存
3. resultMap – 這是最復(fù)雜而卻強(qiáng)大的一個(gè)元素了,它描述如何從結(jié)果集中加載對象
4. sql – 一個(gè)可以被其他語句復(fù)用的SQL 塊
5. insert – 映射INSERT 語句
6. update – 映射UPDATE 語句
7. delete – 映射DELEETE 語句
8. select  -  映射SELECT語句



2.1 resultMap
        resultMap 是MyBatis 中最重要最強(qiáng)大的元素了。你可以讓你比使用JDBC 調(diào)用結(jié)果集省掉90%的代碼,也可以讓你做許多JDBC 不支持的事。現(xiàn)實(shí)上,要寫一個(gè)等同類似于交互的映射這樣的復(fù)雜語句,可能要上千行的代碼。ResultMaps 的目的,就是這樣簡單的語句而不需要多余的結(jié)果映射,更多復(fù)雜的語句,除了只要一些絕對必須的語句描述關(guān)系以外,再也不需要其它的。

resultMap屬性:type為java實(shí)體類;id為此resultMap的標(biāo)識。



resultMap可以設(shè)置的映射:


1. constructor – 用來將結(jié)果反射給一個(gè)實(shí)例化好的類的構(gòu)造器

a) idArg – ID 參數(shù);將結(jié)果集標(biāo)記為ID,以方便全局調(diào)用
b) arg –反射到構(gòu)造器的通常結(jié)果


2. id – ID 結(jié)果,將結(jié)果集標(biāo)記為ID,以方便全局調(diào)用


3. result – 反射到JavaBean 屬性的普通結(jié)果


4. association – 復(fù)雜類型的結(jié)合;多個(gè)結(jié)果合成的類型

a) nested result mappings – 幾resultMap 自身嵌套關(guān)聯(lián),也可以引用到一個(gè)其它上


5. collection –復(fù)雜類型集合a collection of complex types


6. nested result mappings – resultMap 的集合,也可以引用到一個(gè)其它上


7. discriminator – 使用一個(gè)結(jié)果值以決定使用哪個(gè)resultMap

a) case – 基本一些值的結(jié)果映射的case 情形

i. nested result mappings –一個(gè)case 情形本身就是一個(gè)結(jié)果映射,因此也可以包括一些相同的元素,也可以引用一個(gè)外部resultMap。

2.1.1 id、result
id、result是最簡單的映射,id為主鍵映射;result其他基本數(shù)據(jù)庫表字段到實(shí)體類屬性的映射。
  最簡單的例子:

Xml代碼
<resultMap type="StudentEntity" id="studentResultMap"> 
    <id property="studentID" column="STUDENT_ID"/> 
    <result property="studentName" column="STUDENT_NAME"/> 
    <result property="studentSex" column="STUDENT_SEX"/> 
    <result property="studentBirthday" column="STUDENT_BIRTHDAY"/> 
</resultMap> 
id、result語句屬性配置細(xì)節(jié):



屬性
描述

property
需要映射到JavaBean 的屬性名稱。

column
數(shù)據(jù)表的列名或者標(biāo)簽別名。

javaType
一個(gè)完整的類名,或者是一個(gè)類型別名。如果你匹配的是一個(gè)JavaBean,那MyBatis 通常會自行檢測到。然后,如果你是要映射到一個(gè)HashMap,那你需要指定javaType 要達(dá)到的目的。

jdbcType
數(shù)據(jù)表支持的類型列表。這個(gè)屬性只在insert,update 或delete 的時(shí)候針對允許空的列有用。JDBC 需要這項(xiàng),但MyBatis 不需要。如果你是直接針對JDBC 編碼,且有允許空的列,而你要指定這項(xiàng)。

typeHandler
使用這個(gè)屬性可以覆寫類型處理器。這項(xiàng)值可以是一個(gè)完整的類名,也可以是一個(gè)類型別名。



支持的JDBC類型
       為了將來的引用,MyBatis 支持下列JDBC 類型,通過JdbcType 枚舉:
BIT,F(xiàn)LOAT,CHAR,TIMESTAMP,OTHER,UNDEFINED,TINYINT,REAL,VARCHAR,BINARY,BLOB,NVARCHAR,SMALLINT,DOUBLE,LONGVARCHAR,VARBINARY,CLOB,NCHAR,INTEGER,NUMERIC,DATE,LONGVARBINARY,BOOLEAN,NCLOB,BIGINT,DECIMAL,TIME,NULL,CURSOR



2.1.2 constructor

        我們使用id、result時(shí)候,需要定義java實(shí)體類的屬性映射到數(shù)據(jù)庫表的字段上。這個(gè)時(shí)候是使用JavaBean實(shí)現(xiàn)的。當(dāng)然我們也可以使用實(shí)體類的構(gòu)造方法來實(shí)現(xiàn)值的映射,這個(gè)時(shí)候是通過構(gòu)造方法參數(shù)的書寫的順序來進(jìn)行賦值的。
        使用construcotr功能有限(例如使用collection級聯(lián)查詢)。
        上面使用id、result實(shí)現(xiàn)的功能就可以改為:

Xml代碼
<resultMap type="StudentEntity" id="studentResultMap" > 
    <constructor> 
        <idArg javaType="String" column="STUDENT_ID"/> 
        <arg javaType="String" column="STUDENT_NAME"/> 
        <arg javaType="String" column="STUDENT_SEX"/> 
        <arg javaType="Date" column="STUDENT_BIRTHDAY"/> 
    </constructor> 
</resultMap> 


        當(dāng)然,我們需要定義StudentEntity實(shí)體類的構(gòu)造方法:

Java代碼
public StudentEntity(String studentID, String studentName, String studentSex, Date studentBirthday){ 
    this.studentID = studentID; 
    this.studentName = studentName; 
    this.studentSex = studentSex; 
    this.studentBirthday = studentBirthday; 
2.1.3 association聯(lián)合
聯(lián)合元素用來處理“一對一”的關(guān)系。需要指定映射的Java實(shí)體類的屬性,屬性的javaType(通常MyBatis 自己會識別)。對應(yīng)的數(shù)據(jù)庫表的列名稱。如果想覆寫的話返回結(jié)果的值,需要指定typeHandler。
不同情況需要告訴MyBatis 如何加載一個(gè)聯(lián)合。MyBatis 可以用兩種方式加載:

1. select: 執(zhí)行一個(gè)其它映射的SQL 語句返回一個(gè)Java實(shí)體類型。較靈活;
2. resultsMap: 使用一個(gè)嵌套的結(jié)果映射來處理通過join查詢結(jié)果集,映射成Java實(shí)體類型。



例如,一個(gè)班級對應(yīng)一個(gè)班主任。
首先定義好班級中的班主任屬性:

Java代碼
private TeacherEntity teacherEntity; 


2.1.3.1使用select實(shí)現(xiàn)聯(lián)合
例:班級實(shí)體類中有班主任的屬性,通過聯(lián)合在得到一個(gè)班級實(shí)體時(shí),同時(shí)映射出班主任實(shí)體。

這樣可以直接復(fù)用在TeacherMapper.xml文件中定義好的查詢teacher根據(jù)其ID的select語句。而且不需要修改寫好的SQL語句,只需要直接修改resultMap即可。


ClassMapper.xml文件部分內(nèi)容:

Xml代碼
<resultMap type="ClassEntity" id="classResultMap"> 
    <id property="classID" column="CLASS_ID" /> 
    <result property="className" column="CLASS_NAME" /> 
    <result property="classYear" column="CLASS_YEAR" /> 
    <association property="teacherEntity" column="TEACHER_ID" select="getTeacher"/> 
</resultMap> 
 
<select id="getClassByID" parameterType="String" resultMap="classResultMap"> 
    SELECT * FROM CLASS_TBL CT 
    WHERE CT.CLASS_ID = #{classID}; 
</select> 


TeacherMapper.xml文件部分內(nèi)容:

Xml代碼
<resultMap type="TeacherEntity" id="teacherResultMap"> 
    <id property="teacherID" column="TEACHER_ID" /> 
    <result property="teacherName" column="TEACHER_NAME" /> 
    <result property="teacherSex" column="TEACHER_SEX" /> 
    <result property="teacherBirthday" column="TEACHER_BIRTHDAY"/> 
    <result property="workDate" column="WORK_DATE"/> 
    <result property="professional" column="PROFESSIONAL"/> 
</resultMap> 
 
<select id="getTeacher" parameterType="String"  resultMap="teacherResultMap"> 
    SELECT * 
      FROM TEACHER_TBL TT 
     WHERE TT.TEACHER_ID = #{teacherID} 
</select> 
2.1.3.2使用resultMap實(shí)現(xiàn)聯(lián)合
與上面同樣的功能,查詢班級,同時(shí)查詢器班主任。需在association中添加resultMap(在teacher的xml文件中定義好的),新寫sql(查詢班級表left join教師表),不需要teacher的select。


修改ClassMapper.xml文件部分內(nèi)容:

Xml代碼
<resultMap type="ClassEntity" id="classResultMap"> 
    <id property="classID" column="CLASS_ID" /> 
    <result property="className" column="CLASS_NAME" /> 
    <result property="classYear" column="CLASS_YEAR" /> 
    <association property="teacherEntity" column="TEACHER_ID"  resultMap="teacherResultMap"/> 
</resultMap> 
 
<select id="getClassAndTeacher" parameterType="String" resultMap="classResultMap"> 
    SELECT * 
      FROM CLASS_TBL CT LEFT JOIN TEACHER_TBL TT ON CT.TEACHER_ID = TT.TEACHER_ID 
     WHERE CT.CLASS_ID = #{classID}; 
</select> 

其中的teacherResultMap請見上面TeacherMapper.xml文件部分內(nèi)容中。



2.1.4 collection聚集
聚集元素用來處理“一對多”的關(guān)系。需要指定映射的Java實(shí)體類的屬性,屬性的javaType(一般為ArrayList);列表中對象的類型ofType(Java實(shí)體類);對應(yīng)的數(shù)據(jù)庫表的列名稱;
不同情況需要告訴MyBatis 如何加載一個(gè)聚集。MyBatis 可以用兩種方式加載:

1. select: 執(zhí)行一個(gè)其它映射的SQL 語句返回一個(gè)Java實(shí)體類型。較靈活;
2. resultsMap: 使用一個(gè)嵌套的結(jié)果映射來處理通過join查詢結(jié)果集,映射成Java實(shí)體類型。



例如,一個(gè)班級有多個(gè)學(xué)生。
首先定義班級中的學(xué)生列表屬性:

Java代碼
private List<StudentEntity> studentList; 


2.1.4.1使用select實(shí)現(xiàn)聚集
用法和聯(lián)合很類似,區(qū)別在于,這是一對多,所以一般映射過來的都是列表。所以這里需要定義javaType為ArrayList,還需要定義列表中對象的類型ofType,以及必須設(shè)置的select的語句名稱(需要注意的是,這里的查詢 student的select語句條件必須是外鍵classID)。

ClassMapper.xml文件部分內(nèi)容:

Xml代碼
<resultMap type="ClassEntity" id="classResultMap"> 
    <id property="classID" column="CLASS_ID" /> 
    <result property="className" column="CLASS_NAME" /> 
    <result property="classYear" column="CLASS_YEAR" /> 
    <association property="teacherEntity" column="TEACHER_ID"  select="getTeacher"/> 
    <collection property="studentList" column="CLASS_ID" javaType="ArrayList" ofType="StudentEntity" select="getStudentByClassID"/> 
</resultMap> 
 
<select id="getClassByID" parameterType="String" resultMap="classResultMap"> 
    SELECT * FROM CLASS_TBL CT 
    WHERE CT.CLASS_ID = #{classID}; 
</select> 
StudentMapper.xml文件部分內(nèi)容:

Xml代碼
<!-- java屬性,數(shù)據(jù)庫表字段之間的映射定義 --> 
<resultMap type="StudentEntity" id="studentResultMap"> 
    <id property="studentID" column="STUDENT_ID" /> 
    <result property="studentName" column="STUDENT_NAME" /> 
    <result property="studentSex" column="STUDENT_SEX" /> 
    <result property="studentBirthday" column="STUDENT_BIRTHDAY" /> 
</resultMap> 
 
<!-- 查詢學(xué)生list,根據(jù)班級id --> 
<select id="getStudentByClassID" parameterType="String" resultMap="studentResultMap"> 
    <include refid="selectStudentAll" /> 
    WHERE ST.CLASS_ID = #{classID} 
</select> 
2.1.4.2使用resultMap實(shí)現(xiàn)聚集
使用resultMap,就需要重寫一個(gè)sql,left join學(xué)生表。

Xml代碼
<resultMap type="ClassEntity" id="classResultMap"> 
    <id property="classID" column="CLASS_ID" /> 
    <result property="className" column="CLASS_NAME" /> 
    <result property="classYear" column="CLASS_YEAR" /> 
    <association property="teacherEntity" column="TEACHER_ID"  resultMap="teacherResultMap"/> 
    <collection property="studentList" column="CLASS_ID" javaType="ArrayList" ofType="StudentEntity" resultMap="studentResultMap"/> 
</resultMap> 
 
<select id="getClassAndTeacherStudent" parameterType="String" resultMap="classResultMap"> 
    SELECT * 
      FROM CLASS_TBL CT 
           LEFT JOIN STUDENT_TBL ST 
              ON CT.CLASS_ID = ST.CLASS_ID 
           LEFT JOIN TEACHER_TBL TT 
              ON CT.TEACHER_ID = TT.TEACHER_ID 
      WHERE CT.CLASS_ID = #{classID}; 
</select> 

其中的teacherResultMap請見上面TeacherMapper.xml文件部分內(nèi)容中。studentResultMap請見上面StudentMapper.xml文件部分內(nèi)容中。

二、SQL語句映射文件(2)增刪改查、參數(shù)、緩存
2.2 select
一個(gè)select 元素非常簡單。例如:

Xml代碼
<!-- 查詢學(xué)生,根據(jù)id --> 
<select id="getStudent" parameterType="String" resultMap="studentResultMap"> 
    SELECT ST.STUDENT_ID, 
               ST.STUDENT_NAME, 
               ST.STUDENT_SEX, 
               ST.STUDENT_BIRTHDAY, 
               ST.CLASS_ID 
          FROM STUDENT_TBL ST 
         WHERE ST.STUDENT_ID = #{studentID} 
</select> 


這條語句就叫做‘getStudent,有一個(gè)String參數(shù),并返回一個(gè)StudentEntity類型的對象。
注意參數(shù)的標(biāo)識是:#{studentID}。



select 語句屬性配置細(xì)節(jié):


屬性 描述 取值 默認(rèn)
id 在這個(gè)模式下唯一的標(biāo)識符,可被其它語句引用
parameterType 傳給此語句的參數(shù)的完整類名或別名
resultType 語句返回值類型的整類名或別名。注意,如果是集合,那么這里填寫的是集合的項(xiàng)的整類名或別名,而不是集合本身的類名。(resultType 與resultMap 不能并用)
resultMap 引用的外部resultMap 名。結(jié)果集映射是MyBatis 中最強(qiáng)大的特性。許多復(fù)雜的映射都可以輕松解決。(resultType 與resultMap 不能并用)
flushCache 如果設(shè)為true,則會在每次語句調(diào)用的時(shí)候就會清空緩存。select 語句默認(rèn)設(shè)為false true|false false
useCache 如果設(shè)為true,則語句的結(jié)果集將被緩存。select 語句默認(rèn)設(shè)為false true|false false
timeout 設(shè)置驅(qū)動(dòng)器在拋出異常前等待回應(yīng)的最長時(shí)間,默認(rèn)為不設(shè)值,由驅(qū)動(dòng)器自己決定 true|false false
timeout 設(shè)置驅(qū)動(dòng)器在拋出異常前等待回應(yīng)的最長時(shí)間,默認(rèn)為不設(shè)值,由驅(qū)動(dòng)器自己決定 正整數(shù) 未設(shè)置
fetchSize 設(shè)置一個(gè)值后,驅(qū)動(dòng)器會在結(jié)果集數(shù)目達(dá)到此數(shù)值后,激發(fā)返回,默認(rèn)為不設(shè)值,由驅(qū)動(dòng)器自己決定 正整數(shù) 驅(qū)動(dòng)器決定
statementType statement,preparedstatement,callablestatement。
預(yù)準(zhǔn)備語句、可調(diào)用語句 STATEMENT
PREPARED
CALLABLE PREPARED
resultSetType forward_only,scroll_sensitive,scroll_insensitive
只轉(zhuǎn)發(fā),滾動(dòng)敏感,不區(qū)分大小寫的滾動(dòng) FORWARD_ONLY
SCROLL_SENSITIVE
SCROLL_INSENSITIVE 驅(qū)動(dòng)器決定


2.3 insert
一個(gè)簡單的insert語句:

Xml代碼
<!-- 插入學(xué)生 --> 
<insert id="insertStudent" parameterType="StudentEntity"> 
        INSERT INTO STUDENT_TBL (STUDENT_ID, 
                                          STUDENT_NAME, 
                                          STUDENT_SEX, 
                                          STUDENT_BIRTHDAY, 
                                          CLASS_ID) 
              VALUES   (#{studentID}, 
                          #{studentName}, 
                          #{studentSex}, 
                          #{studentBirthday}, 
                          #{classEntity.classID}) 
</insert> 
insert可以使用數(shù)據(jù)庫支持的自動(dòng)生成主鍵策略,設(shè)置useGeneratedKeys=”true”,然后把keyProperty 設(shè)成對應(yīng)的列,就搞定了。比如說上面的StudentEntity 使用auto-generated 為id 列生成主鍵.
還可以使用selectKey元素。下面例子,使用mysql數(shù)據(jù)庫nextval('student')為自定義函數(shù),用來生成一個(gè)key。

Xml代碼
<!-- 插入學(xué)生 自動(dòng)主鍵--> 
<insert id="insertStudentAutoKey" parameterType="StudentEntity"> 
    <selectKey keyProperty="studentID" resultType="String" order="BEFORE"> 
            select nextval('student') 
    </selectKey> 
        INSERT INTO STUDENT_TBL (STUDENT_ID, 
                                 STUDENT_NAME, 
                                 STUDENT_SEX, 
                                 STUDENT_BIRTHDAY, 
                                 CLASS_ID) 
              VALUES   (#{studentID}, 
                        #{studentName}, 
                        #{studentSex}, 
                        #{studentBirthday}, 
                        #{classEntity.classID})     
</insert> 
insert語句屬性配置細(xì)節(jié):


屬性 描述 取值 默認(rèn)
id 在這個(gè)模式下唯一的標(biāo)識符,可被其它語句引用
parameterType 傳給此語句的參數(shù)的完整類名或別名
flushCache 如果設(shè)為true,則會在每次語句調(diào)用的時(shí)候就會清空緩存。select 語句默認(rèn)設(shè)為false true|false false
useCache 如果設(shè)為true,則語句的結(jié)果集將被緩存。select 語句默認(rèn)設(shè)為false true|false false
timeout 設(shè)置驅(qū)動(dòng)器在拋出異常前等待回應(yīng)的最長時(shí)間,默認(rèn)為不設(shè)值,由驅(qū)動(dòng)器自己決定 true|false false
timeout 設(shè)置驅(qū)動(dòng)器在拋出異常前等待回應(yīng)的最長時(shí)間,默認(rèn)為不設(shè)值,由驅(qū)動(dòng)器自己決定 正整數(shù) 未設(shè)置
fetchSize 設(shè)置一個(gè)值后,驅(qū)動(dòng)器會在結(jié)果集數(shù)目達(dá)到此數(shù)值后,激發(fā)返回,默認(rèn)為不設(shè)值,由驅(qū)動(dòng)器自己決定 正整數(shù) 驅(qū)動(dòng)器決定
statementType statement,preparedstatement,callablestatement。
預(yù)準(zhǔn)備語句、可調(diào)用語句 STATEMENT
PREPARED
CALLABLE PREPARED
useGeneratedKeys
告訴MyBatis 使用JDBC 的getGeneratedKeys 方法來獲取數(shù)據(jù)庫自己生成的主鍵(MySQL、SQLSERVER 等

關(guān)系型數(shù)據(jù)庫會有自動(dòng)生成的字段)。默認(rèn):false

true|false false
keyProperty
標(biāo)識一個(gè)將要被MyBatis 設(shè)置進(jìn)getGeneratedKeys 的key 所返回的值,或者為insert 語句使用一個(gè)selectKey

子元素。




selectKey語句屬性配置細(xì)節(jié):



屬性 描述 取值
keyProperty selectKey 語句生成結(jié)果需要設(shè)置的屬性。
resultType 生成結(jié)果類型,MyBatis 允許使用基本的數(shù)據(jù)類型,包括String 、int類型。
order 可以設(shè)成BEFORE 或者AFTER,如果設(shè)為BEFORE,那它會先選擇主鍵,然后設(shè)置keyProperty,再執(zhí)行insert語句;如果設(shè)為AFTER,它就先運(yùn)行 insert 語句再運(yùn)行selectKey 語句,通常是insert 語句中內(nèi)部調(diào)用數(shù)據(jù)庫(像Oracle)內(nèi)嵌的序列機(jī)制。 BEFORE
AFTER
statementType 像上面的那樣, MyBatis 支持STATEMENT,PREPARED和CALLABLE 的語句形式, 對應(yīng)Statement ,PreparedStatement 和CallableStatement 響應(yīng) STATEMENT
PREPARED
CALLABLE
2.4 update、delete
一個(gè)簡單的update:

Xml代碼
<!-- 更新學(xué)生信息 --> 
<update id="updateStudent" parameterType="StudentEntity"> 
        UPDATE STUDENT_TBL 
            SET STUDENT_TBL.STUDENT_NAME = #{studentName},  
                STUDENT_TBL.STUDENT_SEX = #{studentSex}, 
                STUDENT_TBL.STUDENT_BIRTHDAY = #{studentBirthday}, 
                STUDENT_TBL.CLASS_ID = #{classEntity.classID} 
         WHERE STUDENT_TBL.STUDENT_ID = #{studentID};    
</update> 


一個(gè)簡單的delete:

Xml代碼
<!-- 刪除學(xué)生 --> 
<delete id="deleteStudent" parameterType="StudentEntity"> 
        DELETE FROM STUDENT_TBL WHERE STUDENT_ID = #{studentID} 
</delete> 
update、delete語句屬性配置細(xì)節(jié):


屬性 描述 取值 默認(rèn)
id 在這個(gè)模式下唯一的標(biāo)識符,可被其它語句引用
parameterType 傳給此語句的參數(shù)的完整類名或別名
flushCache 如果設(shè)為true,則會在每次語句調(diào)用的時(shí)候就會清空緩存。select 語句默認(rèn)設(shè)為false true|false false
useCache 如果設(shè)為true,則語句的結(jié)果集將被緩存。select 語句默認(rèn)設(shè)為false true|false false
timeout 設(shè)置驅(qū)動(dòng)器在拋出異常前等待回應(yīng)的最長時(shí)間,默認(rèn)為不設(shè)值,由驅(qū)動(dòng)器自己決定 true|false false
timeout 設(shè)置驅(qū)動(dòng)器在拋出異常前等待回應(yīng)的最長時(shí)間,默認(rèn)為不設(shè)值,由驅(qū)動(dòng)器自己決定 正整數(shù) 未設(shè)置
fetchSize 設(shè)置一個(gè)值后,驅(qū)動(dòng)器會在結(jié)果集數(shù)目達(dá)到此數(shù)值后,激發(fā)返回,默認(rèn)為不設(shè)值,由驅(qū)動(dòng)器自己決定 正整數(shù) 驅(qū)動(dòng)器決定
statementType statement,preparedstatement,callablestatement。
預(yù)準(zhǔn)備語句、可調(diào)用語句 STATEMENT
PREPARED
CALLABLE PREPARED
2.5 sql
Sql元素用來定義一個(gè)可以復(fù)用的SQL 語句段,供其它語句調(diào)用。比如:

Xml代碼
<!-- 復(fù)用sql語句  查詢student表所有字段 --> 
<sql id="selectStudentAll"> 
        SELECT ST.STUDENT_ID, 
                   ST.STUDENT_NAME, 
                   ST.STUDENT_SEX, 
                   ST.STUDENT_BIRTHDAY, 
                   ST.CLASS_ID 
              FROM STUDENT_TBL ST 
</sql> 

   這樣,在select的語句中就可以直接引用使用了,將上面select語句改成:

Xml代碼
<!-- 查詢學(xué)生,根據(jù)id --> 
<select id="getStudent" parameterType="String" resultMap="studentResultMap"> 
    <include refid="selectStudentAll"/> 
            WHERE ST.STUDENT_ID = #{studentID}  
</select> 
2.6parameters
        上面很多地方已經(jīng)用到了參數(shù),比如查詢、修改、刪除的條件,插入,修改的數(shù)據(jù)等,MyBatis可以使用的基本數(shù)據(jù)類型和Java的復(fù)雜數(shù)據(jù)類型。
        基本數(shù)據(jù)類型,String,int,date等。
        但是使用基本數(shù)據(jù)類型,只能提供一個(gè)參數(shù),所以需要使用Java實(shí)體類,或Map類型做參數(shù)類型。通過#{}可以直接得到其屬性。

2.6.1基本類型參數(shù)
根據(jù)入學(xué)時(shí)間,檢索學(xué)生列表:

Xml代碼
<!-- 查詢學(xué)生list,根據(jù)入學(xué)時(shí)間  --> 
<select id="getStudentListByDate"  parameterType="Date" resultMap="studentResultMap"> 
    SELECT * 
      FROM STUDENT_TBL ST LEFT JOIN CLASS_TBL CT ON ST.CLASS_ID = CT.CLASS_ID 
     WHERE CT.CLASS_YEAR = #{classYear};     
</select>
Java代碼
List<StudentEntity> studentList = studentMapper.getStudentListByClassYear(StringUtil.parse("2007-9-1")); 
for (StudentEntity entityTemp : studentList) { 
    System.out.println(entityTemp.toString()); 
}
2.6.2Java實(shí)體類型參數(shù)
根據(jù)姓名和性別,檢索學(xué)生列表。使用實(shí)體類做參數(shù):

Xml代碼
<!-- 查詢學(xué)生list,like姓名、=性別,參數(shù)entity類型 --> 
<select id="getStudentListWhereEntity" parameterType="StudentEntity" resultMap="studentResultMap"> 
    SELECT * from STUDENT_TBL ST 
        WHERE ST.STUDENT_NAME LIKE CONCAT(CONCAT('%', #{studentName}),'%') 
          AND ST.STUDENT_SEX = #{studentSex} 
</select> 
Java代碼
StudentEntity entity = new StudentEntity(); 
entity.setStudentName("李"); 
entity.setStudentSex("男"); 
List<StudentEntity> studentList = studentMapper.getStudentListWhereEntity(entity); 
for (StudentEntity entityTemp : studentList) { 
    System.out.println(entityTemp.toString()); 
2.6.3Map參數(shù)
根據(jù)姓名和性別,檢索學(xué)生列表。使用Map做參數(shù):

Xml代碼
<!-- 查詢學(xué)生list,=性別,參數(shù)map類型 --> 
<select id="getStudentListWhereMap" parameterType="Map" resultMap="studentResultMap"> 
    SELECT * from STUDENT_TBL ST 
     WHERE ST.STUDENT_SEX = #{sex} 
          AND ST.STUDENT_SEX = #{sex} 
</select> 
Java代碼
Map<String, String> map = new HashMap<String, String>(); 
map.put("sex", "女"); 
map.put("name", "李"); 
List<StudentEntity> studentList = studentMapper.getStudentListWhereMap(map); 
for (StudentEntity entityTemp : studentList) { 
    System.out.println(entityTemp.toString()); 
2.6.4多參數(shù)的實(shí)現(xiàn)
如果想傳入多個(gè)參數(shù),則需要在接口的參數(shù)上添加@Param注解。給出一個(gè)實(shí)例:
接口寫法:

Java代碼
public List<StudentEntity> getStudentListWhereParam(@Param(value = "name") String name, @Param(value = "sex") String sex, @Param(value = "birthday") Date birthdar, @Param(value = "classEntity") ClassEntity classEntity); 
SQL寫法:

Xml代碼
<!-- 查詢學(xué)生list,like姓名、=性別、=生日、=班級,多參數(shù)方式 --> 
<select id="getStudentListWhereParam" resultMap="studentResultMap"> 
    SELECT * from STUDENT_TBL ST 
    <where> 
        <if test="name!=null and name!='' "> 
            ST.STUDENT_NAME LIKE CONCAT(CONCAT('%', #{name}),'%') 
        </if> 
        <if test="sex!= null and sex!= '' "> 
            AND ST.STUDENT_SEX = #{sex} 
        </if> 
        <if test="birthday!=null"> 
            AND ST.STUDENT_BIRTHDAY = #{birthday} 
        </if> 
        <if test="classEntity!=null and classEntity.classID !=null and classEntity.classID!='' "> 
            AND ST.CLASS_ID = #{classEntity.classID} 
        </if> 
    </where> 
</select> 
進(jìn)行查詢:

Java代碼
List<StudentEntity> studentList = studentMapper.getStudentListWhereParam("", "",StringUtil.parse("1985-05-28"), classMapper.getClassByID("20000002")); 
for (StudentEntity entityTemp : studentList) { 
    System.out.println(entityTemp.toString()); 
2.6.5字符串代入法
        默認(rèn)的情況下,使用#{}語法會促使MyBatis 生成PreparedStatement 屬性并且使用PreparedStatement 的參數(shù)(=?)來安全的設(shè)置值。盡量這些是快捷安全,也是經(jīng)常使用的。但有時(shí)候你可能想直接未更改的字符串代入到SQL 語句中。比如說,對于ORDER BY,你可能會這樣使用:ORDER BY ${columnName}但MyBatis 不會修改和規(guī)避掉這個(gè)字符串。
        注意:這樣地接收和應(yīng)用一個(gè)用戶輸入到未更改的語句中,是非常不安全的。這會讓用戶能植入破壞代碼,所以,要么要求字段不要允許客戶輸入,要么你直接來檢測他的合法性 。

2.7 cache緩存
        MyBatis 包含一個(gè)強(qiáng)在的、可配置、可定制的緩存機(jī)制。MyBatis 3 的緩存實(shí)現(xiàn)有了許多改進(jìn),既強(qiáng)勁也更容易配置。默認(rèn)的情況,緩存是沒有開啟,除了會話緩存以外,它可以提高性能,且能解決全局依賴。開啟二級緩存,你只需要在SQL 映射文件中加入簡單的一行:<cache/>


這句簡單的語句的作用如下:

1. 所有在映射文件里的select 語句都將被緩存。
2. 所有在映射文件里insert,update 和delete 語句會清空緩存。
3. 緩存使用“最近很少使用”算法來回收
4. 緩存不會被設(shè)定的時(shí)間所清空。
5. 每個(gè)緩存可以存儲1024 個(gè)列表或?qū)ο蟮囊茫ú还懿樵兂鰜淼慕Y(jié)果是什么)。
6. 緩存將作為“讀/寫”緩存,意味著獲取的對象不是共享的且對調(diào)用者是安全的。不會有其它的調(diào)用
7. 者或線程潛在修改。

例如,創(chuàng)建一個(gè)FIFO 緩存讓60 秒就清空一次,存儲512 個(gè)對象結(jié)果或列表引用,并且返回的結(jié)果是只讀。因?yàn)樵诓挥玫木€程里的兩個(gè)調(diào)用者修改它們可能會導(dǎo)致引用沖突。

Xml代碼
<cache eviction="FIFO" flushInterval="60000" size="512" readOnly="true"> 
</cache> 
    還可以在不同的命名空間里共享同一個(gè)緩存配置或者實(shí)例。在這種情況下,你就可以使用cache-ref 來引用另外一個(gè)緩存。

Xml代碼
<cache-ref namespace="com.liming.manager.data.StudentMapper"/> 
Cache 語句屬性配置細(xì)節(jié):

屬性 說明 取值 默認(rèn)值
eviction 緩存策略:
LRU - 最近最少使用法:移出最近較長周期內(nèi)都沒有被使用的對象。
FIFI- 先進(jìn)先出:移出隊(duì)列里較早的對象
SOFT - 軟引用:基于軟引用規(guī)則,使用垃圾回收機(jī)制來移出對象
WEAK - 弱引用:基于弱引用規(guī)則,使用垃圾回收機(jī)制來強(qiáng)制性地移出對象 LRU
FIFI
SOFT
WEAK LRU
flushInterval 代表一個(gè)合理的毫秒總計(jì)時(shí)間。默認(rèn)是不設(shè)置,因此使用無間隔清空即只能調(diào)用語句來清空。 正整數(shù)
不設(shè)置

size 緩存的對象的大小 正整數(shù) 1024
readOnly
只讀緩存將對所有調(diào)用者返回同一個(gè)實(shí)例。因此都不能被修改,這可以極大的提高性能??蓪懙木彺鎸⑼ㄟ^序列

化來返回一個(gè)緩存對象的拷貝。這會比較慢,但是比較安全。所以默認(rèn)值是false。


true|false false


轉(zhuǎn)載:   http://limingnihao./blog/781671

三、動(dòng)態(tài)SQL語句
        有些時(shí)候,sql語句where條件中,需要一些安全判斷,例如按性別檢索,如果傳入的參數(shù)是空的,此時(shí)查詢出的結(jié)果很可能是空的,也許我們需要參數(shù)為空時(shí),是查出全部的信息。這是我們可以使用動(dòng)態(tài)sql,增加一個(gè)判斷,當(dāng)參數(shù)不符合要求的時(shí)候,我們可以不去判斷此查詢條件。
        下文均采用mysql語法和函數(shù)(例如字符串鏈接函數(shù)CONCAT)。

        源代碼http://limingnihao./admin/blogs/782190頁面最下面;

3.1 if標(biāo)簽
一個(gè)很普通的查詢:

Xml代碼
<!-- 查詢學(xué)生list,like姓名 --> 
<select id="getStudentListLikeName" parameterType="StudentEntity" resultMap="studentResultMap"> 
    SELECT * from STUDENT_TBL ST  
WHERE ST.STUDENT_NAME LIKE CONCAT(CONCAT('%', #{studentName}),'%') 
</select> 
但是此時(shí)如果studentName是null或空字符串,此語句很可能報(bào)錯(cuò)或查詢結(jié)果為空。此時(shí)我們使用if動(dòng)態(tài)sql語句先進(jìn)行判斷,如果值為null或等于空字符串,我們就進(jìn)行此條件的判斷。

修改為:

Xml代碼
<!-- 查詢學(xué)生list,like姓名 --> 
<select id=" getStudentListLikeName " parameterType="StudentEntity" resultMap="studentResultMap"> 
    SELECT * from STUDENT_TBL ST 
    <if test="studentName!=null and studentName!='' "> 
        WHERE ST.STUDENT_NAME LIKE CONCAT(CONCAT('%', #{studentName}),'%') 
    </if> 
</select> 
此時(shí),當(dāng)studentName的值為null或’’的時(shí)候,我們并不進(jìn)行where條件的判斷,所以當(dāng)studentName值為null或’’值,不附帶這個(gè)條件,所以查詢結(jié)果是全部。

由于參數(shù)是Java的實(shí)體類,所以我們可以把所有條件都附加上,使用時(shí)比較靈活, new一個(gè)這樣的實(shí)體類,我們需要限制那個(gè)條件,只需要附上相應(yīng)的值就會where這個(gè)條件,相反不去賦值就可以不在where中判斷。

   代碼中的where標(biāo)簽,請參考3.2.1.

Xml代碼
<!-- 查詢學(xué)生list,like姓名,=性別、=生日、=班級,使用where,參數(shù)entity類型 --> 
<select id="getStudentListWhereEntity" parameterType="StudentEntity" resultMap="studentResultMap"> 
    SELECT * from STUDENT_TBL ST 
    <where> 
        <if test="studentName!=null and studentName!='' "> 
            ST.STUDENT_NAME LIKE CONCAT(CONCAT('%', #{studentName}),'%') 
        </if> 
        <if test="studentSex!= null and studentSex!= '' "> 
            AND ST.STUDENT_SEX = #{studentSex} 
        </if> 
        <if test="studentBirthday!=null"> 
            AND ST.STUDENT_BIRTHDAY = #{studentBirthday} 
        </if> 
        <if test="classEntity!=null and classEntity.classID !=null and classEntity.classID!='' "> 
            AND ST.CLASS_ID = #{classEntity.classID} 
        </if> 
    </where> 
</select> 
查詢,姓名中有‘李’,男,生日在‘1985-05-28’,班級在‘20000002’的學(xué)生。

Java代碼
StudentEntity entity = new StudentEntity(); 
entity.setStudentName("李"); 
entity.setStudentSex("男"); 
entity.setStudentBirthday(StringUtil.parse("1985-05-28")); 
entity.setClassEntity(classMapper.getClassByID("20000002")); 
List<StudentEntity> studentList = studentMapper.getStudentListWhereEntity(entity); 
for( StudentEntity entityTemp : studentList){ 
    System.out.println(entityTemp.toString()); 
3.2 where、set、trim標(biāo)簽
3.2.1 where
當(dāng)if標(biāo)簽較多時(shí),這樣的組合可能會導(dǎo)致錯(cuò)誤。例如,like姓名,等于指定性別等:
Xml代碼
<!-- 查詢學(xué)生list,like姓名,=性別 --> 
<select id="getStudentListWhere" parameterType="StudentEntity" resultMap="studentResultMap"> 
    SELECT * from STUDENT_TBL ST 
        WHERE 
        <if test="studentName!=null and studentName!='' "> 
            ST.STUDENT_NAME LIKE CONCAT(CONCAT('%', #{studentName}),'%') 
        </if> 
        <if test="studentSex!= null and studentSex!= '' "> 
            AND ST.STUDENT_SEX = #{studentSex} 
        </if> 
</select> 
如果上面例子,參數(shù)studentName為null或’’,則或?qū)е麓藄ql組合成“WHERE AND”之類的關(guān)鍵字多余的錯(cuò)誤SQL。
這時(shí)我們可以使用where動(dòng)態(tài)語句來解決。這個(gè)“where”標(biāo)簽會知道如果它包含的標(biāo)簽中有返回值的話,它就插入一個(gè)‘where’。此外,如果標(biāo)簽返回的內(nèi)容是以AND 或OR 開頭的,則它會剔除掉。
上面例子修改為:

Xml代碼
<!-- 查詢學(xué)生list,like姓名,=性別 --> 
<select id="getStudentListWhere" parameterType="StudentEntity" resultMap="studentResultMap"> 
    SELECT * from STUDENT_TBL ST 
    <where> 
        <if test="studentName!=null and studentName!='' "> 
            ST.STUDENT_NAME LIKE CONCAT(CONCAT('%', #{studentName}),'%') 
        </if> 
        <if test="studentSex!= null and studentSex!= '' "> 
            AND ST.STUDENT_SEX = #{studentSex} 
        </if> 
    </where> 
</select> 
3.2.2 set
當(dāng)在update語句中使用if標(biāo)簽時(shí),如果前面的if沒有執(zhí)行,則或?qū)е露禾柖嘤噱e(cuò)誤。使用set標(biāo)簽可以將動(dòng)態(tài)的配置SET 關(guān)鍵字,和剔除追加到條件末尾的任何不相關(guān)的逗號。
沒有使用if標(biāo)簽時(shí),如果有一個(gè)參數(shù)為null,都會導(dǎo)致錯(cuò)誤,如下示例:

Xml代碼
<!-- 更新學(xué)生信息 --> 
<update id="updateStudent" parameterType="StudentEntity"> 
    UPDATE STUDENT_TBL 
       SET STUDENT_TBL.STUDENT_NAME = #{studentName}, 
           STUDENT_TBL.STUDENT_SEX = #{studentSex}, 
           STUDENT_TBL.STUDENT_BIRTHDAY = #{studentBirthday}, 
           STUDENT_TBL.CLASS_ID = #{classEntity.classID} 
     WHERE STUDENT_TBL.STUDENT_ID = #{studentID}; 
</update> 
使用set+if標(biāo)簽修改后,如果某項(xiàng)為null則不進(jìn)行更新,而是保持?jǐn)?shù)據(jù)庫原值。如下示例:
Xml代碼
<!-- 更新學(xué)生信息 --> 
<update id="updateStudent" parameterType="StudentEntity"> 
    UPDATE STUDENT_TBL 
    <set> 
        <if test="studentName!=null and studentName!='' "> 
            STUDENT_TBL.STUDENT_NAME = #{studentName}, 
        </if> 
        <if test="studentSex!=null and studentSex!='' "> 
            STUDENT_TBL.STUDENT_SEX = #{studentSex}, 
        </if> 
        <if test="studentBirthday!=null "> 
            STUDENT_TBL.STUDENT_BIRTHDAY = #{studentBirthday}, 
        </if> 
        <if test="classEntity!=null and classEntity.classID!=null and classEntity.classID!='' "> 
            STUDENT_TBL.CLASS_ID = #{classEntity.classID} 
        </if> 
    </set> 
    WHERE STUDENT_TBL.STUDENT_ID = #{studentID}; 
</update> 
3.2.3 trim
trim是更靈活的去處多余關(guān)鍵字的標(biāo)簽,他可以實(shí)踐where和set的效果。

where例子的等效trim語句:

Xml代碼
<!-- 查詢學(xué)生list,like姓名,=性別 --> 
<select id="getStudentListWhere" parameterType="StudentEntity" resultMap="studentResultMap"> 
    SELECT * from STUDENT_TBL ST 
    <trim prefix="WHERE" prefixOverrides="AND|OR"> 
        <if test="studentName!=null and studentName!='' "> 
            ST.STUDENT_NAME LIKE CONCAT(CONCAT('%', #{studentName}),'%') 
        </if> 
        <if test="studentSex!= null and studentSex!= '' "> 
            AND ST.STUDENT_SEX = #{studentSex} 
        </if> 
    </trim> 
</select> 
set例子的等效trim語句:

Xml代碼
<!-- 更新學(xué)生信息 --> 
<update id="updateStudent" parameterType="StudentEntity"> 
    UPDATE STUDENT_TBL 
    <trim prefix="SET" suffixOverrides=","> 
        <if test="studentName!=null and studentName!='' "> 
            STUDENT_TBL.STUDENT_NAME = #{studentName}, 
        </if> 
        <if test="studentSex!=null and studentSex!='' "> 
            STUDENT_TBL.STUDENT_SEX = #{studentSex}, 
        </if> 
        <if test="studentBirthday!=null "> 
            STUDENT_TBL.STUDENT_BIRTHDAY = #{studentBirthday}, 
        </if> 
        <if test="classEntity!=null and classEntity.classID!=null and classEntity.classID!='' "> 
            STUDENT_TBL.CLASS_ID = #{classEntity.classID} 
        </if> 
    </trim> 
    WHERE STUDENT_TBL.STUDENT_ID = #{studentID}; 
</update> 
3.3 choose (when, otherwise)
         有時(shí)候我們并不想應(yīng)用所有的條件,而只是想從多個(gè)選項(xiàng)中選擇一個(gè)。MyBatis提供了choose 元素,按順序判斷when中的條件出否成立,如果有一個(gè)成立,則choose結(jié)束。當(dāng)choose中所有when的條件都不滿則時(shí),則執(zhí)行 otherwise中的sql。類似于Java 的switch 語句,choose為switch,when為case,otherwise則為default。
         if是與(and)的關(guān)系,而choose是或(or)的關(guān)系。


         例如下面例子,同樣把所有可以限制的條件都寫上,方面使用。選擇條件順序,when標(biāo)簽的從上到下的書寫順序:

Xml代碼
<!-- 查詢學(xué)生list,like姓名、或=性別、或=生日、或=班級,使用choose --> 
<select id="getStudentListChooseEntity" parameterType="StudentEntity" resultMap="studentResultMap"> 
    SELECT * from STUDENT_TBL ST 
    <where> 
        <choose> 
            <when test="studentName!=null and studentName!='' "> 
                    ST.STUDENT_NAME LIKE CONCAT(CONCAT('%', #{studentName}),'%') 
            </when> 
            <when test="studentSex!= null and studentSex!= '' "> 
                    AND ST.STUDENT_SEX = #{studentSex} 
            </when> 
            <when test="studentBirthday!=null"> 
                AND ST.STUDENT_BIRTHDAY = #{studentBirthday} 
            </when> 
            <when test="classEntity!=null and classEntity.classID !=null and classEntity.classID!='' "> 
                AND ST.CLASS_ID = #{classEntity.classID} 
            </when> 
            <otherwise> 
                 
            </otherwise> 
        </choose> 
    </where> 
</select> 
3.4 foreach
對于動(dòng)態(tài)SQL 非常必須的,主是要迭代一個(gè)集合,通常是用于IN 條件。
List 實(shí)例將使用“l(fā)ist”做為鍵,數(shù)組實(shí)例以“array” 做為鍵。

3.4.1參數(shù)為list實(shí)例的寫法:
SQL寫法:

Xml代碼
<select id="getStudentListByClassIDs" resultMap="studentResultMap"> 
    SELECT * FROM STUDENT_TBL ST 
     WHERE ST.CLASS_ID IN  
     <foreach collection="list" item="classList"  open="(" separator="," close=")"> 
        #{classList} 
     </foreach>    
</select> 
接口的方法聲明:

Java代碼
public List<StudentEntity> getStudentListByClassIDs(List<String> classList); 
  測試代碼,查詢學(xué)生中,在20000002、20000003這兩個(gè)班級的學(xué)生:

Java代碼
List<String> classList = new ArrayList<String>(); 
classList.add("20000002"); 
classList.add("20000003"); 
 
List<StudentEntity> studentList = studentMapper.getStudentListByClassIDs(classList); 
for( StudentEntity entityTemp : studentList){ 
    System.out.println(entityTemp.toString()); 
3.4.2參數(shù)為Array實(shí)例的寫法:
SQL語句:
Xml代碼
<select id="getStudentListByClassIDs" resultMap="studentResultMap"> 
    SELECT * FROM STUDENT_TBL ST 
     WHERE ST.CLASS_ID IN  
     <foreach collection="array" item="ids"  open="(" separator="," close=")"> 
        #{ids} 
     </foreach> 
</select>   

接口的方法聲明:
Java代碼
public List<StudentEntity> getStudentListByClassIDs(String[] ids); 
測試代碼,查詢學(xué)生中,在20000002、20000003這兩個(gè)班級的學(xué)生:
Java代碼
String[] ids = new String[2]; 
ids[0] = "20000002"; 
ids[1] = "20000003"; 
List<StudentEntity> studentList = studentMapper.getStudentListByClassIDs(ids); 
for( StudentEntity entityTemp : studentList){ 
    System.out.println(entityTemp.toString()); 
}

    本站是提供個(gè)人知識管理的網(wǎng)絡(luò)存儲空間,所有內(nèi)容均由用戶發(fā)布,不代表本站觀點(diǎn)。請注意甄別內(nèi)容中的聯(lián)系方式、誘導(dǎo)購買等信息,謹(jǐn)防詐騙。如發(fā)現(xiàn)有害或侵權(quán)內(nèi)容,請點(diǎn)擊一鍵舉報(bào)。
    轉(zhuǎn)藏 分享 獻(xiàn)花(0

    0條評論

    發(fā)表

    請遵守用戶 評論公約

    類似文章 更多