MyBatis基於動態代理機制,讓咱們無需再編寫Dao的實現。java
傳統Dao接口,如今名稱統一以Mapper結尾,還有咱們映射器配置文件要和映射器在同一個包。mysql
(1)根據需求,建立模型相關的Mapper接口web
(2)編寫映射文件spring
a)*Mapper.xml的命名空間,必須和接口的「全限定名」一致sql
b)定義sql標籤的id,須要和「接口的方法」一致apache
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="cn.itsource._01_mapper.TeacherMapper"> 5 <!-- 查詢 findAll() 6 resultType 返回類型 7 --> 8 <select id="findAll" resultType="Teacher"> 9 select * from t_teacher 10 </select> 11 </mapper>
(3)測試spring-mvc
1 @Test 2 public void findAll() { 3 SqlSession sqlSession = MyBatisUtils.INSTANCE.getSqlSession(); 4 //MyBatis動態代理 5 TeacherMapper mapper = sqlSession.getMapper(TeacherMapper.class); 6 mapper.findAll().forEach(t -> System.out.println(t)); 7 }
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="cn.itsource._02_query.TeacherMapper"> 5 <!-- 查詢 findAll() 6 resultType 返回類型 7 --> 8 <select id="findAll" resultType="Teacher"> 9 select * from t_teacher 10 </select> 11 <select id="queryAll" parameterType="teacherQuery" resultType="Teacher"> 12 select * from t_teacher 13 <where> 14 <if test="name!=null"> 15 and name like concat("%",#{name},"%") 16 </if> 17 <if test="minAge!=null"> 18 and age > #{minAge} 19 </if> 20 <if test="maxAge!=null"> 21 and age < #{maxAge} 22 </if> 23 <!-- 放入CDATA區域裏面被xml忽略解析 24 <if test="maxAge != null"> 25 <![CDATA[ 26 and age < #{maxAge} 27 ]]> 28 </if>--> 29 </where> 30 </select> 31 </mapper>
注意:緩存
1.where:裏面全部的條件若是都在前面加上and,而且最後會把第一個and替換爲wheremybatis
2.if 判斷條件是否知足,若是是而且用andmvc
3.模糊查詢
方案1:不能用#
and ( name like %#{keywords}% or password like %#{keywords}% )
方案2:用$ sql注入
and ( name like '%${keywords}%' or password like '%${keywords}%' )
方案3:用mysql中字符串拼接函數concat
and ( name like concat('%',#{keywords},'%') or password like '%${keywords}%' )
4.若是有特殊符號:
方案1:轉義符號,如「<」能夠寫成"<",">"寫成">"等等
方案2:CDATA(上面的例子已經使用過)
解決表字段名和對象屬性名不同的狀況
關聯對象查詢,在mybatis不會默認查詢出來,須要本身查詢結果而且經過resultMap來配置
表與表之間的關係有:
一對一,一對多,多對一,多對多…
MyBatis提供兩種方式處理咱們關聯對象,嵌套查詢和嵌套結果。
嵌套結果:發送一條sql,查詢全部的信息(自己+關聯對象)
嵌套查詢:發送1+n條sql
1 <!--嵌套結果(多對一),發送一條sql查詢數據--> 2 <resultMap id="studentMap" type="student"> 3 <id property="id" column="id"/> 4 <result property="name" column="name"/> 5 <result property="age" column="age"/> 6 <association property="teacher" javaType="teacher"> 7 <id property="id" column="tid"/> 8 <result property="name" column="tname"/> 9 <result property="age" column="tage"/> 10 </association> 11 </resultMap> 12 <select id="findAll" resultMap="studentMap"> 13 select s.id,s.name,s.age,t.id tid,t.name tname,t.age tage 14 from t_student s join t_teacher t on s.teacher_id=t.id 15 </select>
1 <!--嵌套查詢,發送1+n條sql查詢數據--> 2 <resultMap id="studentMap" type="student"> 3 <id property="id" column="id"/> 4 <result property="name" column="name"/> 5 <result property="age" column="age"/> 6 <association property="teacher" javaType="teacher" column="teacher_id" select="queryByTeacherId"/> 7 </resultMap> 8 <select id="findAll" resultMap="studentMap"> 9 select * from t_student 10 </select> 11 <select id="queryByTeacherId" parameterType="long" resultType="teacher"> 12 select * from t_teacher where id=#{id} 13 </select>
1 <!--嵌套結果(一對多),發送一條sql查詢數據--> 2 <resultMap id="teacherMap" type="teacher"> 3 <id property="id" column="id"/> 4 <result property="name" column="name"/> 5 <result property="age" column="age"/> 6 <collection property="students" javaType="arrayList" ofType="student"> 7 <id property="id" column="sid"/> 8 <result property="name" column="sname"/> 9 <result property="age" column="sage"/> 10 </collection> 11 </resultMap> 12 <select id="findAll" resultMap="teacherMap"> 13 select t.id,t.name,t.age,s.id sid,s.name sname,s.age sage 14 from t_teacher t join t_student s on t.id=s.teacher_id 15 </select>
1 <!--嵌套查詢,發送1+n條sql查詢數據--> 2 <resultMap id="teacherMap" type="teacher"> 3 <id property="id" column="id"/> 4 <result property="name" column="name"/> 5 <result property="age" column="age"/> 6 <collection property="students" column="id" javaType="arrayList" ofType="student" select="queryStudent"/> 7 </resultMap> 8 <select id="findAll" resultMap="teacherMap"> 9 select * from t_teacher 10 </select> 11 <select id="queryStudent" parameterType="long" resultType="student"> 12 select * from t_student where teacher_id=#{id} 13 </select>
一級緩存(自帶)命中條件:同一個EntityManagerFactory,同一個EntityManager,同一個OID
二級緩存(須要配置實現):同一個EntityManagerFactory,不一樣的EntityManager,同一個OID
一級緩存:屬於sqlSession級別,同一個SqlSessionFactory,同一個SqlSession,同一個id
二級緩存:屬於sqlSessionFactory,同一個SqlSessionFactory,不一樣的SqlSession,同一個id
序列化:把對象轉換成二進制形式,方便傳輸(特別須要保存到磁盤或者硬盤,須要進行序列化)
反序列化:把二進制的數據轉換成對象
Spring+SpringMvc+MyBatis
框架集成核心:若是你的項目中,用到了Spring框架,那麼其餘框架主要就是和Spring集成。
那麼和Spring集成的核心思路:
1.把當前框架的核心類交給Spring管理
2.若是框架有事務,那麼事務也要統一交給Spring管理
步驟:
(1)導入jar包:今天以導入jar的方式,不是maven
(2)配置文件
applicationContext.xml:
jdbc.properties--->Datasource ---->SqlSessionFactory----掃描Mapper--->事務管理器-開啓註解事務
1 <?xml version="1.0" encoding="UTF-8"?> 2 <beans xmlns="http://www.springframework.org/schema/beans" 3 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 4 xmlns:context="http://www.springframework.org/schema/context" 5 xmlns:tx="http://www.springframework.org/schema/tx" 6 xsi:schemaLocation=" 7 http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd 8 http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd 9 http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd 10 "> 11 <context:component-scan base-package="cn.itsource.ssm.service"/> 12 <!--讀取jdbc.properties--> 13 <context:property-placeholder location="classpath:jdbc.properties"/> 14 <!--配置鏈接池--> 15 <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close"> 16 <property name="driverClassName" value="${jdbc.driverClassName}" /> 17 <property name="url" value="${jdbc.url}" /> 18 <property name="username" value="${jdbc.username}" /> 19 <property name="password" value="${jdbc.password}" /> 20 </bean> 21 <!--配置SqlSessionFactory--> 22 <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"> 23 <property name="dataSource" ref="dataSource"/> 24 <!--*Mapper.xml的位置--> 25 <property name="mapperLocations" value="classpath:cn/itsource/ssm/mapper/*Mapper.xml"/> 26 <!--別名配置--> 27 <property name="typeAliasesPackage"> 28 <value> 29 cn.itsource.ssm.domain 30 cn.itsource.ssm.query 31 </value> 32 </property> 33 </bean> 34 <!-- 處理mapper接口 spring會掃描包產生不少子類 注入到service層--> 35 <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer"> 36 <property name="basePackage" value="cn.itsource.ssm.mapper"/> 37 </bean> 38 <!--事務配置--> 39 <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> 40 <property name="dataSource" ref="dataSource"/> 41 </bean> 42 <tx:annotation-driven transaction-manager="transactionManager"/> 43 </beans>
applicationContext-mvc.xml:
1 <?xml version="1.0" encoding="UTF-8"?> 2 <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 3 xmlns:context="http://www.springframework.org/schema/context" 4 xmlns:mvc="http://www.springframework.org/schema/mvc" 5 xsi:schemaLocation="http://www.springframework.org/schema/beans 6 http://www.springframework.org/schema/beans/spring-beans.xsd 7 http://www.springframework.org/schema/context 8 http://www.springframework.org/schema/context/spring-context.xsd 9 http://www.springframework.org/schema/mvc 10 http://www.springframework.org/schema/mvc/spring-mvc.xsd"> 11 <!--掃描controller層--> 12 <context:component-scan base-package="cn.itsource.ssm.controller"/> 13 <!--靜態資源放行--> 14 <mvc:default-servlet-handler/> 15 <!--mvc特有註解支持--> 16 <mvc:annotation-driven/> 17 <!--配置視圖解析器--> 18 <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"> 19 <property name="prefix" value="/WEB-INF/views/"/> 20 <property name="suffix" value=".jsp"/> 21 </bean> 22 </beans>
web.xml:
<?xml version="1.0" encoding="UTF-8"?> <web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" version="3.1"> <!--spring核心控制器--> <context-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:applicationContext.xml</param-value> </context-param> <listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener> <!--springMvc核心控制器--> <servlet> <servlet-name>dispatcherServlet</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <init-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:applicationContext-mvc.xml</param-value> </init-param> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>dispatcherServlet</servlet-name> <url-pattern>/</url-pattern> </servlet-mapping> <!--編碼過濾器--> <filter> <filter-name>EncodingFilter</filter-name> <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class> <init-param> <param-name>encoding</param-name> <param-value>utf-8</param-value> </init-param> </filter> <filter-mapping> <filter-name>EncodingFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> </web-app>
(3)包的層次結構: