MyBatis进阶讲解+ssm集成
Posted wings丶xh
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了MyBatis进阶讲解+ssm集成相关的知识,希望对你有一定的参考价值。
1.sql映射器Mapper
MyBatis基于动态代理机制,让我们无需再编写Dao的实现。
传统Dao接口,现在名称统一以Mapper结尾,还有我们映射器配置文件要和映射器在同一个包。
1.1使用映射器步骤:
(1)根据需求,创建模型相关的Mapper接口
(2)编写映射文件
a)*Mapper.xml的命名空间,必须和接口的“全限定名”一致
b)定义sql标签的id,需要和“接口的方法”一致
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)测试
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 }
2.高级查询
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替换为where
2.if 判断条件是否满足,如果是并且用and
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(上面的例子已经使用过)
3.ResultMap结果集映射
3.1为什么要使用结果映射
解决表字段名和对象属性名不一样的情况
关联对象查询,在mybatis不会默认查询出来,需要自己查询结果并且通过resultMap来配置
3.2关联映射分类
表与表之间的关系有:
一对一,一对多,多对一,多对多…
3.3关联映射处理方式
MyBatis提供两种方式处理我们关联对象,嵌套查询和嵌套结果。
嵌套结果:发送一条sql,查询所有的信息(本身+关联对象)
嵌套查询:发送1+n条sql
3.3.1多对一(一对一)——嵌套结果
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>
3.3.2多对一(一对一)——嵌套查询
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>
3.3.3一对多(多对多)——嵌套结果
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>
3.3.4一对多(多对多)——嵌套查询
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>
4.缓存
4.1 jpa
一级缓存(自带)命中条件:同一个EntityManagerFactory,同一个EntityManager,同一个OID
二级缓存(需要配置实现):同一个EntityManagerFactory,不同的EntityManager,同一个OID
4.2 MyBatis
一级缓存:属于sqlSession级别,同一个SqlSessionFactory,同一个SqlSession,同一个id
二级缓存:属于sqlSessionFactory,同一个SqlSessionFactory,不同的SqlSession,同一个id
序列化:把对象转换成二进制形式,方便传输(特别需要保存到磁盘或者硬盘,需要进行序列化)
反序列化:把二进制的数据转换成对象
5.SSM集成
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)包的层次结构:
以上是关于MyBatis进阶讲解+ssm集成的主要内容,如果未能解决你的问题,请参考以下文章
Spring+SpringMvc+Mybatis框架集成搭建教程一(背景介绍及项目创建)
SSM-MyBatis-05:Mybatis中别名,sql片段和模糊查询加getMapper