Mybatis个人基础知识总结
Mybatis
1 配置环境
IDEA 2019.2.4
MySql 5.7
MAVEN 3.6.3
1.1 Mysql
数据库名:mybatis
表明:mybatis
字段:id(int) name(varhar) pwd(varhar)
1.2 MAVEN 依赖导入
<dependencies><dependency><groupId>mysql</groupId><artifactId>mysql-connector-java</artifactId><version>5.1.47</version></dependency><dependency><groupId>org.mybatis</groupId><artifactId>mybatis</artifactId><version>3.5.2</version></dependency><dependency><groupId>junit</groupId><artifactId>junit</artifactId><version>4.12</version></dependency>
</dependencies>
创建父模块,导入依赖成功后创建子模块
2 框架配置
1.1 编写mybatis配置文件
在resources目录下创建 mybatis-config.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><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?useSSL=false&useUnicode=true&characterEncoding=utf-8"/><property name="username" value="root"/><property name="password" value="123"/></dataSource></environment></environments><mappers>//每一个XML都要在这里进行映射<mapper resource="com/liang/dao/UserMapper.xml"/></mappers>
</configuration>
1.2 编写工具类
在com.liang.utils目录下创建 MybatisUtils
package com.liang.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;/*Mybatis工具类*/
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();}}public static SqlSession getSqlSession(){SqlSession sqlSession=sqlSessionFactory.openSession();return sqlSession;}
}
1.3 创建User实例类
在com.liang.pojo创建
package com.liang.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 int getId() {return id;}public void setId(int id) {this.id = id;}public String getName() {return name;}public void setName(String name) {this.name = name;}public String getPwd() {return pwd;}public void setPwd(String pwd) {this.pwd = pwd;}@Overridepublic String toString() {return "User{" +"id=" + id +", name='" + name + '\'' +", pwd='" + pwd + '\'' +'}';}
}
1.4 UserDao接口和UserMapper.xml
在dao目录下创建
package com.liang.dao;import com.liang.pojo.User;import java.util.List;public interface UserDao {List<User> getUserList();
}
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapperPUBLIC "-//mybatis.org//DTD Mapper 3.0//EN""http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.liang.dao.UserDao"><select id="getUserList" resultType="com.liang.pojo.User">select * from mybatis.mybatis</select>
</mapper>
1.5 测试类
在对应的目录创建相同的目录结构并且创建
package com.liang.dao;import com.liang.pojo.User;
import com.liang.utils.MybatisUtils;
import org.apache.ibatis.session.SqlSession;
import org.junit.Test;import java.util.List;public class UserDaoTest {@Testpublic void test(){SqlSession sqlSession =MybatisUtils.getSqlSession();UserDao userDao = sqlSession.getMapper(UserDao.class);List<User>userList = userDao.getUserList();for (User user:userList) {System.out.println(user);}sqlSession.close();}
}
1.6 资源导出
由于maven的约定大于配置,之后的配置文件可能无法被导出生效问题
<build><resources><resource><directory>src/main/resources</directory><includes><include>**/*.properties</include><include>**/*.xml</include></includes><filtering>false</filtering></resource><resource><directory>src/main/java</directory><includes><include>**/*.properties</include><include>**/*.xml</include></includes><filtering>false</filtering></resource></resources>
</build>
3 Mybatis实现增删改查
1.1 查
1.在接口中定义一个方法,参数值为int类型
User getUserById(int id);
注意:id为接口中起的方法名字,参数类型返回值类型略
<select id="getUserById" parameterType="int" resultType="com.liang.pojo.User">select * from mybatis.mybatis where id =#{id}
</select>
SqlSession sqlSession = MybatisUtils.getSqlSession();
UserDao userDao = sqlSession.getMapper(UserDao.class);
User user = userDao.getUserById(1);
System.out.println(user);
sqlSession.close();
1.2 增
1.
int addUser(User user);
2.
//注:标签中没有返回值, value中的参数可以直接写实体类中的变量名
<insert id="addUser" parameterType="com.liang.pojo.User">insert into mybatis.mybatis(id, name, pwd) value (#{id},#{name},#{pwd});
</insert>
3.
int result = userDao.addUser(new User(4,"张四","123"));
if (result>0){sqlSession.commit();//事务必须提交,否则无法插入成功
}
1.3 改
1.
int updateUser(User user);
2.
<update id="updateUser" parameterType="com.liang.pojo.User">update mybatis.mybatis set name = #{name},pwd=#{pwd} where id=#{id}
</update>
3.
int result = userDao.updateUser(new User(4\,"jacker","123"));
if (result >0) {sqlSession.commit();
}
1.4 删
1.
int deleteUser(int id);
2.
<delete id="deleteUser" parameterType="int">delete from mybatis.mybatis where id =#{id}
</delete>
3.
int result = userDao.deleteUser(5);
if (result >0) {sqlSession.commit();
}
4 万能MAP
1.1 增
int addUser2(Map<String,Object> map);
<insert id="addUser2" parameterType="map">insert into mybatis.mybatis(id, name, pwd) VALUE (#{userid},#{username},#{userpwd})
</insert>
Map<String,Object> map = new HashMap<String, Object>();
map.put("userid",5);
map.put("username","jack");
map.put("userpwd","123");
userDao.addUser2(map);
sqlSession.commit();
#{} 只不过让里面的值转换成为 ? ,用来防止SQL注入
使用MAP传递参数时:
名字可以随便取无须与实体类中的名字相同,需注意的是xml中的名字要与MAP.put()key值的名字相同
1.2 更新
int updateUser2(Map<String,Object> map);
<update id="updateUser2" parameterType="map">update mybatis.mybatis set name =#{username} where id=#{userid}
</update>
Map<String,Object> map = new HashMap<String,Object>();
map.put("userid",4);
map.put("username","tom");
userMapper.updateUser2(map);
sqlSession.commit();
从此例可知,使用Map集合不用写出对象中的所有属性从而简化操作
模糊查询:传递通配符 %value%
5 配置解析
1.1 核心配置文件
mybatis-config.xml
mybatis的配置文件包含了会影响Mybatis行为的设置和属性信息
1.2 环境配置(environments)
mybatis可以配置多个环境
尽管可以多个环境,但是每个SqlSessionFactory实例只能选择一种环境
mybatis默认的事务管理器就是JDBC
连接池:POOLED (池的概念就是可以回收,不会被销毁)
transactionManager 、 dataSource类型不止一种
1.3 属性(properties)
我们可以通过属性来实现引用配置文件
这些属性都是可外部配置且动态替换,可以在典型的java属性文件中配置,也可以通过properties元素的子元素来传递
1.3.1 编写一个配置文件
db.properties
driver=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/mybatis?useSSL=false&useUnicode=true&characterEncoding=utf-8
username=root
password=123
1.3.2 配置文件
<property name="driver" value="${driver}"/>
<property name="url" value="${url}"/>
<property name="username" value="${username}"/>
<property name="password" value="${password}"/>
属性名必须与配置文件中的属性名称相同
多个属性可以删除掉,只不过需要在标签中添加属性标签
eg:
<properties resource="db.properties"><property name="username" value="${username}"/>
</properties>
当外部文件中的属性值与xml中的属性值冲突时,外部文件的优先级较高
注意:
可以直接引入外部文件
可以再其中中添加属性配置
如果两个文件有同一个字段,优先使用外部配置文件
>>
引入外部文件 添加的新属性
1.4 类型别名(typeAliases)
类型别名是为java类型设置一个短的名字,意义仅在于减少类完全限定的冗余、
此标签位置处于第三位,位于properties、setting之后
类取完别名后,任意地方都可以使用
1.4.1 第一种方法
<typeAliases><typeAlias type="com.liang.pojo.User" alias="User"/>
</typeAliases>
1.4.2 第二种方法
直接扫描包,扫描实体类的包,它的默认别名为这个类的类名,首字母小写
<package name="com.liang.pojo"/>
在实体类比较少的时候,使用第一种方式
若实体类较多,建议第二种;使用扫描的方式还可以使用注解,注解的名为类的别名(实体类上增加注解)
注:使用注解,则扫描包<package name=>语句必须存在
1.5 设置 settings
这是Mybatis中极为重要的调整设置,它们会改变Mybatis的运行行为
1.6 其他设置
typeHandlers
objectFactory
plugins:
mybatis-gererator-core
mybatis-plus
通用mapper
1.7 映射器(mappers)
MapperRegistry:注册绑定我们的Mapper.xml文件
1.7.1 第一种方法
resource注册xml文件
<mappers><mapper resource="com/liang/dao/UserMapper.xml"/>
</mappers>
1.7.2 第二种方法
使用class文件绑定注册
<mapper class="com.liang.dao.UserMapper"/>
注意点:(Mapper.xml和Mapper接口)
接口和它的Mapper配置文件必须同名
接口和它的Mapper配置文件必须在同一个包下
1.7.3 第三种方式
使用包扫描 package
<package name="com.liang.dao"/>
注意点:与方法二注意点相同
6 生命周期与作用域
生命周期和作用域是至关重要的,因为错误的使用会导致非常严重的并发问题
SqlSessionFactoryBuilder:
一旦创建SqlSessionFactory,就不再需要它
局部变量
SqlSessionFactory:
即可想象为:数据库连接池
一旦被创建就应该在应用运行期间一直存在,没有任何理由丢弃它或重新创建另一个实例
最佳作用域为应用作用域
最简单的就是使用单例模式或者静态单例模式
SqlSession
连接到连接池的一个请求
SqlSession实例不是线程安全,因此不能被共享
最佳作用域为请求或方法作用域
用完之后即关闭,否则资源被占用
7 属性名与字段名不一致
查询语句执行成功,但是名字不同的属性值为空
解决方法:
1.1 as 修改字段别名
sql语句使用as 为字段取别名
select id, name, pwd as userpwd from mybatis.mybatis where id =#{id}
1.2 resultMap 结果集映射
<!-- 结果集映射 表中的字段映射一个属性 --><resultMap id="UserMapper" type="User"><id column="id" property="id"/><id column="name" property="name"/><id column="pwd" property="userpwd"/></resultMap><!-- 根据用户ID查询用户信息 --><select id="getUserById" resultMap="UserMapper">select * from mybatis.mybatis where id =#{id}</select>
- resultMap元素是Mybatis中最强大的元素
- ResultMap设计思想为,对于简单的语句不需要配置显示的结果映射,复杂一点的语句只需要描述它们的关系
- ResultMap最优秀的地方在于,虽然你对它相当了解但是根本就不需要显式地用到它们
8 日志
1.1 日志工厂
如果一个数据库操作失误,出现异常需要排错,日志就是最好的帮手
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-2sPdXCMo-1602250356772)(img\logImpl.PNG)]
- SLF4J |
- LOG4J (掌握)
- LOG4J2
- JDK_LOGGING
- COMMONS_LOGGING
- STDOUT_LOGGING (掌握)
- NO_LOGGING
在Mybatis中具体使用哪个日志实现,可以再设置中设定
STDOUT_LOGGING 标准日志输出
在Mybatis的核心配置文件中设定日志文件
<settings><setting name="logImpl" value="STDOUT_LOGGING"/>
</settings>
注意:属性名严格按照官方文档
属性值不能有前后空格,不可写错
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-uQRhGTDz-1602250356777)(img\STDOUT_LOGGING.PNG)]
1.2 Log4j
介绍:
- Log4j是Apache的一个开源项目,通过使用Log4j,我们可以控制日志信息输送的目的地是控制台、文件、GUI组件
- 我们也可以控制每一条日志的输出格式
- 通过定义每一条日志信息的级别,我们能够更加细致地控制日志的生成过程
- 可以通过一个配置文件来灵活地进行配置,而不需要修改应用的代码
1.2.1 先导入log4j包
<dependency><groupId>log4j</groupId><artifactId>log4j</artifactId><version>1.2.17</version>
</dependency>
1.2.2 log4j配置文件
#将等级为DEBUG的日志信息输出到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/kuang.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
1.2.3 配置log4j为日志实现
<settings><setting name="logImpl" value="LOG4J"/>
</settings>
1.2.4 运行同一个程序
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-iKjQRpr5-1602250356780)(img\LOG4J.PNG)]
1.2.5 简单使用
1.在要使用log4j的类中,导入包import org.apache.log4j.Logger;
2.日志对象,参数为当前类的class
static Logger logger = Logger.getLogger(UserDaoTest.class);
3.日志级别
public void testLog4j(){logger.info("info:进入testLog4j类中");logger.debug("debug:进入testLog4j类中");logger.error("error:进入testLog4j类中");}
7 分页
分页语句:
select * from table_name limit startIndex,pageSize
使用Mybatis实现分页
1.接口中写方法
List<User> getUserListByLimit(Map<String,Object> map);
2.添加SQL语句
<select id="getUserListByLimit" parameterType="map" resultMap="UserMapper">select * from mybatis.mybatis limit #{startIndex},#{pageSize}</select>
3.测试
Map<String,Object> map =new HashMap<String, Object>();//分页参数value值应该是数字,填入字符串会报错map.put("startIndex",0);map.put("pageSize",2);List<User> userList =userMapper.getUserListByLimit(map);for (User user:userList){System.out.println(user);}
8 注解开发
注解开发,不再需要UserMapper.xml文件
1.获取所有用户
1.1 在接口方法上方添加注解
@Select("select * from mybatis")List<User> getUserList();
1.2 核心配置文件绑定接口
<mappers><mapper class="com.liang.dao.UserMapper"/>
</mappers>
1.3 测试类
List<User> userList = userMapper.getUserList();for (User user:userList) {System.out.println(user);}
2.注解开发实现CRUD
1.1 ID查询用户
@Select("select * from mybatis where id = #{id}")User getUserById(@Param("id")int id);
@Param(“id”)中的属性名必须与SQL语句中#{id}名字相同,与java语句中的参数可以不相同
方法存在基本数据类参数,需要在参数前加上@Param注解,引用数据类型则不需要
测试类
UserMapper userMapper = sqlSession.getMapper(UserMapper.class);User user =userMapper.getUserById(1);System.out.println(user);
SqlSession sqlSession=sqlSessionFactory.openSession(true);
//参数为true,自动提交事务无序手动提交
1.2 添加用户
@Insert("insert into mybatis(id,name,pwd) value(#{id},#{name},#{pwd})")int addUser(User user);
userMapper.addUser(new User(5,"黎明","123"));
1.3 删除用户
@Delete("delete from mybatis where id =#{id}")
int deleteUser(@Param("id") int id);
userMapper.deleteUser(5);
1.4 更新信息
@Update("update mybatis set name=#{name},pwd=#{pwd} where id =#{id}")
int updateUser(User user);
userMapper.updateUser(new User(4,"黎明","123"));
3.个人总结与分析
@Insert("insert into mybatis(id,name,pwd) value(#{id},#{name},#{pwd})")
int addUser(User user);userMapper.addUser(new User(5,"黎明","123"));
以上语句中 #{id},#{name},#{pwd}是从实体类中取值,实体类中的值已经由创建对象时赋予值
@Delete("delete from mybatis where id =#{uid}")
int deleteUser(@Param("uid") int id);userMapper.deleteUser(5);
以上语句中#{id}取的值应该是参数 int id 中的值,所以int id参数的注解明必须与#{id}中的名字相同才能取到
更新语句中id为条件,set后面跟上ID会报错(ID为主键,不可重复不可为空)
9 Lombok
1.安装插件
2.导入包
<!-- https://mvnrepository.com/artifact/org.projectlombok/lombok -->
<dependency><groupId>org.projectlombok</groupId><artifactId>lombok</artifactId><version>1.18.12</version><scope>provided</scope>
</dependency>
3.添加注解
@Data
@AllArgsConstructor
@NoArgsConstructor
自己用用开心就好,不建议怎么用但是很方便
10 多对一
关联:多个学生对应一个老师
创建两张表,学生表与教师表
CREATE TABLE `teacher` (`id` INT(10) NOT NULL,`name` VARCHAR(30) DEFAULT NULL,PRIMARY KEY (`id`)
) ENGINE=INNODB DEFAULT CHARSET=utf8INSERT INTO teacher(`id`, `name`) VALUES (1, '秦老师'); CREATE TABLE `student` (`id` INT(10) NOT NULL,`name` VARCHAR(30) DEFAULT NULL,`tid` INT(10) DEFAULT NULL,PRIMARY KEY (`id`),KEY `fktid` (`tid`),CONSTRAINT `fktid` FOREIGN KEY (`tid`) REFERENCES `teacher` (`id`)
) ENGINE=INNODB DEFAULT CHARSET=utf8
INSERT INTO `student` (`id`, `name`, `tid`) VALUES ('1', '小明', '1');
INSERT INTO `student` (`id`, `name`, `tid`) VALUES ('2', '小红', '1');
INSERT INTO `student` (`id`, `name`, `tid`) VALUES ('3', '小张', '1');
INSERT INTO `student` (`id`, `name`, `tid`) VALUES ('4', '小李', '1');
INSERT INTO `student` (`id`, `name`, `tid`) VALUES ('5', '小王', '1');
搭配实验环境:
- 创建实体类
- 创建实体类的Mapper接口和Mapper.xml文件
- Mybatis核心配置文件中绑定Mapper接口(也可说是绑定 .xml文件)
- 编写Mapper.xml文件
- 创建实体类进行测试
1.按照查询嵌套查询处理
创建Studen实体类
@Data
public class Student {private int id;private String name;private Teacher teacher;
}
在StudentMapper 添加方法
List<Student> getStudentList();
添加查询语句标签StudentMapper.xml
<select id="getStudentList" resultMap="StudentList">select * from mybatis.student</select><resultMap id="StudentList" type="Student"><!-- 因为teacher为引用数据类型所以标签使用 association --><association property="teacher" column="tid" javaType="Teacher" select="getTeacher"></association></resultMap><select id="getTeacher" resultType="Teacher">select * from mybatis.teacher where id=#{tid}</select>
测试
List<Student> studentList = studentMapper.getStudentList();for (Student ss:studentList) {System.out.println(ss);}
结果
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-yvWpIlrQ-1602250356784)(img/202009232121.png)]
个人理解:
- 查询方式为联合查询与子查询结合
- Student表中的字段为id,name,tid,实体类中的属性为id,name,teacher
- 学生表与老师表依靠tid外键连接
- 查询方式为结果集映射可以理解为
- 查询语句中的字段名为Teacher,而学生实体类中属性名为tid
- 查询结果需要让tid显示为Teacher信息,这样看来就是字段名与属性名不同的结果集映射查询方式
注意重点:
<association property="teacher" column="tid" javaType="Teacher" select="getTeacher"></association>
javaType为属性teacher的类型,select为查询老师表的标签对名称
2.按照结果嵌套查询处理
在StudentMapper 添加方法
List<Student> getStudentList2();
添加查询语句标签StudentMapper.xml
<select id="getStudentList2" resultMap="getStudentList2">select s.id sid,s.name sname,t.name tnamefrom student s ,teacher twhere s.tid = t.id
</select>
<resultMap id="getStudentList2" type="Student"><result property="id" column="sid"/><result property="name" column="sname"/><association property="teacher" javaType="Teacher"><association property="name" column="tname"></association></association>
</resultMap>
测试同上
个人总结:
- 嵌套查询不用子查询,方便简单许多
- 结果集映射每个都映射,引用数据类型使用association且不用写上column,直接跟上javaType
- 在association标签对中嵌套association
- 字段名誉属性名不同,让实体类老师中的name属性与要查询的表的字段名匹配
总结:
1.子查询方式(理解有些许难度似乎理解似乎不理解)
大致意思:
select id,name,tid from student where tid =(select id,name from teacher where id );
2.联合查询
11 一对多
集合:一个老师对应多个学生
学生类
@Data
public class Student {private int id;private String name;private int tid;
}
老师类
@Data
public class Teacher {private int id;private String name;private List<Student> students;
}
1.按照结果嵌套查询处理
查询特定老师的所有学生
TeacherMapper.配置
Teacher getTeacher(@Param("sid") int id);
TeacherMapper.xml配置
<select id="getTeacher" resultMap="Teacher">select s.id sid,s.name sname,s.tid stid,t.id tid,t.name tnamefrom student s,teacher twhere s.tid = t.id and t.id =#{sid}</select><resultMap id="Teacher" type="Teacher"><result property="id" column="tid"/><result property="name" column="tname"/><collection property="students" ofType="Student"><result property="id" column="sid"/><result property="name" column="sname"/><result property="tid" column="stid"/></collection></resultMap>
注:因为students属性为List集合泛型为Student,而要获得泛型的数据类型需要 ofType
测试
TeacherMapper teacherMapper = sqlSession.getMapper(TeacherMapper.class);
Teacher teacher = teacherMapper.getTeacher(1);
System.out.println(teacher);
2.按照查询嵌套查询处理
Teacher getTeacher2(@Param("sid") int id);
<select id="getTeacher2" resultMap="teacher">select * from student where id=#{sid}</select><resultMap id="teacher" type="Teacher"><collection property="students" column="id" javaType="ArrayList" ofType="Student" select="getStudent"/></resultMap><select id="getStudent" resultType="Student">select * from student where tid = #{sid}</select>
注:
- 因为使用子查询嵌套,所以 List集合类型、泛型类型都必须加上
- List集合映射的字段colunm为特定老师的id,因为子查询需要查询学生的特定的老师需要老师的id
3.两种查询处理区别
按照结果嵌套:
字段挨着映射,最后特殊地方不需要column字段直接跟上类型集合javaType/ofType
按照查询嵌套:
字段挨着映射,最后特殊地方需要property、column、javaType、(ofType)、select子查询语句
association:没什么特别的
collection:oftype
12 动态SQL
动态SQL即根据不同的条件生成不同的SQL语句
1.搭配环境
创建表
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
创建getId工具类
public class IDutils {public static String getId(){return UUID.randomUUID().toString().replaceAll("-","");}
}
创建实体类(类中属性为createTime,数据库中的表明为creat_time,这是需要在核心配置文件中添加配置)
public class blog {private String id;private String title;private String author;private Date createTime;private int views;
}
<setting name="mapUnderscoreToCamelCase" value="true"/>
//自动按照驼峰式命名
创建Mapper接口
public interface blogMapper {int addBlog(blog Blog);
}
创建Mapper.xml
<insert id="addBlog" parameterType="blog">insert into mybatis.blog(id, title, author, create_time, views)VALUE (#{id},#{title},#{author},#{createTime},#{views})</insert>
表中添加数据(使用框架的insert方式添加数据)
public void addBlogTest() {SqlSession sqlSession = MybatisUtils.getSqlSession();blogMapper mapper = sqlSession.getMapper(blogMapper.class);blog blog = new blog();blog.setId(IDutils.getId());blog.setTitle("Mybatis");blog.setAuthor("狂神说");blog.setCreateTime(new Date());blog.setViews(9999);mapper.addBlog(blog);blog.setId(IDutils.getId());blog.setTitle("Java");mapper.addBlog(blog);blog.setId(IDutils.getId());blog.setTitle("Spring");mapper.addBlog(blog);blog.setId(IDutils.getId());blog.setTitle("微服务");mapper.addBlog(blog);sqlSession.close();}
2.if/Where
if标签比较简单,其中条件不可以 #{},否则查询为空
<select id="getBlogIF" parameterType="map" resultType="blog">select *from mybatis.blog where 1=1<if test="title!=null">and title=#{title}</if><if test="author!=null">and author=#{author}</if></select>
where语句后方不可能添加 1=1 这样的语句,但是不写上sql语句又会报错,所以Mybatis有解决方案
使用Where标签,所有的判断语句放在Where标签对中即可
Where标签会智能的对SQL语句进行改编并保证使用Where条件语句时SQL语句的正常语序
例如1.where后面什么也没有传入则自动删除where判断
2.where后第一条语句不存在直接判断第二个条件 and… 则自动删除and关键字保证sql语句正确
3.choose(when,otherwise)
相当于java语句中的 switch…case判断
<select id="getBlogChoose" parameterType="map" resultType="blog">select *from mybatis.blog<where><choose><when test="title!=null">title=#{title}</when><when test="author!=null">and author=#{author}</when><otherwise>and views=#{views}</otherwise></choose></where></select>
List<blog> getBlogChoose(Map map);
Map map = new HashMap();//map.put("title","Java");map.put("views","1000");List<blog> list = mapper.getBlogChoose(map);for (blog blog1:list) {System.out.println(blog1);}
注:使用此动态SQL,必须为otherwise这个最后条件设置为成立,否则查询结果为空
第二个when条件需要加上 and关键字,最后一个默认条件也需加上 and关键字
Map map = new HashMap();map.put("title","Java");map.put("views","1000");//这个条件必须给定,否则查询结果皆为空List<blog> list = mapper.getBlogChoose(map);for (blog blog1:list) {System.out.println(blog1);}
4.trim(Where,Set)
set作用与where一样,智能添加关键字且删除不必要的逗号等其他保证SQL语句的正确
int upDateBlogSet(Map map);
Map map = new HashMap();map.put("title", "Java02");map.put("id", "94d0bf59572440adb0a187f61a743cdb");mapper.upDateBlogSet(map);
<update id="upDateBlogSet" parameterType="int">Update mybatis.blog<set><if test="title!=null">title=#{title},</if><if test="author!=null">and author=#{author},</if></set>where id = #{id}</update>
5.SQL片段
本质为实现代码复用,对于重复使用的SQL片段抽取出来,需要的时候引入
<!-- SQL代码片段抽取 -->
<sql id="getIF"><if test="title!=null">and title=#{title}</if><if test="author!=null">and author=#{author}</if></sql>
<select id="getBlogIF" parameterType="map" resultType="blog">select *from mybatis.blog <where><!-- 依照ID引入SQL代码片段 --><include refid="getIF"></include></where></select>
注意事项:
- 最好基于单表来定义SQL片段
- 不要存在Where标签
6.Foreach
List<blog> getBlogForeach(Map map);
<select id="getBlogForeach" parameterType="map" resultType="blog">select * from mybatis.blog<where><foreach collection="ids" item="tid" open="(" separator="or" close=")">id=#{tid}</foreach></where></select>
Map map = new HashMap();ArrayList<Integer>ids = new ArrayList<Integer>();ids.add(1);map.put("ids",ids);List<blog> blogForeach = mapper.getBlogForeach(map);for (blog bb:blogForeach) {System.out.println(bb);}
/*Foreach对集合进行遍历,集合名字为ids,测试类创建一个名叫ids的单链表ArrayList并向其中放入数字1Foreach取出单链表中的数字1,则where后面的判断语句即为 id=1
*/
注:
- foreach中collection为要遍历的集合名字
- item为集合中的每个具体元素
- id=#{id}
- = 左边为拼接SQL语句,必须为id因为字段名
- = 右边中取得值应该与item中的名字相同且可与=左边名字不同
总结:动态SQL就是在拼接SQL语句,我们只需要保证SQL正确性,按照SQL的格式去排列组合即可
13 缓存(了解)
1.简介
1.1 什么是缓存?
- 存在内存中的数据
- 将用户经常查询的数据放在缓存中(内存)中,用户查询数据就无需从磁盘上(关系型数据库文件)查询,从缓存中查询,从而提高查询效率,解决了高并发系统的性能问题
1.2 为什么使用缓存?
减少和数据库的交互次数,减少系统开销,提高系统效率
1.3 什么样的数据能使用缓存
经查查询并且不经常改变的数据
2.Mybatis缓存
- MyBatis 内置了一个强大的事务性查询缓存机制,它可以非常方便地配置和定制,它可以极大提升 查询效率
- Mybatis中默认定义了两级缓存:一级缓存和二级缓存
- 默认情况下,只有一级缓存(SqlSession级别的缓存,也成为本地缓存)
- 二级缓存需要手动开启与配置,它是基于namespace级别的缓存
- 为提高扩展性,Mybatis自定义了缓存接口Cache,我们可以通过实现接口自定义二级缓存
3.一级缓存
一级缓存也称为本地缓存:
- 与数据库同一次会话期间查询到的数据会放在本地缓存中
- 以后如果需要相同的数据,直接从缓存中取,无需再去查询数据库
配置环境:1.打印日志文件
2.查询同一个用户
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-PkFN5ki8-1602250356792)(img/202009261546.PNG)]
缓存失效的原因:
- 查询不同的用户缓存会刷新
- 增删改可能会改变原来的数据,所以缓存会刷新
- 查询不同的Mapper.xml
- 手动清理缓存:sqlsession.cleanCache()
小结:一级缓存默认开启,在sqlsession.close之前都有作用,只有一次sqlsession有效
一级缓存相当于map
4.二级缓存
- 二级缓存也称为全局缓存,一级缓存作用域太低所以诞生了二级缓存
- 基于namespace级别的缓存,一个名称空间,对应一个二级缓存
- 工作机制
- 一个会话查询一条数据,这个数据就会被放在当前会话的一次缓存中
- 如果当前会话关闭,这个会话对应的一级缓存就没了;但我们需要会话关闭一个缓存中的数据会被保存在二级缓存中
- 新的会话查询信息,就可以从二级缓存中获取内容
- 不同的mapper查出的数据会放在自己的对应缓存(mapp)中
步骤:
1.开启全局缓存(默认开启,为了代码的可读性)
<setting name="cacheEnabled" value="true"/>
2.在要使用二级缓存的Mapper中开启
<cache/>
也可以自定义参数
<cacheeviction="FIFO"flushInterval="60000"size="512"readOnly="true"/>
一级缓存被干掉后二级缓存会启用并保存一级缓存的数据
5.缓存原理
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-QTIAs6pF-1602250356794)(img/缓存原理.png)]
缓存也可以在标签中进行优化:
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-pRteci7g-1602250356796)(img/202009261632.png)]
不知道的话空格一下会有提示
6.自定义缓存-ehcache
Ehcache是一种广泛使用的开源Java分布式缓存,主要面向通用缓存
导包
<!-- https://mvnrepository.com/artifact/org.mybatis.caches/mybatis-ehcache -->
<dependency><groupId>org.mybatis.caches</groupId><artifactId>mybatis-ehcache</artifactId><version>1.1.0</version>
</dependency>
<!--在当前Mapper.xml中使用二级缓存-->
<cache type="org.mybatis.caches.ehcache.EhcacheCache"/>
<?xml version="1.0" encoding="UTF-8"?>
<ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:noNamespaceSchemaLocation="http://ehcache.org/ehcache.xsd"updateCheck="false"><!--diskStore:为缓存路径,ehcache分为内存和磁盘两级,此属性定义磁盘的缓存位置。参数解释如下:user.home – 用户主目录user.dir – 用户当前工作目录java.io.tmpdir – 默认临时文件路径--><diskStore path="./tmpdir/Tmp_EhCache"/><defaultCacheeternal="false"maxElementsInMemory="10000"overflowToDisk="false"diskPersistent="false"timeToIdleSeconds="1800"timeToLiveSeconds="259200"memoryStoreEvictionPolicy="LRU"/><cachename="cloud_user"eternal="false"maxElementsInMemory="5000"overflowToDisk="false"diskPersistent="false"timeToIdleSeconds="1800"timeToLiveSeconds="1800"memoryStoreEvictionPolicy="LRU"/><!--defaultCache:默认缓存策略,当ehcache找不到定义的缓存时,则使用这个缓存策略。只能定义一个。--><!--name:缓存名称。maxElementsInMemory:缓存最大数目maxElementsOnDisk:硬盘最大缓存个数。eternal:对象是否永久有效,一但设置了,timeout将不起作用。overflowToDisk:是否保存到磁盘,当系统当机时timeToIdleSeconds:设置对象在失效前的允许闲置时间(单位:秒)。仅当eternal=false对象不是永久有效时使用,可选属性,默认值是0,也就是可闲置时间无穷大。timeToLiveSeconds:设置对象在失效前允许存活时间(单位:秒)。最大时间介于创建时间和失效时间之间。仅当eternal=false对象不是永久有效时使用,默认是0.,也就是对象存活时间无穷大。diskPersistent:是否缓存虚拟机重启期数据 Whether the disk store persists between restarts of the Virtual Machine. The default value is false.diskSpoolBufferSizeMB:这个参数设置DiskStore(磁盘缓存)的缓存区大小。默认是30MB。每个Cache都应该有自己的一个缓冲区。diskExpiryThreadIntervalSeconds:磁盘失效线程运行时间间隔,默认是120秒。memoryStoreEvictionPolicy:当达到maxElementsInMemory限制时,Ehcache将会根据指定的策略去清理内存。默认策略是LRU(最近最少使用)。你可以设置为FIFO(先进先出)或是LFU(较少使用)。clearOnFlush:内存数量最大时是否清除。memoryStoreEvictionPolicy:可选策略有:LRU(最近最少使用,默认策略)、FIFO(先进先出)、LFU(最少访问次数)。FIFO,first in first out,这个是大家最熟的,先进先出。LFU, Less Frequently Used,就是上面例子中使用的策略,直白一点就是讲一直以来最少被使用的。如上面所讲,缓存的元素有一个hit属性,hit值最小的将会被清出缓存。LRU,Least Recently Used,最近最少使用的,缓存的元素有一个时间戳,当缓存容量满了,而又需要腾出地方来缓存新的元素的时候,那么现有缓存元素中时间戳离当前时间最远的元素将被清出缓存。--></ehcache>
Mybatis个人基础知识总结相关推荐
- Spring+SpringMVC+MyBatis深入学习及搭建(一)——MyBatis的基础知识
转载请注明出处:http://www.cnblogs.com/Joanna-Yan/p/6812311.html 1.对原生态jdbc程序中问题总结 1.1 jdbc程序 需求:使用jdbc查询mys ...
- java培训基础知识都学哪些
很多人都开始学习java技术,觉得java语言在未来的发展前景空间非常大,事实却是如此,那么针对于零基础的同学, 学习java技术需要学哪些呢?下面我们就来看看java培训基础知识都学哪些? java ...
- TCP/IP 基础知识总结
点击上方蓝色"方志朋",选择"设为星标" 回复"666"获取独家整理的学习资料! 要说我们接触计算机网络最多的协议,那势必离不开 TCP/I ...
- 2021 版 Spring Boot 基础知识复习手册(2w字,建议收藏)
点击上方 好好学java ,选择 星标 公众号重磅资讯,干货,第一时间送达 今日推荐:分享一套基于SpringBoot和Vue的企业级中后台开源项目,这个项目有点哇塞!个人原创100W +访问量博客: ...
- ❤️六W字《计算机基础知识》(二)(建议收藏)❤️
上一篇: ❤️六W字<计算机基础知识>(一)❤️ 51. Access是一种____数据库管理系统. A.发散型 B.集中型 C.关系型 D.逻辑型 52. 用高级程序设计语言编写的 ...
- ❤️六W字《计算机基础知识》(一)(建议收藏)❤️
计算机简介: 计算机(computer)俗称电脑,是现代一种用于高速计算的电子计算机器,可以进行数值计算,又可以进行逻辑计算,还具有存储记忆功能.是能够按照程序运行,自动.高速处理海量 ...
- mvc试图 下拉框不重复_面试前不巩固一下基础知识、刷刷题吗?
其实面试就像一场相亲,在你心动人的面前,肯定要展示自己最好的一面,无论是穿着还是言行举止.作为一个软件开发工程师,看过很多公司的面试题,也参与过很多公司的面试,也给不少人新人面过时不试,虽说我现在并没 ...
- java不死神兔总数_Java基础知识强化之IO流笔记13:递归之不死神兔问题(斐波那契数列)...
1.这个问题是如下的: 有一对兔子,从出生后第3个月起,每个月都生一对兔子,小兔子长到第3个月又生一对兔子,加入兔子都不死,问第20个月兔子的对数? 分析:我们找规律 兔子对数 第1个月: 1 第 ...
- JAVA基础知识学习全覆盖
文章目录 一.JAVA基础知识 1.一些基本概念 1.Stringbuffer 2.局部变量成员变量 3.反射机制 4.protect 5.pow(x,y) 6.final ,finally,fina ...
最新文章
- C# ObservableCollection和List的区别
- 各层作用_OSI模型中各层在通信中的作用
- 好玩的问答,看看你的年龄阶段哦
- 中国团队屠榜:COCOMapillary挑战赛包揽全部冠军
- Maven进行Mahout编程,使其兼容Hadoop2.2.0环境运行 (转)
- 互不侵犯king (状压dp)
- Oracle 临时表
- java编程马拉松比赛_腾讯编程马拉松
- Linux系统之audit
- clover懒人_懒人气球驱动的互联网毕竟可能不是一个愚蠢的想法
- js怎么实现hmacsha256_各种语言HMAC SHA256实现
- vue下载压缩包 , 提示文件损坏
- 提醒电脑族:眼睛酸涩会致病
- Matlab算法之优化计算1
- 平面设计与UI设计有什么不同之处
- 在windows上搭建DZ(Discuz)论坛-部署完成
- ibm服务器芯片架构,IBM服务器X架构技术综述(图)
- python读取文件夹下txt文件,并转化成excel
- 微信小程序中相机api_微信小程序API 相机·CameraContext实例
- 推断统计--假设检验