数据持久化
为什么需要持久化
Dao层,Service层,Controller层…
帮助程序猿将数据存入到数据库中
方柏霓
传统的JDBC代码太复杂了,简化,框架,自动化
不用Mybatis也可以,更容易上手,技术没有高低之分
有点
思路:搭建环境–>导入mybatis>编写代码–>测试
<configuration>
<environments default="development">
<environment id="development">
<transactionManager type="JDBC"/>
<dataSource type="POOLED">
<property name="driver" value="com.mysql.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost:3306/mybatis?useUnicode=true&characterEncoding=utf-8&serverTimezone=UTC"/>
<property name="username" value="root"/>
<property name="password" value="dql11111."/>
dataSource>
environment>
environments>
<mappers>
<mapper resource="host/qianlong/dao/UserMapper.xml"/>
mappers>
configuration>
package host.qianlong.utils;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import java.io.IOException;
import java.io.InputStream;
//sqlSessionFactory -->sqlSession
public class MybatisUtils {
private static SqlSessionFactory sqlSessionFactory;
static {
try {
//使用Mybatis获取sqlSessionFactory
String resource = "mybatis-config.xml";
InputStream inputStream = Resources.getResourceAsStream(resource);
sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
}catch (IOException e){
e.printStackTrace();
}
}
//既然有了sqlSessionFactory,顾名思义,我们就可以从中获得SqlSession的实例了
//SqlSession完全包含了面向数据库执行SQL命令所需的所有方法。
public static SqlSession getSqlSession(){
return sqlSessionFactory.openSession();
}
}
package host.qianlong.pojo;
//实体类
public class User {
private int id;
private String name ;
private String pwd ;
public User(){
}
public User(int id, String name, String pwd) {
this.id = id;
this.name = name;
this.pwd = pwd;
}
public void setId(int id) {
this.id = id;
}
public void setName(String name) {
this.name = name;
}
public void setPwd(String pwd) {
this.pwd = pwd;
}
public int getId() {
return id;
}
public String getName() {
return name;
}
public String getPwd() {
return pwd;
}
@Override
public String toString() {
return "User{" +
"id=" + id +
", name='" + name + '\'' +
", pwd='" + pwd + '\'' +
'}';
}
}
public interface UserDao {
List<User> getUserList();
}
<?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">
<!--namespace=绑定一个对应的Dao/mapper接口-->
<mapper namespace="host.qianlong.dao.UserDao">
<select id="getUserList" resultType="host.qianlong.pojo.User">
select * from mybatis.user
</select>
</mapper>
@Test
public void test(){
//1.获取SqlSession对象
SqlSession sqlSession = MybatisUtils.getSqlSession();
//方式一:getMapper
UserDao userDao = sqlSession.getMapper(UserDao.class);
List<User> userList = userDao.getUserList();
for (User user : userList){
System.out.println(user);
}
//关闭SqlSession
sqlSession.close();
}
namespace中的包名要和Dao/Mapper接口的报名一致
选则,查询语句
1.编写接口
User getUserById(int id);
2.编写对应的mapper中的sql语句
<select id="getUserById" resultType="host.qianlong.pojo.User" parameterType="int">
select * from mybatis.user where id = #{id}
select>
3.测试
@Test
//查询用户
public void getUserById(){
SqlSession sqlSession = MybatisUtils.getSqlSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
User user = mapper.getUserById(1);
System.out.println(user);
sqlSession.close();
}
//添加用户
@Test
public void addUser(){
SqlSession sqlSession = MybatisUtils.getSqlSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
int szy = mapper.addUser(new User(4, "szy", "123456"));
sqlSession.commit();
sqlSession.close();
}
@Test
public void updateUser(){
SqlSession sqlSession = MybatisUtils.getSqlSession();
UserMapper mapper = (UserMapper) sqlSession.getMapper(UserMapper.class);
int i = mapper.updateUser(new User( 1,"dql","123456"));
if (i>0){
System.out.println("修改成功");
}
sqlSession.commit();
sqlSession.close();
}
//删除用户
@Test
public void deleteUser(){
SqlSession sqlSession = MybatisUtils.getSqlSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
int i = mapper.deleteUser(4);
if (i>0){
System.out.println("删除成功");
}
sqlSession.commit();
sqlSession.close();
}
注意点:
假设,我们的实体类,或者数据库中的表,字段或者参数过多,我们应当考虑使用Map
Map传递参数,直接在sql中取出key即可。[parameterType=‘map’]
对象传递参数,再接再sql中取对象的属性即可。[parameterType=‘map’]
只有一个基本类型参数的情况下,可以直接在sql中渠道
多个参数用Mao,或者注解!
模糊查询怎么写?
1.java代码执行的时候,传递通配符%%
List<User> users = mapper.getLikeUserList("%d%");
2.在sql拼接中使用通配符
select * from mybatis.user where name like #{value}
configuration(配置)
properties(属性)
settings(设置)
typeAliases(类型别名)
typeHandlers(类型处理器)
objectFactory(对象工厂)
plugins(插件)
environments(环境配置)
environment(环境变量)
transactionManger(事务管理器)
dataSource(数据源)
databaseIdPeovider(数据库厂商标识)
mappers(映射器)
mybatis可以配置成适应多种环境
不过要记住:尽管可以配置多个环境,但每个sqlsessionFactory实例只能选择一种环境!
mybatis默认的事务管理就是jdbc 连接池:POOLED
我们可以通过peoperties属性来实现引用配置文件
这些属性都可外部配置且可动态替换的,既可以在典型的java属性文件中配置,亦可通过properties元素的子元素来传递。{db.properties}
1.db.properties
2.在核心配置中映入
<typeAliases>
<typeAlias type="host.qianlong.pojo.User" alias="user">typeAlias>
typeAliases>
也可以指定一个包名,Mybatis会在包名下面搜索需要的Java Bean,比如:扫描实体类的包,他的默认别名就为这个类的类名,首字母小写
<typeAliases>
<package name="host.qianlong.pojo"/>
typeAliases>
在实体类比较少的时候,使用第一种方式
如果实体类十分多,建议使用的耳中
第一种可以自定义别名,第二种则不行,如果非要改,需要在实力类上增加注解
@Alias("hello")
public class User{
}
STDOUT_LOGGING NO_LONGGING
MapperRegistrry:注册绑定我们的Mapper文件
方式一:【推荐使用】
<mapper resource="host/qianlong/dao/UserMapper.xml"/>
方式二:使用class文件进行绑定注册
注意点:
方式三:使用扫描包进行注入绑定
注意点:
声明周期和作用域是至关重要的,因为错误的使用会导致非常严重的并发问题
SqlSessionFactoryBuilder:
SqlSessionFactory:
SqlSession
这里的每一个mapper,就代表一个具体的业务
属性名和字段名不一致的会导致数据库的数据拿不到。
解决方法:
给字段起别名
<resultMap id="" type="hellp"></resultMap>
<select id="getUserId" resultMap="helloMap">
select id,name,pwd password from mybatis.user where id = #{
id}
</select>
结果集映射
id name pwd
id name password
<resultMap id="userMap" type="User">
<result column="id" property="id">result>
<result column="name" property="name">result>
<result column="pwd" property="password">result>
resultMap>
resultMap元素是MyBatis中最重要最强大的元素
ResulyMap的设计思想是,对于简单的语句根本不需要配置显示的结果映射,而对于复杂一点的语句只需要描述他们的关系就行了
ResultMap最优秀的地方在于,虽然你对他相当了解了,但是根本就不需要显示地用到他们
如果世界总是这么简单就好了
如果一个数据库操作,出现了异常,我们需要排错,日志就是我们最好的助手!
曾经:sout,debug
现在:日志工厂!
logImpl
在Mybatis中具体使用哪一个日志实现,在设置中设定
STDOUT_LOGGING标准日志输出
在mybatis核心配置文件中,配置我们的日志
<settings>
<setting name="logImpl" value="STDOUT_LOGGING"/>
settings>
什么是Log4j?
1.先导入Log4j包
<dependencies>
<dependency>
<groupId>log4jgroupId>
<artifactId>log4jartifactId>
<version>1.2.17version>
dependency>
2.log4j.properties
#将等级为DEBUG的日志信息输出到console和file这两个目的地,console和file的定义在下面的代码
log4j.rootLogger=DEBUG,console,file
#控制台输出的相关设置
log4j.appender.console = org.apache.log4j.ConsoleAppender
log4j.appender.console.Target = System.out
log4j.appender.console.Threshold=DEBUG
log4j.appender.console.layout = org.apache.log4j.PatternLayout
log4j.appender.console.layout.ConversionPattern=[%c]-%m%n
#文件输出的相关设置
log4j.appender.file = org.apache.log4j.RollingFileAppender
log4j.appender.file.File=./log/qianlong.log
log4j.appender.file.MaxFileSize=10mb
log4j.appender.file.Threshold=DEBUG
log4j.appender.file.layout=org.apache.log4j.PatternLayout
log4j.appender.file.layout.ConversionPattern=[%p][%d{yy-MM-dd}][%c]%m%n
#日志输出级别
log4j.logger.org.mybatis=DEBUG
log4j.logger.java.sql=DEBUG
log4j.logger.java.sql.Statement=DEBUG
log4j.logger.java.sql.ResultSet=DEBUG
log4j.logger.java.sql.PreparedStatement=DEBUG
3.配置log4j为日志实现
<settings>
<setting name="logImpl" value="STDOUT_LOGGING"/>
settings>
4.测试使用
简单使用
1.在要使用Log4j地类中,导入包import org.apache.log4j.Logger;
2.日志对象,参数为当前类的class
static Logger logger = Logger.getLogger(UserDaoTest.class)
3.日志级别
logger.info("info:进入了Log4jTest方法")
logger.debug("debuf:进入了Log4jTest方法")
logger.error("error:进入了Log4jTest方法")
思考:为什么要分页?
使用Limit分页
语法:SELECT * FROM USER LIMIT startIndex,pageSize;
SELECT * FROM USER LIMIT 3; #[0,n]
使用Mybatis实现分页
1.接口
List<User> getUserByLimit(Map<String,Integer> map);
2.xml配置
select>
<select id="getUserByLimit" parameterType="map" resultMap="userMap">
select * from mybatis.user limit #{startIndex},#{pageSize}
select>
3.测试
public void getUserByLimit(){
//分页
SqlSession sqlSession = MybatisUtils.getSqlSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
HashMap<String, Integer> map = new HashMap<String, Integer>();
map.put("startIndex",0);
map.put("pageSize",2);
List<User> userByLimit = mapper.getUserByLimit(map);
for (User user : userByLimit) {
System.out.println(user);
}
sqlSession.close();
}
根本原因:解耦。可拓展,提高复用,分层开发中,上层不用管具体的实现,大家都遵守共同的标准,使得开发变得容易,规范性更好
在一个面向对象的系统中,系统的各种功能是由许许多多的不同对象协作完成的,在这种情况下,各个对象内部是如何实现自己的,对系统设计人员来讲就不那么重要了;
而各个对象之间的协作关系则成为系统设计的关键,小到不同类之间的通信,大到各模块之间的交互,在系统设计之初都是要着重考虑的,这也是系统设计的主要工作内容。面向接口编程就是指按照这种思想来编程。
关于接口的理解
接口从更深层次的理解,应是定义(规范,约束)与实现(明实分离的原则)的分离。
接口的本身反映了系统设计人员对系统的抽象理解
接口应有两类:
一个体有可能有多个抽象面,抽象体与抽象面是有分别的
三个面向区别
1、注解在接口上实现
@Select("select * from user")
List<User> getUsers();
2、在核心配置文件上绑定接口
<mappers>
<mapper class="host.qianlong.dao.UserMapper">mapper>
mappers>
3、测试
@Test
public void getUser(){
SqlSession sqlSession = MybatisUtils.getSqlSession();
//底层主要应用反射
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
List<User> users = mapper.getUsers();
for (User user : users) {
System.out.println(user);
}
sqlSession.close();
}
本质:反射机制实现
底层:动态代理
关于@Parram()注解
按照查询嵌套处理
<mapper namespace="host.qianlong.dao.EmpMapper">
<select id="getEmployee" resultMap="EmpDept">
select * from emp;
select>
<resultMap id="EmpDept" type="Emp">
<result property="eid" column="eid">result>
<result property="name" column="name">result>
<result property="age" column="age">result>
<association property="dept" column="dept_id" javaType="Dept" select="getDept"/>
resultMap>
<select id="getDept" resultType="Dept" >
select * from dept where did = #{did};
select>
mapper>
按照结果嵌套查询处理
<select id="getEmployee2" resultMap="EmpDept2">
select * from emp,dept where emp.dept_id = dept.did;
select>
<resultMap id="EmpDept2" type="Emp">
<result property="eid" column="eid">result>
<result property="name" column="name">result>
<result property="age" column="age">result>
<association property="dept" javaType="Dept">
<result property="did" column="did">result>
<result property="name" column="name">result>
association>
resultMap>
//Dept
private int did;
private String name;
//一个部门拥有多个员工
private List<Emp> emp;
Emp
//Emp
public class Emp {
private int eid;
private String name;
private int age;
private int dept_id;
public interface DeptMapper {
// List getDept();
//获取部门对应的员工
Dept getDept(@Param("did")int did);
<select id="getDept2" resultMap="DeptEmp2">
select * from dept;
select>
<resultMap id="DeptEmp2" type="Dept">
<result property="did" column="did">result>
<result property="name" column="name">result>
<collection property="emp" javaType="ArrayList" ofType="Emp" select="getEmp" column="did">collection>
resultMap>
<select id="getEmp" resultType="Emp">
select * from emp where dept_id = #{did}
select>
按照结果嵌套处理
<select id="getDept" resultMap="DeptEmp">
select d.name dn,e.name en,e.age from emp e,dept d
where e.dept_id = d.did and d.did = #{did};
select>
<resultMap id="DeptEmp" type="Dept">
<result property="did" column="did">result>
<result property="name" column="dn">result>
<collection property="emp" ofType="Emp">
<result property="eid" column="eid">result>
<result property="name" column="en">result>
<result property="age" column="age">result>
<result property="dept_id" column="dept_id">result>
collection>
resultMap>
小结
关联-association【多对一】
集合-collection【一对多】
JavaType & ofType
注意点:
保证SQL的可读性,尽量保证通俗易懂
注意一对多和多对一中,属性名和字段的问题
如果问题不好排除可以使用日志
什么是动态SQL:动态SQL就是根据不同的条件生成不同的SQL语句
利用动态SQL这一特性可以彻底摆脱这种痛苦
动态SQL元素和JSTL或基于类型似XML的文本处理器相似。在Mybatis之前的版本中,有很多元素需要花时间了解,Mybatis3大大精简了元素种类,现在只需学习原来一半的元素便可,Mybatis采用功能强大的基于OGNL的表达式来淘汰其它大部分元素
if
choose(when,otherwise)
trim(where,set)
foreach
搭建环境
USE mybatis;
CREATE TABLE `blog`(
`id` VARCHAR(50) NOT NULL COMMENT '博客id',
`title` VARCHAR(100) NOT NULL COMMENT '博客标题',
`author` VARCHAR(30) NOT NULL COMMENT '博客作者',
`create_time` DATETIME NOT NULL COMMENT '创建时间',
`views` INT(30) NOT NULL COMMENT '浏览量'
)ENGINE=INNODB DEFAULT CHARSET=utf8
创建一个基础工程
1.导包
2.编写配置文件
3.编写实体类
4.编写实体类对应Mapper接口和Mapper.xml文件
<mapper namespace="host.qianlong.dao.BlogMapper">
<insert id="addBlog" parameterType="blog">
insert into blog(id,title,author,create_time,views) values(#{id},#{title},#{author},#{createtime},#{views});
insert>
<select id="queryBlogIF" parameterType="map" resultType="blog">
select * from blog where 1 =1
<if test="title != null">
and title = #{title}
if>
<if test="author != null">
and author = #{author}
if>
select>
mapper>
<select id="queryBlogChoose" parameterType="map" resultType="Blog">
select * from blog
<where>
<choose>
<when test="title!=null">
title = #{title}
when>
<when test="author!=null">
author = #{author}
when>
<otherwise>
views = #{views}
otherwise>
choose>
where>
select>
<select id="queryBlogIF" parameterType="map" resultType="blog">
select * from blog
<where>
<if test="title != null">
and title = #{title}
if>
<if test="author != null">
and author = #{author}
if>
where>
select>
所谓的动态SQL,本质还是SQL语句,只是我们可以在SQL层面去执行一个逻辑代码
有的时候,我们可能会将一些功能的部分抽取出来,方便复用
1、使用SQL标签抽取公共的部分
sql id="if-title-author">
<where>
<if test="title != null">
and title = #{title}
if>
<if test="author != null">
and author = #{author}
if>
where>
sql>
2、在需要使用的地方使用include标签引用即可
<select id="queryBlogIF" parameterType="map" resultType="blog">
select * from blog
<include refid="if-title-author">include>
select>
动态sql就是在拼接sql语句,我们只要保证sql的正确性,按照sql的格式,去排列组合就可以了
<select id="queryBlogForeach" parameterType="map" resultType="Blog">
select * from blog
<where>
<foreach collection="ids" item="id" open="and (" close=")" separator="or">
id = #{id}
foreach>
where>
select>
查询 : 连接数据库,耗资源!
一次查询的结果,给他暂存在一个直接取到的地方! -->内存 : 缓存
我们再次查询相同数据的时候,直接走缓存,就不用走数据库了
1.什么是缓存【Cache】?
2、为什么使用缓存?
3、什么样的数据库能使用缓存?
Mybatis包含一个非常强大的查询缓存特性,它可以非常方便的定制和配置缓存,存放可以极大的提升查询效率。
mybatis系统中默认定义了两级缓存:一级缓存和二级缓存
缓存失效的情况:
sqlSession.clearCache();
小结:一级缓存默认是开启的,只在一次sqlseesion中有效,也就是拿到连接到关闭这个区间段!
步骤:
1,开启全局缓存
<setting name="cacheEnabled" value="true"/>
2.在要使用二级缓存的mapper中开启
<cache eviction="FIFO"
flushInterval="60000"
size="512"
readOnly="true"
>cache>
3.测试
如果cache没有参数 实体类就要被序列化
小结: