一、MyBatis入门
- 什么是框架?
是给开发者进行二次开发的骨架,是软件开发中的一套解决方案,不同的框架解决不同的问题。 - 三成架构
表现层(展示数据)、业务层(处理业务需求)、持久层(与数据库进行交互) - 持久层技术解决方案
JDBC技术
Spring的JdbcTemplate
Apache的DBUtils
以上这些都不是框架,只是规范
二、MyBatis的概述
- mybatis的概念:
MyBatis是一个使用java编写的持久层框架。
封装了JDBC操作的很多细节,是开发者只需要关注sql本身,无需关注注册驱动,创建连接等
它使用了ORM思想来实现结果集的封装
ORM(Object Relational Mapping)对象关系映射
简单地说:
就是将数据库表和实体类的属性一一对应,让我们可以通过操纵实体类就实现操纵数据库表。
三、MyBatis的环境搭建
-
mybatis的环境搭建
第一步:创建maven工程并导入坐标
第二步:创建实体类和dao的接口
第三步:创建MyBatis的主配置文件 SQLMapConfig.xml
第四步:创建映射配置文件 UserDao.xml
环境搭建的注意事项: -
创建UserDao.xml和UserDao.java时名称一致是为了和我们之前的知识保持一致
-
在idea创建目录的时候,java里面和resources里面是不一样的,java用.分层,resources用 / 分层
-
mybatis的映射配置文件位置必须和dao接口的包结构一致
-
映射文件的mapper标签namespace属性取值,必须是dao接口的全限定类名
-
配置文件的操作设置select,id属性的取值必须是dao接口的全方法名
当我们遵从第三第四第五点之后,就无需编写dao的实现类。
四、MyBatis入门案例
- 创建maven工厂并导入坐标
导入坐标:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.itheima</groupId>
<artifactId>mybatis</artifactId>
<version>1.0-SNAPSHOT</version>
<!--将打包方式写完jar包方式-->
<packaging>jar</packaging>
<dependencies>
<!--mybatis坐标-->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.4.5</version>
</dependency>
<!--mysql坐标-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.6</version>
</dependency>
<!--日志坐标-->
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.12</version>
</dependency>
<!--测试工具坐标-->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.10</version>
</dependency>
</dependencies>
</project>
- 创建实体类和dao接口
包结构图
实体类(省去set get 方法,以后用lombok实现)
/**
*变量信息要同数据表中结构一致
*/
public class User {
private Integer id;
private String username;
private Date birthday;
private String sex;
private String address;
}
接口
public interface UserDao {
/**
* 查询所有操作
*/
List<User> findAll();
}
- 创建mysql的主配置文件,对文件名称没有要求,位置放在resources目录下
<?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">
<!--myabtis的主配置文件-->
<configuration>
<!--配置环境-->
<environments default="development">
<!--配置mysql环境-->
<environment id="development">
<!--配置事务的类型-->
<transactionManager type="JDBC"/>
<!--配置数据源(连接池)-->
<dataSource type="POOLED">
<!--配置连接数据库的基本信息-->
<property name="driver" value="com.mysql.jdbc.Driver"/>
<property name="url" value="jdbc:mysql:///db10"/>
<property name="username" value="root"/>
<property name="password" value="root"/>
</dataSource>
</environment>
</environments>
<!--mybatis的映射文件配置,指定配置文件的位置-->
<mappers>
<mapper resource="com/itheima/Dao/UserDao.xml"/>
</mappers>
</configuration>
创建接口文件的映射文件要求名称跟接口名称一模一样+.xml,其所在包结构同接口一致
<?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="com.itheima.dao.UserDao">
<!--配置查询所有,resultType表示返回结果封装成对象的类型-->
<select id="findAll" resultType="com.itheima.domain.User">
select * from user
</select>
</mapper>
创建测试类,检测能否正常完成数据操作
基本流程:
1.读取配置文件:使用Resouce.getResourceAsSrteam(“映射文件名称”);将映射文件读取流,读取配置文件的建议使用的两种方式:使用类加载器,只能读取类路径的配置文件。使用ServletContext对象的getRealPath方法。
2.创建SqlSessionFactory对象,因为是接口不能直接new,所以使用SqlSessionFactoryBuider对象创建工厂。创建工厂mybatis使用了构建者模式,SqlSessionFactoryBulider就是构建者。构建者模式:把对象创建的细节隐藏,是使用者直接通过调用方法就可以拿到对象。
3.使用SqlSessionFactory的openSession()方法,生产SqlSession对象。sqlSession使用工厂模式。工厂模式的优势,解耦,降低类之间的依赖关系。
4.使用SqlSession创建dao接口的代理对象,使用了代理模式,优势:不修改源码的基础上对已有方法增强。
5.使用代理对象执行方法
6.处理结果
7.释放资源,需要释放sqlSession和InputStream输入流资源
具体实现代码如下:
public class MybatisTest {
/**
* 入门案例
*/
public static void main(String[] args) throws IOException {
//读取配置文件
InputStream ip = Resources.getResourceAsStream("SqlMapConfig.xml");
//创建SqlSessionFactory工厂,sqlSessionFactory是一个接口,需要实现
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(ip);
//使用工厂生产一个SqlSession对象
SqlSession sqlSession = sqlSessionFactory.openSession();
//使用SqlSession创建dao接口的代理对象
UserDao userDao = sqlSession.getMapper(UserDao.class);
//使用代理对象执行方法
List<User> users = userDao.findAll();
//遍历结果
for (User user : users) {
System.out.println(user);
}
//释放资源
sqlSession.close();
ip.close();
}
}
使用注解开发:
- 首先映射的xml接口文件就没有意义了
- 在接口类的findAll方法上加上@Select(“select语句”)
- 将SqlMapConfig.xml文件中的mapper映射修改如下:
注意:resource路径之间使用/,注解开发使用 .
五、自定义MyBatis框架
- 有了他就能创建Connection连接对象
- 有了它就有了映射配置信息
- 有了他就有了执行的SQL语句,就可以获取PreparedStatement对象
读取XML文件用到的技术是:dom4j解析xml技术
向下走:
- 根据配置文件的信息创建Connection对象
注册驱动,获取连接 - 获取预处理的PreparedStatement
此处需要sql语句 - 执行查询
ResultSet resultSet = new ArrayList(); - 遍历结果集用于封装
List list = new ArrayList();
while(list.next()){
E element = Class.forName(配置文件的全限定类名).newInstance();
进行封装,将每个rs的内容添加到element中
我们的实体类属性和表中的列名是一致的
于是我们可以吧表的列名看成是实体类的属性名称
就可以使用反射的方式来根据名称偶去每个属性,并把赋值进去
list.add(element);
}
返回list; - 自定义mybatis的分析:
mybatis在使用代理dao的方式实现增伤改查时做什么事情?
1. 创建代理对象
2.在代理对象中调用selectList
自定义mybatis能通过入门案例看到的类:
Class Resource
Class SqlSessionFactoryBuilder
interface SqlSessionFactory
六、MyBatis的CRUD
- mybatis的crud操作
- CRUD中可能遇到的一些问题
- mybatis主配置文件中的常用配置:
properties标签
typeAliases标签,别名
mappers标签的子标签:package - OGNL表达式:
Object Graphic Navigation language
对象 图 导航 语言
通过对象的取值方法来获得数据,在写法上把get省略,
比如:想获取用户的名称
类中的写法:user.getUsername();
OGNL写法:user.username
mybatis中可以直接写username,而不用user.
因为parameterType中已经提供了属性所属的类。
以下是实例代码:
mybatis的crud操作
外置jdbc.properties文件,内含数据库驱动、url、mysql用户名、密码
jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql:///db10?characterEncoding=UTF-8
jdbc.username=root
jdbc.password=roo
SqlMapConfig.xml文件:
<?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">
<!--myabtis的主配置文件-->
<configuration>
<!--使用property标签进行配置-->
<!--<properties>
<property name="driver" value="com.mysql.jdbc.Driver"/>
<property name="url" value="jdbc:mysql:///db10?characterEncoding=UTF-8"/>
<property name="username" value="root"/>
<property name="password" value="root"/>
</properties>-->
<!--使用外部配置文件进行配置
可以在标签内部配置连接数据库的信息,也可以通过属性引用外部配置文件信息
resources属性:
用于指定配置文件的位置,是按照类路径的写法来写,并切必须存在于类路径下。
url属性:
是要求按照url属性的写法来写地址
URL:Uniform Resource Locator 统一资源定位符。可以为一标识一个资源的位置
写法:
http://localhost:8080/mybatis/demo
协议 主机 端口 URI(Uniform Resource Identifier 统一资源标识符)
-->
<properties resource="jdbcConfig.properties"></properties>
<!--使用typeAliases配置别名,-->
<typeAliases>
<!--typeAlias标签中的type标签指定实体类全限定类名,alias指定别名-->
<typeAlias type="com.itheima.domain.User" alias="user"/>
<!--指定需要配置别名的包,别名为类名且不区分大小写-->
<package name="com.itheima.domain"/>
</typeAliases>
<!--配置环境-->
<environments default="mysql">
<!--配置mysql环境-->
<environment id="mysql">
<!--配置事务类型-->
<transactionManager type="JDBC"></transactionManager>
<!--配置数据源,数据库连接池-->
<dataSource type="POOLED">
<!--配置数据库信息-->
<!--注意value值同jdbcConfig.properties文件中命名一致-->
<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>
<mappers>
<!--<mapper resource="com/itheima/dao/UserDao.xml"/>-->
<!--package标签用于指定dao接口所在的包,指定完成之后就不需要mapper,resource,class标签
自己就可以找到dao接口以及dao接口所对应的映射配置-->
<package name="com.itheima.dao"/>
</mappers>
</configuration>
实体类:省去getter 、setter方法
public class User implements Serializable {
private Integer id;
private String username;
private Date birthday;
private String sex;
private String address;
}
Dao层(持久层):
public interface UserDao {
/**
* 查询全部,返回User集合
* @return
*/
List<User> findAll();
/**
* 添加用户
* @param user
*/
void addUser(User user);
/**
* 删除用户
* @param id
* @return
*/
int deleteUser(int id);
/**
* 更新用户
* @param user
* @return
*/
int updateUser(User user);
/**
* 根据id查询单个用户
* @param id
* @return
*/
User findById(int id);
/**
*根据用户名模糊查询
* @param username
* @return
*/
List<User> findByNameHu(String username);
/**
* 查询总用户数
* @return
*/
Integer findTotal();
/**
* 根据QueryVo查询中的条件查询用户
* @param v
* @return
*/
List<User> findByQueryVo(QueryVo v);
}
Dao-持久层对应的映射配置文件:
<?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="com.itheima.dao.UserDao">
<!--配置 查询结果的类名和实体类的属性名的对应关系-->
<resultMap id="getUsers" type="User">
<id property="id" column="id"></id>
<result property="username" column="username"></result>
<result property="birthday" column="birthday"></result>
<result property="sex" column="sex"></result>
<result property="address" column="address"></result>
</resultMap>
<!--配置查询所有,resultType表示返回结果封装成对象的类型-->
<select id="findAll" resultMap="getUsers">
select * from user
</select>
<!--新增用户-->
<insert id="addUser" parameterType="com.itheima.domain.User">
<selectKey keyProperty="id" keyColumn="id" resultType="int" order="AFTER">
select last_insert_id();
</selectKey>
insert into user(username,birthday,sex,address) values (#{username},#{birthday},#{sex},#{address});
</insert>
<!--更新用户-->
<update id="updateUser" parameterType="com.itheima.domain.User">
update user set username=#{username},birthday=#{birthday},sex=#{sex},address=#{address} where id=#{id};
</update>
<!--删除单个用户-->
<delete id="deleteUser" parameterType="java.lang.Integer">
delete from user where id=#{id};
</delete>
<!--根据查询单个用户-->
<select id="findById" parameterType="Integer" resultType="com.itheima.domain.User">
select * from user where id=#{id};
</select>
<!--根据名称模糊查询-->
<select id="findByNameHu" parameterType="java.lang.String" resultType="com.itheima.domain.User">
/*select * from user where username like #{name};*/
select * from user where username like '%${value}%';
</select>
<!--获取用户总数-->
<select id="findTotal" resultType="Integer">
select count(id) from user;
</select>
<!--根据QueryVO的条件查询用户-->
<select id="findByQueryVo" parameterType="com.itheima.domain.QueryVo" resultType="com.itheima.domain.User">
select * from user where username like #{user.username};
</select>
</mapper>
测试类:
public class MybatisTest {
private InputStream in;
private SqlSession sqlSession;
private UserDao mapper;
@Before //用于测试方法之前执行
public void init() throws IOException {
//1.读取配置文件,生成字节输入流
in = Resources.getResourceAsStream("SqlMapConfig.xml");
//2.获取sqlSessionFactory
SqlSessionFactory build = new SqlSessionFactoryBuilder().build(in);
//3.获取sqlSession对象
sqlSession = build.openSession();
//4.获取dao的代理对象
mapper = sqlSession.getMapper(UserDao.class);
}
//在测试方法之后运行
@After
public void destroy() throws IOException {
//释放资源
sqlSession.close();
in.close();
}
//查询全部
@Test
public void findAll(){
//5.执行sql
List<User> all = mapper.findAll();
//6.打印user
for (User user : all) {
System.out.println(user);
}
}
//添加用户
@Test
public void testAdd () throws IOException {
User user = new User();
user.setUsername("adduser last_insert");
user.setAddress("安徽");
user.setSex("男");
user.setBirthday(new Date());
System.out.println("保存前"+user);
//5.执行sql
mapper.addUser(user);
System.out.println("保存后"+user);
sqlSession.commit();
}
//更新用户
@Test
public void updateTest(){
User user = new User();
user.setId(48);
user.setUsername("adduser");
user.setAddress("安徽");
user.setSex("男");
user.setBirthday(new Date());
mapper.updateUser(user);
sqlSession.commit();
}
//删除用户
@Test
public void deleteTest(){
mapper.deleteUser(48);
sqlSession.commit();
}
/**
* 模糊查询
*/
@Test
public void mohuchaxun(){
List<User> users = mapper.findByNameHu("王");
for (User user : users) {
System.out.println(user);
}
sqlSession.commit();
}
/**
* 查询用户数
*/
@Test
public void findTotal(){
System.out.println(mapper.findTotal());
}
@Test
public void findUserByQueryVo(){
QueryVo o = new QueryVo();
User user = new User();
user.setUsername("%王%");
o.setUser(user);
List<User> users= mapper.findByQueryVo(o);
for (User user1 : users) {
System.out.println(user1);
}
sqlSession.commit();
}
@Test
public void findById(){
User user = mapper.findById(43);
System.out.println(user);
}
七、Mybatis中的连接池以及数据深入
1. mybatis的连接池以及事务控制 (原理部分了解,应用部分会用)
mybatis中连接池使用分析
1.连接池:
就是一个容器(集合对象),该集合必须是线程安全的不能
同一个连接被两个线程同时使用。
该集合还必须实现队列的特性,就是先进先出。
2. mybatis中的连接池
mybatis连接池提供了三种方式的配置:
配置的位置:
主配置文件SQlMapConfig.xml中的datasource标签
type属性:
POOLED 传统javax.sql.DataSource规范的连接池
UNPOOLED 传统放入获取连接的方式,没有池的
思想。
JNDI 是服务器提供的JNDI实现,来获取对象
注意不是web或者maven的war工程,不能用
我们课程使用tomcat服务器,采用连接池为
dbcp连接池。
UNPOOLED与POOLED
mybatis中事务控制的分析
2. mybatis基于XML配置的动态SQL语句 (会用即可)
mybatis配置文件中的常用标签:
< if >
< where >
< for each>
< sql >
动态sql示例代码:
List<User> findUserByCondition(User user);
<?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="com.itheima.dao.UserDao">
<!--配置 查询结果的类名和实体类的属性名的对应关系-->
<resultMap id="getUsers" type="user">
<id property="id" column="id"></id>
<result property="username" column="username"></result>
<result property="birthday" column="birthday"></result>
<result property="sex" column="sex"></result>
<result property="address" column="address"></result>
</resultMap>
<!--抽取重复的sql语句-->
<sql id="defaultUser">
select * from user
</sql>
<!--根据条件查询-->
<select id="findUserByCondition" resultMap="getUsers" parameterType="com.itheima.domain.User">
<include refid="defaultUser"/>
<where>
<if test="username != null">
username =#{username}
</if>
<if test="sex != null">
and sex =#{sex}
</if>
<if test="address != null">
and address =#{address}
</if>
</where>
</select>
<!--根据QueryVO的id集合查询用户-->
<select id="findUserByIds" parameterType="com.itheima.domain.QueryVo" resultMap="getUsers">
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>
</mapper>
//根据条件查询
@Test
public void testFindByCondition(){
User user = new User();
user.setUsername("老王");
user.setSex("男");
List<User> userByCondition = mapper.findUserByCondition(user);
for (User user1 : userByCondition) {
System.out.println(user1);
}
}
3. mybatis中的多表操作 (掌握使用)
一对多、一对一
多对一
多对多
一对一、一对多查询语句实例代码:
实体类:
public class Account implements Serializable {
private Integer id;
private Integer uid;
private Double money;
/**
* 从表实体应该包含一个主表实体的对象引用
* @return
*/
private User user;
}
映射配置文件:
注:<association property=“user” column=“uid” javaType=“user”>
<?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="com.itheima.dao.AccountDao">
<!--定义封装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">
<result property="id" column="id"></result>
<result property="username" column="username"></result>
<result property="address" column="address"></result>
<result property="sex" column="sex"></result>
<result property="birthday" column="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 a.uid=u.id;
</select>
<!--查询所有账户同时包含用户名和地址信息-->
<select id="findAllAccount" resultType="accountUser">
select a.*,u.username,u.address from account a,user u where a.uid=u.id;
</select>
</mapper>
测试类:
@Test
public void findAll(){
List<Account> accounts = accountDao.findAll();
for (Account account : accounts) {
System.out.println(account);
System.out.println(account.getUser());
}
}
多对多代码实现:
数据表:
实体类:
public class Role implements Serializable {
private Integer roleId;
private String roleName;
private String roleDesc;
//多对多的关系映射,一个角色可以赋予多个用户
private List<User> users;
}
public class User implements Serializable {
private Integer id;
private String username;
private Date birthday;
private String sex;
private String address;
}
dao层:
public interface RoleDao {
/**
* 查询所有角色
* @return
*/
List<Role> findAll();
}
多对多映射文件配置:
<?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="com.itheima.dao.RoleDao">
<resultMap id="roleMap" type="com.itheima.domain.Role">
<id property="roleId" column="id"></id>
<result property="roleName" column="role_name"></result>
<result property="roleDesc" column="role_desc"></result>
<collection property="users" ofType="user">
<id column="id" property="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>
</collection>
</resultMap>
<!--多对多-查询全部角色信息-->
<select id="findAll" resultMap="roleMap">
select u.*,r.id as rid ,r.role_name ,r.ROLE_DESC from role r
left outer join user_role ur on r.id=ur.RID
left outer join user u on u.id=ur.UID;
</select>
</mapper>
测试类:
@Test
public void findAll(){
List<Role> all = roleDao.findAll();
for (Role role : all) {
System.out.println(role);
System.out.println(role.getUsers());
}
}
八、Mybatis中的缓存
1. Mybatis中的延迟加载
问题:在一对多中,当我们有一个用户,它有一百个账户,在查询用户的时候,要不要把关联账户查出来,在查询账户的时候,要不要把关联的用户查出来。
查询用户时,用户下的账户信息是什么时候使用,什么时候查询的。
查询账户时,账户的所属用户信息应该是随着账户查询时一起查询的
什么是延迟加载?(也叫作懒加载、按需加载)
在真正使用数据时才发起查询,不用的时候不查询。
延迟加载的基本配置:配置在主配置文件中
<settings>
<!--开启mybatis全局延迟加载开关-->
<setting name="lazyLoadingEnabled" value="true"/>
<!--允许触发方法立即加载-->
<setting name="aggressiveLazyLoading" value="false"/>
</settings>
dao层映射文件也要改变:
<association property="user" column="uid" javaType="user" select="com.itheima.dao.UserDao.findById">
</association>
什么是立即加载?
不管用不用,只要一调用方法,马上发起查询
在对应的四种表关系中:一对多、多对一、一对一、多对多
一对多,多对多: 通常采用延迟加载。
一对一,多对一: 通常采取立即加载。
2. Mybatis中的缓存
什么是缓存?
存在于内存中的临时数据
为什么使用缓存
减少与数据库的交互次数,增加执行效率
什么样的数据能使用缓存,什么样的数据不能使用
经常查询并切不经常改变的,数据对结果影响不大的
mybatis中的一级缓存和二级缓存
一级缓存:
mybatis中sqlSession对象的缓存,执行查询后查询结果存入sqlSession中,该区域的结构是一个map。
一级缓存是sqlSession范围的缓存,当调用SqlSession缓存
的修改、删除、添加、close()、commit()等操作时,就会自
动清空一级缓存。
二级缓存:
mybatis中SqlSessionFactory对象的缓存,可以生产SqlSession
很多个
二级缓存中存放的是数据,不是对象