文章目录
1 映射器Mapper(掌握)
以前:XXXDao(接口) — XXXDaoImpl(实现类)
今天:XXXMapper(接口) —没有实现类(Mybatis底层会采用动态代理模式 会自动生成)
1.1 步骤
-
创建项目 配置mybatis-config.xml文件
-
创建一个接口XXXMapper 里面定义一个接口
-
创建对应的XXXMapper.xml
namespace 和 标签里面id (namespace+id) == (ProductMapper包路径+方法)
<?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd"> <mapper namespace="cn.itsource._01_mapper.mapper.ProductMapper"> <select id="findAll" resultType="product"> select * from product </select> </mapper>
-
创建测试类
@Test public void testMapper(){ //得到mapper --映射器 (动态代理) ProductMapper productMapper = MybatisUtil.INSTANCE.getSqlSession(). getMapper(ProductMapper.class); for (Product product : productMapper.findAll()) { System.out.println(product); } }
2 高级查询注意事项
2.1 sql注入问题
(1)错误写法:
<if test="productName != null">
and productName like '%#{productName}%'
<!--相当于 and productName like '%?%' -->
</if>
正确写法: --存在sql注入问题
<if test="productName != null">
and productName like '%${productName}%'
<!--相当于 and productName like '%XXX%' -->
</if>
正确写法:
<if test="productName != null">
and productName like concat('%',#{productName},'%')
</if>
2.2 特殊符号转义
<!-- salePrice minPrice 和maxPrice之间 特殊符号需要转义-->
<!-- <if test="minPrice != null and maxPrice != null">
and salePrice > #{minPrice} and salePrice < #{maxPrice}
</if>-->
<if test="minPrice != null and maxPrice != null">
<![CDATA[
and salePrice > #{minPrice} and salePrice <= #{maxPrice}
]]>
</if>
2.3 关于$和#使用的第二个问题
update bbs_brand set is_display=0 where id IN (#{ids})
这里只能够使用$ 进行字符串的拼接,而不是#.
当我们传入的字符串是1,3,5,7的时候,用#只能删除id为1的品牌,其他的就不能删除了,这是因为,使用了#,就是一个占位符了,经过编译后是
where id in(?) 加入字符串后是 where id in(‘1,3,5,7’) 这种,在SQL中就只会删除一个原文链接:https://blog.csdn.net/u010398771/article/details/70768280
3 结果映射(掌握)
处理数据库里面的列 和 对象里面的字段 不一统一的情况下
(1)使用别名就可以解决
<select id="findAll" resultType="product">
select id,productName pName,salePrice,costPrice,cutoff from product
</select>
(2)返回Map解决映射问题
<select id="findAll" resultMap="productMap">
select id,productName,salePrice,costPrice,cutoff from product
</select>
<resultMap id="productMap" type="product">
<!-- id:主键
property:类里面的属性
column:查询列名称
-->
<id property="id" column="id"></id>
<result property="pName" column="productName"></result>
<result property="salePrice" column="salePrice"></result>
</resultMap>
4 ResultMap 中collection
原文链接:https://blog.csdn.net/qq_36826506/article/details/81943123
**resultMap是Mybatis最强大的元素,它可以将查询到的复杂数据(比如**查询到**几个表中数据)*映射*到一个结果集当中
<!--column不做限制,可以为任意表的字段,而property须为type 定义的pojo属性-->
<resultMap id="唯一的标识" type="映射的pojo对象">
<id column="表的主键字段,或者可以为查询语句中的别名字段" jdbcType="字段类型" property="映射pojo对象的主键属性" />
<result column="表的一个字段(可以为任意表的一个字段)" jdbcType="字段类型" property="映射到pojo对象的一个属性(须为type定义的pojo对象中的一个属性)"/>
<association property="pojo的一个对象属性" javaType="pojo关联的pojo对象">
<id column="关联pojo对象对应表的主键字段" jdbcType="字段类型" property="关联pojo对象的主席属性"/>
<result column="任意表的字段" jdbcType="字段类型" property="关联pojo对象的属性"/>
</association>
<!-- 集合中的property须为oftype定义的pojo对象的属性-->
<collection property="pojo的集合属性" ofType="集合中的pojo对象">
<id column="集合中pojo对象对应的表的主键字段" jdbcType="字段类型" property="集合中pojo对象的主键属性" />
<result column="可以为任意表的字段" jdbcType="字段类型" property="集合中的pojo对象的属性" />
</collection>
</resultMap>
如果collection标签是使用嵌套查询,格式如下:
<collection column="传递给嵌套查询语句的字段参数" property="pojo对象中集合属性" ofType="集合属性中的pojo对象" select="嵌套的查询语句" >
</collection>
*注意:标签中的column:要传递给select查询语句的参数,如果传递多个参数,格式为column= ” {参数名1=表字段1,参数名2=表字段2} ;
5 关系处理(掌握)
5.1 关系:
- 一对一
- 一对多
- 多对一
- 多对多
5.1.1 mybatis怎么处理关系:
- 一对一 :mybatis处理一方
- 多对一:mybatis处理一方
- 多对多: mybatis处理多方
- 一对多:mybatis处理多方
5.2 对一方处理(多对一/一对一)
5.2.1 嵌套结果: 只发送一条sql
使用嵌套结果映射来处理重复的联合结果的子集。这种方式,所有属性都要自己来
<select id="findAll" resultMap="productMap">
select p.id, p.productName, p.salePrice, p.cutoff, p.costPrice, dir.id did,dir.dirName dname
from product p join productdir dir on p.dir_id=dir.id;
</select>
<resultMap id="productMap" type="product">
<id property="id" column="id"></id>
<result property="pName" column="productName"></result>
<result property="costPrice" column="costPrice"></result>
<result property="salePrice" column="salePrice"></result>
<result property="cutoff" column="cutoff"></result>
0.
<!--处理一方-->
<association property="dir" javaType="ProductDir">
<id column="did" property="id"></id>
<id column="dname" property="dirName"></id>
</association>
<result property="dir.id" column="did"></result>
<result property="dir.dirName" column="dname"></result>
</resultMap>
5.2.2 嵌套查询: 发送 1+n条sql
先将所有产品查询出来 再根据Dir_id查询出一个产品的分类
<select id="findAll" resultMap="productMap">
select p.id, p.productName, p.salePrice, p.cutoff, p.costPrice, p.dir_id
from product p ;
</select>
<resultMap id="productMap" type="product">
<id property="id" column="id"></id>
<result property="pName" column="productName"></result>
<result property="costPrice" column="costPrice"></result>
<result property="salePrice" column="salePrice"></result>
<result property="cutoff" column="cutoff"></result>
<association property="dir" javaType="productDir" column="dir_id" select="selectDir">
</association>
</resultMap>
<select id="selectDir" parameterType="long" resultType="ProductDir">
select * from productDir where id = #{dir_id}
</select>
5.3 对多方进行处理(一对多/多对多)
5.3.1 嵌套结果 一条sql语句
先将所有的结果查询出来 在进行分类
<select id="findAll" resultMap="productDirMap">
select dir.id ,dir.dirName,
p.id pid,p.productName pName,p.salePrice,p.costPrice,p.cutoff
from productDir dir join product p
on dir.id = p.dir_id
</select>
<resultMap id="productDirMap" type="productDir">
<id property="id" column="id"></id>
<result property="dirName" column="dirName"></result>
<collection property="products" ofType="product">
<id property="id" column="pid"></id>
<result property="pName" column="pName"></result>
<result property="salePrice" column="salePrice"></result>
<result property="costPrice" column="costPrice"></result>
</collection>
</resultMap>
5.3.2 嵌套查询 多条sql语句
先查询出一个产品分类 然后将这个产品分类的所有商品查找出来
<select id="findAll" resultMap="productDirMap">
select dir.id ,dir.dirName from productDir dir
</select>
<resultMap id="productDirMap" type="productDir">
<id property="id" column="id"></id>
<result property="dirName" column="dirName"></result>
<collection property="products" column="id" ofType="product" select="selectProducts">
</collection>
</resultMap>
<select id="selectProducts" parameterType="long" resultType="product">
select id,productName pName,salePrice,costPrice,cutoff
from product where dir_id = #{dir_id}
</select>
5.4 延迟加载(了解)
使用的时候,才去加载内容
product.jsp -->展示所有的产品 把产品的分类展示
以后常用项目模式都是前台端分离模式
前后端分离 不能使用延迟加载模式 不能配置Lazy 自动 发送sql去查询 因为他们是不同的服务
5.5 缓存(了解)
5.5.1 mybatis一级缓存
属于sqlSession级别缓存(entityManager类似)
命中条件:
mybatis一级缓存 命中条件(同一个SqlSessionFactory 同一个SqlSession 同一个OID)
@Test
public void testMapper(){
SqlSession sqlSession1 = MybatisUtil.INSTANCE.getSqlSession();
//mybatis一级缓存命中条件
//同一个SqlSessionFactory 同一个SqlSession 同一个ID
ProductMapper mapper1 = sqlSession1.getMapper(ProductMapper.class);
System.out.println(mapper1.findOne(21L));
ProductMapper mapper2 = sqlSession1.getMapper(ProductMapper.class);
System.out.println(mapper2.findOne(21L));
}
5.5.2 mybatis二级缓存
命中条件:同一个SqlSessionFactory 不同的SqlSession 同一个ID
什么叫序列化: 把对象转换成二进制的信息 这个过程
为什么需要序列化: 用在网络传输
反序列化:把二进制内容转成对象的形式 这个过程
6 SSM整合(掌握)
常用开发框架:
sss – springmvc+spring+springjdbc 入门
sssdj – springmvc+spring+springdatajpa 中小型的项目
ssm – springmvc+spring+mybatis 中型项目/大型项目
6.1 整合步骤
-
创建项目
-
导包
-
配置文件
applicationContext.xml 配置spring+mybatis
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context" xmlns:tx="http://www.springframework.org/schema/tx" xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd "> <!--扫描service 自动注入到spring service注解 --> <context:component-scan base-package="cn.itsource.ssm.service"></context:component-scan> <!-- db.proproperties dataSource sqlSessionFactory transaction mapper--> <!--引入jdbc.properties--> <context:property-placeholder location="classpath:db.properties" /> <!--创建dataSource --> <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close"> <property name="driverClassName" value="${jdbc.driverClassName}" /> <property name="url" value="${jdbc.url}" /> <property name="username" value="${jdbc.username}" /> <property name="password" value="${jdbc.password}" /> </bean> <!--sqlSessionFactory --> <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"> <property name="dataSource" ref="dataSource"></property> <property name="mapperLocations" value="classpath:cn/itsource/ssm/mapper/*Mapper.xml"></property> <property name="typeAliasesPackage"> <value> cn.itsource.ssm.domain </value> </property> </bean> <!-- 把产生mapper 交给 spring--> <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer"> <property name="basePackage" value="cn.itsource.ssm.mapper"></property> </bean> <!--事务配置--> <!--配置事务管理器--> <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> <property name="dataSource" ref="dataSource" /> </bean> <!--开启事务注解的支持,默认会去找一个名称叫做transactionManager的事务管理器 --> <tx:annotation-driven transaction-manager="transactionManager" /> </beans>
applicationCotnext-mvc.xml 配置springmvc
<?xml version="1.0" encoding="UTF-8" ?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context" xmlns:mvc="http://www.springframework.org/schema/mvc" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd"> <!--扫描controller--> <context:component-scan base-package="cn.itsource.ssm.web.controller" /> <!--静态资源处理--> <mvc:default-servlet-handler /> <!--识别@RequestMapping等注解支持--> <mvc:annotation-driven /> <!--配置视图解析器--> <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="prefix" value="/WEB-INF/views/" /> <property name="suffix" value=".jsp" /> </bean> </beans>
db.properties --配置数据库
jdbc.driverClassName=com.mysql.jdbc.Driver jdbc.url=jdbc:mysql:///mybatis?createDatabaseIfNotExist=true jdbc.username=root jdbc.password=root
web.xml --配置web的内容
<?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_4_0.xsd" version="4.0"> <!-- 监听器 --> <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> <!--核心控制器--> <servlet> <servlet-name>dispatchServlet</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>dispatchServlet</servlet-name> <url-pattern>/</url-pattern> </servlet-mapping> <!--编码过滤器--> <filter> <filter-name>characterEncodingFilter</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>characterEncodingFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> </web-app>
log4j.properties 日志文件
#log4j.rootLogger=ERROR, stdout #(了解)日志等级: OFF level > FATAL(致命) > ERROR(错误) > WARN (警告)> # INFO (提示)> DEBUG (调试)> trace > ALL level(所有配置) #输出效果 如果你设置日志级别是trace,则大于等于这个级别的日志都会输出 # 关闭日志输出 #log4j.rootLogger=NONE #log4j.rootLogger=NONE ERROR 为严重错误 主要是程序的错误、 # WARN为一般警告,比如session丢失、 # INFO为一般要显示的信息,比如登录登出、 # DEBUG为程序的调试信息 # TRACE 堆栈信息 # 扫描包 配置自己包 log4j.rootLogger=ERROR, stdout #log4j.rootLogger=NONE log4j.logger.cn.itsource=TRACE log4j.appender.stdout=org.apache.log4j.ConsoleAppender log4j.appender.stdout.layout=org.apache.log4j.PatternLayout log4j.appender.stdout.layout.ConversionPattern=%d %p [%c] - %m%n
7 扩展(掌握)
扩展一
<resultMap id="productMap" type="product">
<id column="id" property="id"></id>
<result column="productName" property="pName"></result>
<result column="salePrice" property="salePrice"></result>
<result column="costPrice" property="costPrice"></result>
<result column="cutoff" property="cutoff"></result>
<!-- 处理一方-->
<!--<association property="dir" javaType="productDir">
<id column="did" property="id"></id>
<result column="dname" property="dirName"></result>
</association>-->
<!-- 扩展1-->
<result property="dir.id" column="did"></result>
<result property="dir.dirName" column="dname"></result>
</resultMap>
扩展二 多对多的分页问题
分页 多对多使用 嵌套结果去分页 ,存在小问题
<select id="findAll" resultMap="productDirMap">
select dir.id ,dir.dirName,
p.id pid,p.productName pName,p.salePrice,p.costPrice,p.cutoff
from productDir dir join product p
on dir.id = p.dir_id
limit 0,2
</select>
<resultMap id="productDirMap" type="productDir">
<id property="id" column="id"></id>
<result property="dirName" column="dirName"></result>
<collection property="products" ofType="product">
<id property="id" column="pid"></id>
<result property="pName" column="pName"></result>
<result property="salePrice" column="salePrice"></result>
<result property="costPrice" column="costPrice"></result>
</collection>
</resultMap>
建议使用嵌套查询:
<select id="findAll" resultMap="productDirMap">
select dir.id ,dir.dirName from productDir dir limit 0,2
</select>
<resultMap id="productDirMap" type="productDir">
<id property="id" column="id"></id>
<result property="dirName" column="dirName"></result>
<collection property="products" column="id" ofType="product" select="selectProducts">
</collection>
</resultMap>
<select id="selectProducts" parameterType="long" resultType="product">
select id,productName pName,salePrice,costPrice,cutoff
from product where dir_id = #{dir_id}
</select>
8常见错误
- 写的mapper文件没有在配置文件里面注册
java.lang.IllegalArgumentException: Mapped Statements collection does not contain value for cn.itsource.mybatis.crud.UserMapper.createTable
配置找不到方法
- 返回的结果是List,而需要的是一个对象
org.apache.ibatis.executor.ExecutorException: Statement returned more than one row, where no more than one was expected.
Product findAll()
<select id="findAll"
resultType="cn.itsource.mybatis.c_manytoone.Dept" parameterType="long">
select id,name from t_dept where id=#{id}
</select>
- 没有序列化异常
使用缓存,如果报序列化问题,让类去实现序列化接口
implements Serializable
9 什么是序列化–面试题
把java对象转换二进制过程
什么情况下使用序列化
-
在网络中直接传输一个java对象。
-
在数据库的Blob(二进制)字段(列)中,直接存一个java对象会出问题
-
当前需要把java对象放入内存(本地的临时文件)中
java.io.ObjectInputStream
java.io.ObjectOutputStream
- HttpSession里面存放对象,tomcat的内存不足(500M)的时候,钝化到硬盘