一.SQL映射器Mapper
1.1引入
MyBatis基于动态代理机制,让我们无需再编写Dao的实现。
传统Dao接口,现在名称统一以Mapper结尾,还有我们映射器配置文件要和映射器在同一个包.:
IDeptDao---->DeptMapper.java—DeptMapper.xml(namespace直接写DeptMapper.java的全限定名)
映射文件
<mapper namespace="cn.itsource._01_mybatis.IUserDao">
<!-- 查询 queryAll()
resultType 返回类型
-->
<select id="findAll" resultType="User">
select * from t_user
</select>
</mapper>
1.2实现
package cn.itsource._01_mybatis;
import cn.itsource.utils.MybatisUtils;
import org.apache.ibatis.session.SqlSession;
import java.util.List;
public class UserDaoImpl implements IUserDao{
@Override
public List<User> findAll() {
SqlSession sqlSession = MybatisUtils.INSTANCE.getSqlSession();
List<User> users = sqlSession.selectList("cn.itsource._01_mybatis.IUserDao.findAll");
return users;
}
}
1.3使用映射器步骤
1、根据需求,创建模型相关的Mapper接口(UserMapper)
2、编写映射文件
a)Mapper。Xml的命名空间,必须和接口的“全限定名”一致
b)定义sql标签的id,需要和“接口的方法”一致
3、配置映射文件
4、测试
二.高级查询
2.1需求
做学生高级查询,高级查询条件有两个:
1)关键字–作用于name或password
2)年龄区间(minAge,maxAge)-作用于age
2.2实现
1)定义映射去接口-EmployeeMapper
List query(EmployeeQuery query);
2)写映射文件并且导入核心配置文件
3)做测试
注意:
1 where:里面所有的条件如果都在前面加上and,并且最后会把第一个and替换为where
2 if 判断条件是否满足,如果是并且用and
3 模糊查询
方案1: 不能用#
and ( name like %#{keywords}% or password like %#{keywords}% )
方案2:用$ sql注入
and ( name like ‘%
k
e
y
w
o
r
d
s
{keywords}%' or password like '%
keywords{keywords}%’ )
方案3:用mysql中字符串拼接函数concat
and ( name like concat(’%’,#{keywords},’%’) or password like ‘%${keywords}%’ )
4 如果有特殊符号
方案1:转义符号
<!–and saleprice <= #{maxSalePrice}
方案2:cdata
<![CDATA[ and saleprice <= #{maxSalePrice} ]]>
三.结果映射(resultMap)
3.1为什么要使用结果映射
解决表字段名和对象属性名不一样的情况.
关联对象查询,在mybatis不会默认查询出来,需要自己查询结果并且通过resultMap来配置
3.2.关联映射分类
一对一:一个员工只有一个身份证号。随意一方设计一个字段
多对一:多个员工对应一个部门。一般在多方设计一个一方属性 员工里面设计部门字段
一对多:一个部门拥有多个员工。还是在多方维护对象关联关系
多对多: 一个员工有多个角色。一个角色属于多个员工。用中间表来表示
本质上:多对一,一对一是一样的,都只是处理一个(association )。而一对多、多对多也是一样处理的都是集合(collection)
3.3.关联映射处理方式
MyBatis提供两种方式处理我们关联对象,嵌套查询和嵌套结果。
嵌套结果: 发送1条SQL,查询所有的信息(本身+关联对象)
嵌套查询:发送1+N条sql。
接下来,分别使用两种方式对多对一、一对一和一对多、多对多进行处理。
– 查询员工时要把一起获取到,sql怎么?
– 1 嵌套结果(一条SQL查询出来)
SELECT
e.id,e.name,e.password,e.age, d.id did,d.name dname
FROM
t_employee e
LEFT JOIN t_dept d ON e.dept_id = d.id
WHERE
e.id = 1
– 2 嵌套查询(1+N条sql)
SELECT * from t_employee
SELECT * from t_dept where id = 1
3.4多对一,一对一
<!--嵌套查询 1+n条数据查询-->
<resultMap id="studentMap" type="student">
<id property="id" column="id"></id>
<result property="name" column="name"></result>
<result property="hobby" column="hobby"></result>
<association property="teacher" column="tid" javaType="Teacher" select="queryTeacherByTid">
</association>
</resultMap>
<select id="queryAll" resultMap="studentMap">
select * from t_student s
</select>
<select id="queryTeacherByTid" parameterType="long" resultType="Teacher">
select * from t_teacher where id=#{id}
</select>
</mapper>
3.5一对多
<!-- 嵌套查询-->
<resultMap id="teacherMap" type="Teacher">
<id property="id" column="id"></id>
<result property="name" column="name"></result>
<result property="age" column="age"></result>
<collection property="students" column="id" javaType="arraylist"
ofType="student" select="findStudentsByTid">
</collection>
</resultMap>
<select id="findAll" resultMap="teacherMap">
SELECT t.id,t,name,t.age from t_teacher t
</select>
<select id="findStudentsByTid" parameterType="long" resultType="student">
select * from t_student where tid=#{tid}
</select>
</mapper>
四.SSM集成
4.1
SpringMvc+Spring+Mybatis
框架集成核心
如果你的项目中,用到了Spring框架,那么其他框架主要就是和Spring集成!!
和Spring集成的核心思路
1、把当前框架的核心类,交给Spring管理
2、如果框架有事务,那么事务也要统一交给Spring管理
步骤:
Spring
Spring+SpringMVC
Spring+Mybtis
Spring+SpringMVC+Mybatis:管理事务
jar:今天以导入jar的方式,不是maven
4.1.
4.1.1.单独集成Spring
4.1.2.创建javaweb项目
4.1.3.导入springjar
4.1.4.准备配置文件applicationContext.xml,并且配置对象
配置:applicationContext.xml
配置bean
4.1.5.测试
4.2.Spring+SpringMV
4.2.1.导入jar
4.2.2.配置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>
<!--核心控制器-->
<servlet>
<servlet-name>dispatchServlet</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>concontextConfigLocationtext</param-name>
<param-value>classpath:applicationContext-mvc.xml</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>dispatchServlet</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>
4.2.3.applicationContext-mvc.xml
<?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.controller" />
<!--静态资源处理-->
<mvc:default-servlet-handler />
<!--识别@requestMapper等注解支持-->
<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>
4.3.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层-->
<context:component-scan base-package="cn.itsource.ssm.service"/>
<!--引入jdbc.properties-->
<context:property-placeholder location="classpath:jdbc.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 -> SqlSessionFactoryBean
-->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<!--连接池-->
<property name="dataSource" ref="dataSource" />
<property name="mapperLocations" value="classpath:cn/itsource/ssm/mapper/*Mapper.xml" />
<!--typeAliasesPackage:这个包中所的值都会取相应的别名-->
<property name="typeAliasesPackage">
<value>
cn.itsource.ssm.domain
cn.itsource.ssm.query
</value>
</property>
</bean>
<!-- 一劳永逸
Mapper(映射)Scanner(扫描)Configurer(配置)
basePackage:扫描的包(会用对象的类都创建实现)
-->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="basePackage" value="cn.itsource.ssm.mapper" />
</bean>
<!--事务配置-->
<!--配置事务管理器-->
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource" />
</bean>
<!--开启事务注解的支持,默认会去找一个名称叫做transactionManager的事务管理器 -->
<tx:annotation-driven transaction-manager="transactionManager" />
</beans>