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,来对列名和属性名进行映射。
动态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语句等使用场景:互联网项目, 电商, 互联网金融, 互联网旅游, 互联网教育等特点: 使用人数不固定不限制, 可以处理高并发, 大数据量的情况
