持久层技术解决方案:
JDBC技术:
Connection
PrepareStatement
ResultSet
Spring的JdbcTemplate:Spring中对Jdbc的简单封装
Apache的DBUtils:
它和Spring的JdbcTemplate很像,也是对Jdbc的简单封装
以上这些都不是框架:
JDBC是规范,Spring的JdbcTemplate和Apache的DBUtils都只是工具类
Mybatis是一个优秀的基于java的持久层框架,它内部封装了jdbc,使开发者只需要关注sql语句的本身,而不需要花费精力去处理加载驱动、创建连接、创建statement等繁杂的过程
mybatis通过xml或注解的方式将要执行的各种statment配置起来,并通过java对象和statement中sql的动态参数进行映射生成最终执行的sql语句,最后由mybatis框架执行sql并将结果映射为java对象并返回,它使用了ORM思想实现了结果集的封装。
ORM:
Object Relational Mapping 对象关系映射
简单的说就是把数据库表和实体类及实体类的属性对应起来,让我们可以操作实体类就实现操作数据库表
mybatis的入门:
mybatis 的环境搭建:
第一步:创建maven工程并导入坐标
第二步:创建实体类和dao的接口
第三步:创建Mybatis的主配置文件
环境搭建的注意事项:
- 创建IUserDao.xml 和 IUserDao.java时名称是为了和我们之前的知识保持一致,在Mybatis中它把持久层的操作接口名称和映射文件也叫做:Mapper,所以IUserDao和IUserMapper是一样的
- 在idea中创建目录的时候,它和包是不一样的,包在创建时:com.yutou.dao它是三级结构 目录在创建时:com.yutou.dao是一级目录
- mybatis的映射文件位置必须和dao接口的包结构相同
- 映射配置文件的mapper标签namespace属性的取值必须是dao接口的全限定类名
- 映射配置文件的操作配置,id属性的取值必须是dao接口的方法名
当我们遵从了第三四五点后,在开发中就无需再写dao的实现类
//入门案例
public static void main(String[] args) throws Exception {
//1.读取配置文件
InputStream in = Resources.getResourceAsStream("sqlMapConfig.xml");
//2.创建SqlSessionFactory工厂
SqlSessionFactoryBuilder builder = new SqlSessionFactoryBuilder();
SqlSessionFactory factory = builder.build(in);
//3.使用工厂生产SqlSession对象
SqlSession session = factory.openSession();
//4.使用SqlSession创建Dao接口的代理对象
IUserDao userDao = session.getMapper(IUserDao.class);
//5.使用代理对象执行方法
List<User> users = userDao.findAll();
for (User user : users){
System.out.println(user);
}
//6.释放资源
session.close();
in.close();
}
读取配置文件:
1.使用类加载器,他只能读取类路径的配置文件
2.使用ServletContext对象的getRealPath()
创建工厂Mybatis使用了构建者模式
mybatis基于注解的入门案例:
把IUserDao.xml移除,在dao接口的方法上使用Select注解,并且指定SQL语句,同时需要在SqlMapConfig.xml中的mapper配置时,使用class属性指定dao接口的全限定类名。
在实际开发中,都是越简便越好,所以都是采用不写dao实现类的方法,不管使用XML还是注解配置,但是Mybatis它是支持写dao实现类的。
自定义Mybatis的分析:
mybatis在使用代理dao的方式实现增删改查时可以做到以下两件事:
第一 创建代理对象
第二 在代理对象中调用selectList方法
SqlMapConfig.xml中语句的作用:
连接数据库的信息,有了它们就能创建Connection对象
<!--配置连接数据库的4个基本信息-->
<property name="driver" value="com.mysql.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost:3306/easy_mybatis"/>
<property name="username" value="root"/>
<property name="password" value=""/>
有了它就有了映射配置信息
<mappers>
<mapper resource="com/yutou/dao/IUserDao.xml"/>
</mappers>
以上三段代码读取配置文件,用到的技术就是解析XML的技术(此处用的是dom4j解析xml技术)
1.定义接口方法:
//用户的持久层接口
public interface IUserDao {
//查询所有用户
List<User> findAll();
//保存用户
void saveUser(User user);
//更新用户
void updateUser(User user);
//删除用户
void deleteUser(Integer userId);
//根据id查询用户
User findById(Integer userId);
//根据名称模糊查找用户信息
List<User> findByName(String username);
//查询总用户数
int findTotal();
}
2.配置xml文件
<mapper namespace="com.yutou.dao.IUserDao">
<!--查询所有-->
<select id="findAll" resultType="com.yutou.domain.User">
select * from user;
</select>
<!--保存用户-->
<insert id="saveUser" parameterType="com.yutou.domain.User">
<!--配置插入操作后,获取插入数据的id-->
<selectKey keyProperty="id" keyColumn="id" resultType="int" order="AFTER">
select last_insert_id();
</selectKey>
insert into user(username,address,sex,birthday)value(#{username},#{address},#{sex},#{birthday});
</insert>
<!--更新用户-->
<update id="updateUser" parameterType="com.yutou.domain.User">
update user set username=#{username},address=#{address},sex=#{sex},birthday=#{birthday} where id=#{id}
</update>
<!--删除用户-->
<delete id="deleteUser" parameterType="java.lang.Integer">
delete from user where id = #{uid}
</delete>
<!--根据id查询用户-->
<select id="findById" parameterType="INT" resultType="com.yutou.domain.User">
select * from user where id = #{uid}
</select>
<!--根据名称模糊查询-->
<select id="findByName" parameterType="string" resultType="com.yutou.domain.User">
select * from user where username like #{name}
</select>
<!--获取用户的总记录条数-->
<select id="findTotal" resultType="int">
select count(id) from user;
</select>
</mapper>
Mybatis使用实体类的包装对象作为查询条件:
OGNL表达式: object graphic navigation language
它是通过对象的取值方法来获取数据,在写法上把get给省略了。
parameterType(输入类型):
Mybatis使用Ognl表达式解析对象字段的值,#{}或者${}括号中的值作为Pojo属性名称
如果实体类的属性名和查询列名不相同可以采用以下方法:
<!--配置查询结果的列名和实体类的属性名的对应关系-->
<resultMap id="userMap" type="com.yutou.domain.User">
<!--主键字段的对应-->
<id property="userId" column="id"></id>
<!--非主键字段的对应-->
<result property="userName" column="username"></result>
<result property="userAddress" column="address"></result>
<result property="userSex" column="sex"></result>
<result property="userBirthday" column="birthday"></result>
</resultMap>
<!--配置properties
可以在标签内部配置连接数据库的信息,也可以通过属性引用外部配置文件信息
resource属性:用于指定配置文件的位置,是按照类路径的写法来写,并且必须存在于类路径下。
url属性:是要求按照Url的写法来写地址
http://localhost:8080/mybatisserver/demo1Servlet
协议 主机 端口 URI
URI:Uniform Resource Identifier 统一资源标识符,它是在应用中可以唯一定位一个资源的。
-->
<properties resource="jdbcConfig.properties">
</properties>
2.给数据库列起别名
<!--使用typeAliases配置别名,它只能配置domain中类的别名-->
<typeAliases>
<!-- typeAlias用于配置别名,Type属性指定的是实体类全限定类名,alias属性指定别名,当指定了别名就不再区分大小写-->
<typeAlias type="com.yutou.domain.User" alias="user"></typeAlias>
<!-- 用于指定要配置别名的包,当指定之后,该包下的实体类都会注册别名,并且类名就是别名,不再区分大小写-->
<package name="com.yutou.domain"/>
</typeAliases>
<mappers>
<!-- <mapper resource="com/yutou/dao/IUserDao.xml"/>-->
<!--package标签是用于指定dao接口所在包,当指定了之后就不需要再写mapper以及resource或者class了-->
<package name="com.yutou.dao"/>
</mappers>
连接池:
mybatis中的连接池提供了3种方式的配置
配置的位置:
主配置文件SqlMapConfig.xml种dataSource标签,type属性就说表示采用何种连接池方式
type属性的取值:
POOLED 采用传统的javax.sql.DateSource规范中的连接池,mybatis中针对规范的实现
UNPOOLED 采用传统的获取连接的方式,虽然也实现Javax.sql.DataSource接口,但是并没有采用池的思想
JNDI 采用服务器提供的JNDI技术实现,来获取DataSource对象,不同的服务器所能拿到DataSource不一样,注意:如果不是web或者maven的war工厂是不能使用的
//里面值为true为事务自动提交
sqlSession = factory.openSession(true);
动态sql语句-if标签
<!--根据条件查询-->
<select id="findUserByCondition" resultMap="userMap" parameterType="user">
select * from user
<where>
<if test="userName != null">
and username = #{userName}
</if>
<if test="userSex != null">
and sex = #{userSex}
</if>
</where>
</select>
foreach标签:
<!--根据queryvo中的id集合实现查询用户列表-->
<select id="findUserInIds" resultMap="userMap" parameterType="queryvo">
select * from user
<where>
<if test="ids != null and ids.size()>0">
<foreach collection="ids" open="and id in (" close=")" item="id" separator=",">
#{id}
</foreach>
</if>
</where>
</select>
了解内容:
select * from user;mybatis中的多表查询:
示例:用户和账户
一个用户可以有多个账户
一个账户只能属于一个用户(多个账户也可以属于同一个用户)
步骤:
1.建立两张表:用户表、账户表
让用户表和账户表之间具备一对多的关系,需要使用外键在账户表中添加
2.建立两个实体类:用户实体类和账户实体类
让用户和账户的实体类能体现出来一对多的关系
3.建立两个配置文件
用户、账户的配置文件
4.实现配置
当我们查询用户时,可以同时得到用户下包含的账户信息
当我们查询账户时,可以同时得到账户的所属用户信息
一对一查询操作
<!--定义封装account和User的resultMap-->
<resultMap id="accountUserMap" type="account">
<id property="id" column="aid"></id>
<result property="uid" column="uid"></result>
<result property="money" column="money"></result>
<!--一对一的关系映射,配置封装User的内存-->
<association property="user" column="uid" javaType="user">
<id property="id" column="id"></id>
<result column="username" property="username"></result>
<result column="address" property="address"></result>
<result column="sex" property="sex"></result>
<result column="birthday" property="birthday"></result>
</association>
</resultMap>
<!--查询所有-->
<select id="findAll" resultMap="accountUserMap">
select u.*,a.id as aid,a.uid,a.money from account a ,user u where u.id=a.uid;
</select>
一对多查询操作
<!--定义User的resultMap-->
<resultMap id="userAccountMap" type="user">
<id property="id" column="id"></id>
<result property="username" column="username"></result>
<result property="address" column="address"></result>
<result property="sex" column="sex"></result>
<result property="birthday" column="birthday"></result>
<!--配置user对象中accounts集合的映射-->
<collection property="accounts" ofType="account">
<id column="aid" property="id"></id>
<result column="uid" property="id"></result>
<result column="money" property="money"></result>
</collection>
</resultMap>
多对多查询操作:
<mapper namespace="com.yutou.dao.IRoleDao">
<!--定义role表的ResultMap-->
<resultMap id="roleMap" type="role">
<id property="roleId" column="id"></id>
<result property="roleName" column="role_name"></result>
<result property="roleDesc" column="role_desc"></result>
</resultMap>
<!--查询所有-->
<select id="findAll" resultMap="roleMap">
select * from role;
</select>
</mapper>
延迟加载:在真正使用数据时才发起查询,不用的时候不查询,按需加载(懒加载)
立即加载:不管用不用,只要一调用方法,马上发起查询
一对多,多对多:通常采用延迟加载
多对一,一对一:通常采用立即加载
一对一实现延迟加载:
<!--配置参数-->
<settings>
<!--开启Mybatis支持延迟加载-->
<setting name="lazyLoadingEnabled" value="true"/>
<setting name="aggressiveLazyLoading" value="false"/>
</settings>
<!--一对一的关系映射,配置封装User的内存
select属性指定的内容,查询用户的唯一标识。
column属性指定内容,用户根据id查询时,所需要的参数的值
-->
<association property="user" column="uid" javaType="user" select="com.yutou.dao.IUserDao.findById">
</association>
一对多实现延迟查找:
<!--查询所有-->
<select id="findAll" resultMap="userAccountMap">
select * from user
</select>
缓存是存在于内存中的临时数据
为什么使用缓存?减少和数据库的交互次数,提高执行效率
什么样的数据能使用缓存,什么样的数据不能使用
适用于缓存:
经常查询并且不经常改变的
数据的正确与否对最终的结果影响不大的
Mybatis中的一级缓存和二级缓存:
一级缓存:它指的是mybatis中sqlsession对象的缓存,当我们执行查询之后,查询的结果会同时存入到sqlsession为我们提供一块区域中,该区域的结构是一个Map,当我们再次查询同样的数据,mybatis会先去sqlsession中查询是否有,有的话直接拿出来用
当sqlsession对象消失时,mybatis的一级缓存也就消失了
一级缓存是sqlsession范围的缓存,当调用sqlsession的修改,添加,删除,commit(),close()等方法时,就会清空一级缓存
二级缓存:它指的是Mybatis中sqlsessionFactory对象的缓存,由同一个sqlsessionFactory对象创建的sqlsession共享其缓存
使用步骤:
第一步:让Mybatis框架支持二级缓存(sqlMapConfig.xml中配置)
第二步:让当前的映射文件支持二级缓存(在IUserDao.xml中配置)
第三步:让当前的操作支持二级缓存(在select标签中配置)
Mybatis注解开发
一对一的查询配置
@Select("select * from account")
@Result(id ="accountMap",value={
@Result(id=true,column="id",property="id"),
@Result(column="uid",property="uid"),
@Result(column="money",property="money"),
@Result(property="user",column="uid",one=@One(select="com.yutou.dao.IUseDao.findById",fetchType = FetchType.EAGER))
List<Account> findAll();
})
一对多的查询配置
@Select("select * from account")
@Result(id ="accountMap",value={
@Result(id=true,column="id",property="id"),
@Result(column="uid",property="uid"),
@Result(column="money",property="money"),
@Result(property="user",column="uid",many=@Many(select="com.yutou.dao.IAccountDao.findAccountByUid",fetchType = FetchType.LAZY))
List<User> findAll();
})
使用二级缓存:
1.配置setting
2.使用注解@CachNameSpace(blocking = true)