MyBatis
Mybatis简介
什么是mybatis
MyBatis本是apache的一个开源项目Ibatis,2010年这个项目有apache software foundation迁移到了google code,并且改名为MyBatis。2013年11月迁移到Github。
MyBatis是一个优秀的持久层框架,它对jdbc的操作数据库的过程进行封装,使开发者只需要关注 SQL 本身,而不需要花费精力去处理例如注册驱动、创建connection、创建statement、手动设置参数、结果集检索等jdbc繁杂的过程代码。
Mybatis通过xml或注解的方式将要执行的各种statement(statement、preparedStatemnt、CallableStatement)配置起来,并通过java对象和statement中的sql进行映射生成最终执行的sql语句,最后由mybatis框架执行sql并将结果映射成java对象并返回
Mybatis是apache旗下的顶级一个项目,mybatis是对jdbc的封装的一个持久层框架
架构设计图
mybatis配置
SqlMapConfig.xml,此文件作为mybatis的全局配置文件,配置了mybatis的运行环境等信息。
mapper.xml文件即sql映射文件,文件中配置了操作数据库的sql语句。此文件需要在SqlMapConfig.xml中加载。
通过mybatis环境等配置信息构造SqlSessionFactory即会话工厂
由会话工厂创建sqlSession即会话,操作数据库需要通过sqlSession进行。
mybatis底层自定义了Executor执行器接口操作数据库,Executor接口有两个实现,一个是基本执行器、一个是缓存执行器。
Mapped Statement也是mybatis一个底层封装对象,它包装了mybatis配置信息及sql映射信息等。mapper.xml文件中一个sql对应一个Mapped Statement对象,sql的id即是Mapped statement的id。
Mapped Statement对sql执行输入参数进行定义,包括HashMap、基本类型、pojo,Executor通过Mapped Statement在执行sql前将输入的java对象映射至sql中,输入参数映射就是jdbc编程中对preparedStatement设置参数。
Mapped Statement对sql执行输出结果进行定义,包括HashMap、基本类型、pojo,Executor通过Mapped Statement在执行sql后将输出结果映射至java对象中,输出结果映射过程相当于jdbc编程中对结果的解析处理过程。
MyBatis的核心配置文件
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
<!-- 自定义别名 起了别名 那么在 在 映射文件中的
parameterType="可以用别名" resultType="可以用别名"
<typeAliases>
单个别名定义 给这个全路径定义别名
type:类的全路径
<typeAlias alias="user" type="com.heima.pojo.User"/>
批量别名定义,扫描整个包下的类,别名为类名(首字母大写或小写都可以)
<package name="cn.itcast.mybatis.po"/>
<package name="其它包"/>
</typeAliases> -->
<!-- 引入properties文件 -->
<properties resource="db.properties"/>
<!-- 和spring整合后 environments配置将废除-->
<environments default="development">
<environment id="development">
<!-- 使用jdbc事务管理-->
<transactionManager type="JDBC" />
<!-- 数据库连接池-->
<dataSource type="POOLED">
<property name="driver" value="${db.driver}" />
<property name="url" value="${db.url}" />
<property name="username" value="${db.username}" />
<property name="password" value="${db.password}" />
</dataSource>
</environment>
</environments>
<mappers>
<mapper resource="User.xml"/>
<!-- 加载mapper层的映射配置文件 -->
<mapper resource="com/heima/mapper/UserMapper.xml"/>
<!-- class 加载 代表的加载这个接口的映射文件
用在mapper层(等于dao层)
必须是接口的全路径,映射文件的名称,除了扩展名外,其他必须相同
接口和映射文件在同一个目录
<mapper class="com.heima.mapper.UserMapper"/>-->
<!-- package标签加载 映射文件 用在mapper层(等于dao层)
name:写包的全路径 ,代表加载这个包下所有接口的映射文件
必须是接口的名称和映射文件的名称,除了扩展名外,其他必须相同
接口和映射文件在同一个目录
<package name="com.heima.mapper"/> -->
</mappers>
</configuration>
概览
SqlMapConfig.xml的配置内容和顺序如下(顺序不能乱):
Properties(属性)
Settings(全局参数设置)
typeAliases(类型别名)
typeHandlers(类型处理器)
objectFactory(对象工厂)
plugins(插件)
environments(环境信息集合)
environment(单个环境信息)
transactionManager(事物)
dataSource(数据源)
mappers(映射器)
Properties
Db.properties
SqlMapConfig.xml
加载的顺序
1、 先加载properties中property标签声明的属性
2、 再加载properties标签引入的java配置文件中的属性
3、 parameterType的值会和properties的属性值发生冲突。
settings
mybatis全局配置参数,全局参数将会影响mybatis的运行行为。
Setting(设置) | Description(描述) | Valid Values(验证值组) | Default(默认值) |
cacheEnabled | 在全局范围内启用或禁用缓存配置任何映射器在此配置下。 | true | false | TRUE |
lazyLoadingEnabled | 在全局范围内启用或禁用延迟加载。禁用时,所有协会将热加载。 | true | false | TRUE |
aggressiveLazyLoading | 启用时,有延迟加载属性的对象将被完全加载后调用懒惰的任何属性。否则,每一个属性是按需加载。 | true | false | TRUE |
multipleResultSetsEnabled | 允许或不允许从一个单独的语句(需要兼容的驱动程序)要返回多个结果集。 | true | false | TRUE |
useColumnLabel | 使用列标签,而不是列名。在这方面,不同的驱动有不同的行为。参考驱动文档或测试两种方法来决定你的驱动程序的行为如何。 | true | false | TRUE |
useGeneratedKeys | 允许JDBC支持生成的密钥。兼容的驱动程序是必需的。此设置强制生成的键被使用,如果设置为true,一些驱动会不兼容性,但仍然可以工作。 | true | false | FALSE |
autoMappingBehavior | 指定MyBatis的应如何自动映射列到字段/属性。NONE自动映射。 PARTIAL只会自动映射结果没有嵌套结果映射定义里面。 FULL会自动映射的结果映射任何复杂的(包含嵌套或其他)。 | NONE, PARTIAL, FULL | PARTIAL |
defaultExecutorType | 配置默认执行人。SIMPLE执行人确实没有什么特别的。 REUSE执行器重用准备好的语句。 BATCH执行器重用语句和批处理更新。 | SIMPLE REUSE BATCH | SIMPLE |
defaultStatementTimeout | 设置驱动程序等待一个数据库响应的秒数。 | Any positive integer | Not Set (null) |
safeRowBoundsEnabled | 允许使用嵌套的语句RowBounds。 | true | false | FALSE |
mapUnderscoreToCamelCase | 从经典的数据库列名A_COLUMN启用自动映射到骆驼标识的经典的Java属性名aColumn。 | true | false | FALSE |
localCacheScope | MyBatis的使用本地缓存,以防止循环引用,并加快反复嵌套查询。默认情况下(SESSION)会话期间执行的所有查询缓存。如果localCacheScope=STATMENT本地会话将被用于语句的执行,只是没有将数据共享之间的两个不同的调用相同的SqlSession。 | SESSION | STATEMENT | SESSION |
dbcTypeForNull | 指定为空值时,没有特定的JDBC类型的参数的JDBC类型。有些驱动需要指定列的JDBC类型,但其他像NULL,VARCHAR或OTHER的工作与通用值。 | JdbcType enumeration. Most common are: NULL, VARCHAR and OTHER | OTHER |
lazyLoadTriggerMethods | 指定触发延迟加载的对象的方法。 | A method name list separated by commas | equals,clone,hashCode,toString |
defaultScriptingLanguage | 指定所使用的语言默认为动态SQL生成。 | A type alias or fully qualified class name. | org.apache.ibatis.scripting.xmltags.XMLDynamicLanguageDriver |
callSettersOnNulls | 指定如果setter方法或地图的put方法时,将调用检索到的值是null。它是有用的,当你依靠Map.keySet()或null初始化。注意原语(如整型,布尔等)不会被设置为null。 | true | false | FALSE |
logPrefix | 指定的前缀字串,MyBatis将会增加记录器的名称。 | Any String | Not set |
logImpl | 指定MyBatis的日志实现使用。如果此设置是不存在的记录的实施将自动查找。 | SLF4J | LOG4J | LOG4J2 | JDK_LOGGING | COMMONS_LOGGING | STDOUT_LOGGING | NO_LOGGING | Not set |
proxyFactory | 指定代理工具,MyBatis将会使用创建懒加载能力的对象。 | CGLIB | JAVASSIST |
properties(属性)SqlMapConfig.xml可以引用java属性文件中的配置信息如下:
在classpath下定义db.properties文件,
jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/mybatis?characterEncoding=utf-8
jdbc.username=root
jdbc.password=root
SqlMapConfig.xml引用如下:
<properties resource="db.properties"/>
<environments default="development">
<environment id="development">
<transactionManager type="JDBC"/>
<dataSource type="POOLED">
<property name="driver" value="${jdbc.driver}"/>
<property name="url" value="${jdbc.url}"/>
<property name="username" value="${jdbc.username}"/>
<property name="password" value="${jdbc.password}"/>
</dataSource></environment></environments>
注意: MyBatis 将按照下面的顺序来加载属性:
在 properties 元素体内定义的属性首先被读取。
然后会读取properties 元素中resource或 url 加载的属性,它会覆盖已读取的同名属性。
typeAliases(类型别名)mybatis支持别名:别名映射的类型
_byte byte
_long long
_short short
_int int
_integer int
_double double
_float float
_boolean boolean
string String
byte Byte
long Long
short Short
int Integer
integer Integer
double Double
float Float
boolean Boolean
date Date
decimal BigDecimal
bigdecimal BigDecimal
map Map
传递pojo包装对象开发中通过pojo传递查询条件 ,查询条件是综合的查询条件,不仅包括用户查询条件还包括其它的查询条件(比如将用户购买商品信息也作为查询条件),这时可以使用包装对象传递输入参数:Pojo类中包含pojo。
Dao开发方法原始dao开发------不和spring整合时
//接口public interface MyBatisDao {
public User getUserById(int id) throws Exception;
}
//实现类public class MyBatisDaoImpl implements MyBatisDao{
//通过构造参数在外部创建实现类的时候传入会话工厂
private SqlSessionFactory sqlSessionFactory;
//主要是在测试使用
public MyBatisDaoImpl(SqlSessionFactory sqlSessionFactory) {
this.sqlSessionFactory = sqlSessionFactory;
}
public User getUserById(int id) throws Exception {
SqlSession session = sqlSessionFactory.openSession();User user = null;
try {
//通过sqlsession调用selectOne方法获取一条结果集
//参数1:指定定义的statement的id,参数2:指定向statement中传递的参数
user = session.selectOne("test.findUserById", 1);
System.out.println(user);
} finally{
session.close();
}
return user;
}
原始Dao开发中存在以下问题:
Dao方法体存在重复代码:通过SqlSessionFactory创建SqlSession,调用SqlSession的数据库操作方法
调用sqlSession的数据库操作方法需要指定statement(配置文件 select等标签)的id,这里存在硬编码,不便于维护Mapper动态代理方式
Mapper接口开发方法只需要程序员编写Mapper接口(相当于Dao接口),由Mybatis框架根据接口定义创建接口的动态代理对象,代理对象的方法体同上边Dao接口实现类方法。
Mapper接口开发需要遵循以下规范:
1、 Mapper.xml文件中的namespace与mapper接口的类路径相同。
2、 Mapper接口方法名和Mapper.xml中定义的每个statement的id(CRUD标签的id)相同
3、 Mapper接口方法的输入参数类型和mapper.xml中定义的每个sql 的parameterType的类型相同
4、 Mapper接口方法的输出参数类型和mapper.xml中定义的每个sql的resultType的类型相同动态代理的配置文件和po类的映射文件一样,就是命名空间必须使用接口的全路径
核心配置文件中间加载
<mappers>
<mapper resource="UserMapper.xml"/>
</mappers>
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapperPUBLIC "-//mybatis.org//DTD Mapper 3.0//EN""http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<!-- Mybatis动态代理实现规则:
1.要求映射文件中的namespace必须等于接口的全路径名称
2.要求映射文件中的id必须等于接口方法的方法名
3.要求映射文件中parameterType中的类型必须等于接口的方法的传入参数类型
4.要求文件中的resultType中的类型必须等于接口方法的返回值 -->
<mapper namespace="com.heima.mapper.UserMapper">
<select id="findUserById" parameterType="int" resultType="cn.itcast.pojo.User">
select * from user where id=#{id}
</select>
<!-- sql片段 id sql片段的唯一标识将重复的sql 提取出来 用include 引入 达到sql 重用的目的 -->
<sql id="user_id" >
<where>
<if test="user.username !=null and user.username !='' ">
and username like '%${user.username}%'
</if>
</where>
</sql>
<select id="findUserById" parameterType="java.lang.Integer" resultType="com.heima.pojo.User">
select * from user where id =#{id}
</select>
<select id="findUser" parameterType="com.heima.pojo.QueryVo" resultType="com.heima.pojo.User">
select * from user
<!-- 引入sql片段 -->
<include refid="user_id"/>
</select>
<!-- -->
<select id="findUserByIds" parameterType="com.heima.pojo.QueryVo" resultType="com.heima.pojo.User">
select * from user <if test="list !=null and list.size>0">
<where>
<!--collection:要遍历的集合 写集合的属性名 item:每次遍历到的数据都用此变量接收,变量名可以随意取 open:循环开始时一次性拼接的字符串,后面不在拼接,只出现一次 cloase:循环结束后一次性拼接的字符串 separator:拼接格式(将每次遍历到的数据用什么隔开拼接) -->
<foreach collection="list" item="id" open="id in(" close=")" separator=",">
${id}
</foreach>
</where>
</if>
</select>
<!-- 一对多 查询用resultMap标签 映射type:接口方法的返回结果类型()id:唯一标识 -->
<resultMap type="com.heima.pojo.User" id="userAndorders">
<!-- id标签:主键的映射 column:数据库表的字段名 property:pojo类的属性名 -->
<id column="id" property="id"/>
<!-- 非主键的映射 -->
<result column="username" property="username"/>
<!--collection标签用来表示对应的集合对象property:将查询出来的 Orders类的数据 封装到User类的 oList属性中(一个List集合)ofType:表示这个集合的泛型的类型oList属性的类型, 因为使用了collection标签所以mybatis就知道结果集为一个集合, 所以我们这里要写list中的泛型的类型 -->
<collection property="oList" ofType="com.heima.pojo.Orders">
<!-- id标签指定主键的对应关系column:数据库中的列名property: pojo中的属性名称 -->
<id column="id" property="id"/>
<!-- result:指定非主键的对应关系column:数据库中的列名property: pojo中的属性名称 -->
<result column="user_id" property="userId"/>
</collection>
</resultMap>
<select id="findUserAndOrders" resultMap="userAndorders">
<!—左外连接--> select * from user u left join orders o on u.id=o.user_id </select>
<!-- 一对一查询方式一: 创建一个 pojo类 包含 查询结果的所有字段 返回类型为 新建的那个pojo类-->
<select id="findOrderAndUser" resultType="com.heima.pojo.OrdersAndUser">
SELECT o.*,u.username,u.address FROM orders o,USER u WHERE o.user_id=u.id
</select>
<!-- 一对一查询 方式二 (多对一,一对一的关系)在商品的pojo类中加个 属性 类型 为 用户的 pojo类将查询结果中的字段一一映射到对应的pojo类属性中type type:返回的结果集类型(返回类型为集合的泛型类型)id 唯一标识 --> <resultMap type="com.heima.pojo.Orders" id="findOrderAndUser2">
<!-- id标签指定主键的对应关系column:数据库中的列名property: pojo中的属性名称 -->
<id column="id" property="id"/>
<!-- result:指定非主键的对应关系column:数据库中的列名property: pojo中的属性名称 -->
<result column="user_id" property="userId"/>
<result column="number" property="number"/>
<result column="createtime" property="createtime"/>
<result column="note" property="note"/>
<!-- association 标签 标记的是单个对象的对应关系property:将查询出来的数据 放入到 pojo类中的哪个属性中 :这里查询的是用户的信息,所有放入到这个 pojo类中的 user属性中javaType:要封装的属性类型 (一般是一个pojo类) -->
<association property="user" javaType="com.heima.pojo.User">
<result column="username" property="username"/>
<result column="address" property="address"/>
</association>
</resultMap>
<select id="findOrderAndUser2" resultMap="findOrderAndUser2">
SELECT o.*,u.username,u.address FROM orders o,USER u WHERE o.user_id=u.id
</select>
<!-- 添加 -->
<insert id="saveUser" parameterType="com.heima.pojo.User">
<!-- 查询最后一次插入的id值 keyProperty 将查询到的id主键值 封装到 传入参数 user对象中属性名为 id的属性 -->
<selectKey keyProperty="id" resultType="java.lang.Integer" order="AFTER">
<!--mysql的函数查询最后一次插入的id -->
select LAST_INSERT_ID()
</selectKey>
insert into user(username, birthday, sex, address) value (#{username},#{birthday},#{sex},#{address})
</insert>
</mapper>
定义mapper接口public interface UserMapper {
public User findUserById(Integer id);
public List<User> findUserByUserName(String username);
}
Mapper的单元测试
public class MapperTest {
@Test
public void findUserById() throws Exception{
String resource="SqlMapConfig.xml";
//创字节输入流读取配置文件
InputStream inputStream = Resources.getResourceAsStream(resource);
//创建SqlSession工厂
SqlSessionFactory faction = new SqlSessionFactoryBuilder().build(inputStream);
//获得
sqlsessionSqlSession session = faction.openSession();
//获得代理对象,参数写 接口的Class类
UserMapper mapper = session.getMapper(UserMapper.class);
//调用代理对象方法
User user = mapper.findUserById(1);
System.out.println(user);
}
@Test
public void saveUser() throws Exception{
String resource="SqlMapConfig.xml";
//创字节输入流读取配置文件
InputStream inputStream = Resources.getResourceAsStream(resource);
//创建SqlSession工厂
SqlSessionFactory faction = new SqlSessionFactoryBuilder().build(inputStream);
//获得sqlsession
SqlSession session = faction.openSession();
//获得代理对象,参数写 接口的Class类
UserMapper mapper = session.getMapper(UserMapper.class);
//创建对象User user = new User();user.setAddress("浙江");
user.setBirthdax(new Date());
user.setSex("男");user.setUsername("幻影");
//调用代理对象方法
mapper.saveUser(user);
//添加,并提交事务
session.commit();
session.close();
}
}
MyBatis和spring的整合
1.1.1 SqlMapConfig.xml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configurationPUBLIC "-//mybatis.org//DTD Config 3.0//EN""http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
<typeAliases>
批量别名定义,扫描整个包下的类,别名为类名(首字母大写或小写都可以)
<package name="cn.itcast.mybatis.pojo"/>
</typeAliases><mappers><mapper resource="sqlmap/User.xml"/>
//如果在application配置了 包扫描,那么这就不用配置包扫描了
</mappers>
</configuration>
1.1.2 属性文件classpath:db.properties
db.propertiesdb.driver=com.mysql.jdbc.Driver
db.url=jdbc:mysql://localhost:3306/mybatis?characterEncoding=utf-8
db.username=rootdb.password=123
链接数据库的一些信息ApplicationContext.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context" xmlns:p="http://www.springframework.org/schema/p"
xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsdhttp://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsdhttp://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.0.xsd http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-4.0.xsdhttp://www.springframework.org/schema/util
http://www.springframework.org/schema/util/spring-util-4.0.xsd">
<!-- 加载属性文件 -->
<context:property-placeholder location="classpath:db.properties" />
<!-- 数据库连接池 -->
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close"> <property name="driverClassName" value="${db.driver}" />
<property name="url" value="${db.url}" />
<property name="username" value="${db.username}" />
<property name="password" value="${db.password}" />
<property name="maxActive" value="10" />
<property name="maxIdle" value="5" />
</bean>
<!—配置声明式事务-->
<!-- 配置mybatis的会话工厂 -->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<!-- 加载核心配置文件-->
<property name="configLocation" value="classpath:SqlMapConfig.xml"/>
<!-- 配置所用的数据源 --><property name="dataSource" ref="dataSource"/>
</bean>
<!-- 原始Dao开发方式-->
<bean id="userDao" class="com.itheima.dao.impl.UserDaoImpl">
<property name="sqlSessionFactory" ref="sqlSessionFactory"></property></bean>
<!-- 动态代理方式开发 -->
<!-- 配置单个Mapper
<bean id="userMapper" class="org.mybatis.spring.mapper.MapperFactoryBean">需要实例化的接口
<property name="mapperInterface" value="com.itheima.mapper.UserMapper">
</property>
配置会话工厂
<property name="sqlSessionFactory" ref="sqlSessionFactory">
</property>
</bean> -->
<!-- 使用包扫描的方式批量将mapper加入到环境中(推荐使用 )每个mapper代理对象的id就是类名,首字母小写使用的时候使用该接口的类名来调用,首字母小写mybatis核心配置文件中的包扫描和加载mapper映射文件的配置都可以去掉了-->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<!-- 配置需要扫描的包 使用包扫描: id 为 类名的 首字母小写 那么在SqlMapConfig.xml中就不用再配置<package name=""/> -->
<property name="basePackage" value="com.xxx.mapper"/>
</bean>
</beans>
输入映射和输出映射输入映射:输入的参数 基本类型:Integer Double Boolean等
String List Map po类输出映射:返回值类型 简单类型:Integer Double Boolean String等 只有返回的结果集是一行一列的时候返回值才是简单类型
List map po类使用要求:使用resultType进行结果映射时,需要查询出的列名和映射的对象的属性名一致,才能映射成功。
如果查询的列名和对象的属性名全部不一致,那么映射的对象为空。
如果查询的列名和对象的属性名有一个一致,那么映射的对象不为空,但是只有映射正确那一个属性才有值。
如果查询的sql的列名有别名,那么这个别名就是和属性映射的列名。
resultMap使用要求:
使用resultMap进行结果映射时,不需要查询的列名和映射的属性名必须一致。但是需要声明一个resultMap,来对列名和属性名进行映射。
动态sql高级查询的时候,查询条件有可能多也有可能少,所以我们才需要动态拼接sql语句需求:
根据用户名和性别来查询 查询id为1,16,25数据a)
If 用来判断传入的参数是否为空 字符串 如: a !=null and a!="" ,如果是集合 :如 list !=null and list.size>0
Where 作用:自动添加where关键字 去掉第一个条件的and关键字
Foreach 需求: 综合查询时,会根据用户ID集合进行查询
SELECT * FROM USER WHERE id IN (1,2,10)
用来循环传入的集合参数
例如:List<Integer> collection:要遍历的集合
写集合的属性名
item:每次遍历到的数据都用此变量接收,变量名可以随意取 open:循环开始时一次性拼接的字符串,后面不在拼接,只出现一次 cloase:循环结束后一次性拼接的字符串 separator:拼接格式(将每次遍历到的数据已什么隔开拼接) <foreach collection="遍历的集合" item="接收遍历到的数据" open="" ></foreach>d) Sql片段 <sql id="user_id" > 在其他声明标签内 :如 select标签内 用 include标签 引入 达到sql 重用的目的 <!-- 引入sql片段 --> <include refid="user_id"/>用来封装sql语句, 可以在映射文件中重用注意:如果引用其它mapper.xml的sql片段,则在引用时需要加上namespace,如下:<include refid="namespace.sql片段”/>关联查询一对一关联resultType自动映射: 需要查询出来的列名和放入的pojo类的属性名一致resultMap手动映射: 需要挨个配置查询出的列名和pojo中的属性名称的对应关系对应单个对象关系使用association标签<!-- 一对一查询 方式二 (多对一,一对一的关系)在商品的pojo类中加个 属性 类型 为 用户的 pojo类将查询结果中的字段一一映射到对应的pojo类属性中type type:返回的结果集类型(返回类型为集合的泛型类型)id 唯一标识 --> <resultMap type="com.heima.pojo.Orders" id="findOrderAndUser2"> <!-- id标签指定主键的对应关系column:数据库中的列名property: pojo中的属性名称 --> <id column="id" property="id"/> <!-- result:指定非主键的对应关系column:数据库中的列名property: pojo中的属性名称 --> <result column="user_id" property="userId"/><!-- association 标签 标记的是单个对象的对应关系property:将查询出来的数据 放入到 pojo类中的哪个属性中 :这里查询的是用户的信息,所有放入到这个 pojo类中的 user属性中javaType:要封装的属性类型 (一般是一个pojo类) --><association property="user" javaType="com.heima.pojo.User"><result column="username" property="username"/> <result column="address" property="address"/> </association> </resultMap> <select id="findOrderAndUser2" resultMap="findOrderAndUser2">SELECT o.*,u.username,u.address FROM orders o,USER u WHERE o.user_id=u.id</select>一对多关联:一对多关系映射:只能使用resultMap来进行手动的数据库中的列名和pojo中的属性的一一指定对应集合对象可以使用collection标签<resultMap type="com.itheima.pojo.User" id="UserAndOrders"> <id column="id" property="id"/><!-- 非主键的映射 --> <result column="username" property="username"/><!-- 一对多 关联映射 collection标签用来表示对应的集合对象关系,表示关联查询结果集property: 关联查询的结果集存储在代表 一方的po类中的上哪个属性上。 将查询到代表多方的po类的数据封装到代表 一方的po类中 的oList属性(集合属性)中,写集合的属性名 ofType: 指定关联查询的结果集中的对象类型即List中的对象类型。多方的返回值的类型(集合的泛型类型) 此处可以使用别名,也可以使用全路径定名。因为使用了collection标签所以mybatis就知道结果集为一个集合, 所以我们这里要写list中的泛型的类型 --><collection property="oList" ofType="com.itheima.pojo.Orders" > <id column="id" property="id"/>//主键映射 <result column="user_id" property="userId"/>非主键映射 </collection> </resultMap> <!-- 动态代理方式 statement 的 id的值 必须和接口的方法名相同 --> <select id="findUserAndOrders" resultMap="UserAndOrders" > select * from user u left join orders o on u.id=o.user_id </select>#{}与${}的区别#和$#{}表示一个占位符,#{}接受传入参数,类型可以是基本类型,pojo,map如果接受的是基本类型的值,那么#{}括号中可以任意或者value如果#{}获取是的pojo,mybatis通过ognl获取参数值。Ognl就是对象导航语言 属性.属性.属性的方式获取值。如果传递是map值,#{}中需要的是map的key${}表示拼接sql,会引入sql注入,不建议使用${}接受输入参数可以是pojo,基本类型,map${}如果接受的是基本类型,只能是value${}接受pojo类型的参数,通过ognl对象导航进行获取mybatis和hibernate区别 hibernate: 它是一个orm框架(关系映射), hibernate学习成本高, 比较复杂. 自动化程度高, 不用写sql语句,使用hibernate可以缩短开发周期, 因为不用写sql语句等. 由于程序员水平不等, 所以hql执行效率不高又不好优化.使用场景: 传统项目, oa(办公系统), crm(客户关系管理系统), erp(大型企业管理信息化系统)特点: 使用人数固定, 并发量不高, 数据量不大.mybatis: 它不是一个完全的orm框架, 就是对jdbc的一个轻量级封装. 学习成本低, 比较简单.需要自己写sql语句. 优点是执行效率高, 缺点就是写的代码比较多, 因为需要手写sql语句等使用场景:互联网项目, 电商, 互联网金融, 互联网旅游, 互联网教育等特点: 使用人数不固定不限制, 可以处理高并发, 大数据量的情况