一个网站需要什么,做视频的软件模板下载网站有哪些内容,wordpress博客实现ajax,wordpress可以制作什么网站吗mybatis简介#xff1a; MyBatis 是一款优秀的持久层框架#xff0c;它支持自定义 SQL、存储过程以及高级映射。MyBatis 免除了几乎所有的 JDBC 代码以及设置参数和获取结果集的工作。MyBatis 可以通过简单的 XML 或注解来配置和映射原始类型、接口和 Java POJO#xff08;P…mybatis简介 MyBatis 是一款优秀的持久层框架它支持自定义 SQL、存储过程以及高级映射。MyBatis 免除了几乎所有的 JDBC 代码以及设置参数和获取结果集的工作。MyBatis 可以通过简单的 XML 或注解来配置和映射原始类型、接口和 Java POJOPlain Old Java Objects普通老式 Java 对象为数据库中的记录。 mybatis的优点 mybatis框架内可以简化数据据编程。mybatis底层封装的是jdbc使用起来大大简化了jdbc。sql与java编码分开功能边界清晰。 mybatis环境搭建
开发环境 maven mysql8 创建maven项目在pom.xml 中导入坐标依赖
!-- junit单元测试 --
dependency
groupIdjunit/groupId
artifactIdjunit/artifactId
version4.11/version
scopetest/scope
/dependency
!-- mysql驱动 --
dependency
groupIdmysql/groupId
artifactIdmysql-connector-java/artifactId
version8.0.31/version
/dependency
!-- MyBatis --
dependency
groupIdorg.mybatis/groupId
artifactIdmybatis/artifactId
version3.5.11/version
/dependency jar包的下载方式
如果不使用maven可以从官网上面下载相应的jar包导入进行使用 https://github.com/mybatis/mybatis-3/releasesmybatis中文文档 https://mybatis.net.cn/index.htmlmybatis核心原理
什么叫ORM ORM是Object Relational Mapping 对象关系映射。把数据库表和实体类以及实体类的属性对应起来让开发者操作实体类就实现操作数据表 ORM也叫对象关系映射是一种程序设计思想。简单来说就是将数据库中查询出的数据映射到对应的实体中。 程序分层 控制层controller/servlet
业务逻辑层service
持久层数据库访问层dao/mapper mybatis操作数据库的步骤 ①读取mybatis的配置文件mybatis-cinfig.xml 是mybatis的全局配置文件主要作用是获取数据库连接
②加载映射mapper.xml 该文件配置了操作数据库的sql语句需要在mybatis-config.xml 中加载才行。mybatis-cinfig.xml 可以加载多个配置文件每个配置文件对应数据库中的一张表
③构建会话工厂SqlSessionFactory
④创建SqlSession对象。会话工厂创建SqlSession对象该对象中包含执行sql所有方法。 mybatis-config.xml核心配置文件 每个mybatis应用都是以一个 SqlSessionFactory 的实例为核心的。SqlSessionFactory的实例通过SqlSessionBuilder获得。 在maven中配置mybatis-config.xml
?xml version1.0 encodingUTF-8 ?
!DOCTYPE configuration
PUBLIC -//mybatis.org//DTD Config 3.0//EN
http://mybatis.org/dtd/mybatis-3-config.dtd
configuration
environments defaultdevelopment
environment iddevelopment
transactionManager typeJDBC/
dataSource typePOOLED
property namedriver valuecom.mysql.cj.jdbc.Driver/
property nameurl
valuejdbc:mysql://localhost:3306/db_mybatis?serverTimezoneGMT%2B8/
property nameusername valueroot/
property namepassword valueroot/
/dataSource
/environment
/environments
!-- 引入映射文件 --
mappers
mapper resourceorg/mybatis/example/BlogMapper.xml/
/mappers
/configuration 创建db.properties properties该标签可以引入外部配置的属性也可以自己配置。该配置标签所在的同一个配置文件中的其他配置均可引用此配置中的属性。 我们的配置文件中数据库连接相关参数其实是写死的但是我们清楚一般情况下这种参数的配置我们不会写死而是通过properties这种配置文件进行读取。
db.drivercom.mysql.cj.jdbc.Driver
db.urljdbc:mysql://localhost:3306/db_mybatis?serverTimezoneGMT%2B8
db.usernameroot
db.passwordroot 在mybatis-config配置文件中通过properties标签引入以上配置:
?xml version1.0 encodingUTF-8 ?
!DOCTYPE configuration
PUBLIC -//mybatis.org//DTD Config 3.0//EN
http://mybatis.org/dtd/mybatis-3-config.dtd
configuration
!-- properties标签使用resource属性引入db.properties配置文件 --
properties resourcedb.properties/properties
environments defaultdevelopment
environment iddevelopment
transactionManager typeJDBC/
dataSource typePOOLED
!-- 通过${属性名}获取具体属性 --
property namedriver value${db.driver}/
property nameurl value${db.url}/
property nameusername value${db.username}/
property namepassword value${db.password}/
/dataSource
/environment
/environments
!-- 引入映射文件 --
mappers
mapper resourcemapper/UserMapper.xml/
/mappers
/configuration 创建mybatis的mapper映射
数据库的准备
tb_user的脚本文件
create database db_mybatis character set utf8;use db_mybatis;create table tb_user(
id int primary key auto_increment,
username varchar(20),
password varchar(20)
);insert into tb_user(username,password) values(tom,123),(jerry,456); 创建实体类
public class User {Integer id;String username;String password;public User() {}public User(Integer id, String username, String password) {this.id id;this.username username;this.password password;}public Integer getId() {return id;}public void setId(Integer id) {this.id id;}public String getUsername() {return username;}public void setUsername(String username) {this.username username;}public String getPassword() {return password;}public void setPassword(String password) {this.password password;}Overridepublic String toString() {return User{ id id , username username \ , password password \ };}
} 创建mapper接口 mapper接口命名方式为相关类的实体类User --- UserMapper
Mapper.xml文件命名方式与对应的Mapper接口保持一致UserMapper -- UserMapper.xml位置一般在resource目录下创建mapper目录把所有的mapper.xml保存到这里。 创建mapper接口
public interface UserMapper {
/**
* 新增用户数据方法
* return 新增结果
*/
Integer addUser();
} 创建UserMapper.xml namespace属性此属性的作用就是绑定当前映射xml文件与对应接口的关系。需要把UserMapper的全限定名填入到namespace属性中简历接口与xml文件的关系 crud标签selectupdateinsertdelete标签中的id对应的就是mapper接口中要执行的方法。 ?xml version1.0 encodingUTF-8 ?
!DOCTYPE mapper
PUBLIC -//mybatis.org//DTD Mapper 3.0//EN
http://mybatis.org/dtd/mybatis-3-mapper.dtd
mapper namespacecom.java.mapper.UserMapper!-- addUser() --insert idaddUserinsert into tb_user(username,password) values(小明,123)/insert
/mapper 在mybatis-config.xml文件里面引入映射文件的位置
mappers
mapper resourcemapper/UserMapper.xml/
/mappers 构建会话工厂 配置好mybatis-config.xmlmapper接口mapper.xml映射文件之后现在要通过mybatis提供的API来执行具体的sql语句。 junit单元测试 Junit是Java语言的单元测试框架。
Junit 测试也是程序员测试即所谓的白盒测。 一般在项目的 testjava 目录中编写测试类型通过test注解来声明测试方法 mybatisAPI的调用 SqlSessionFactory:生产SqlSession的工厂 工厂SqlSession通过SqlSessionFactory生产而来代表Java程序和数据库之间的会话通过此对象来完成SQL语句的执行和获取结果等操作。 Testpublic void test(){try {//读取mybatis-config.xml核心配置文件InputStream is Resources.getResourceAsStream(mybatis-config.xml);//创建SqlSessionFactory对象SqlSessionFactory sqlSessionFactory new SqlSessionFactoryBuilder().build(is);//openSession方法默认是不会进行自动事务提交的所以我们如果想做
DML操作并且自动提交事务需要加上true参数默认为falseSqlSession sqlSession sqlSessionFactory.openSession(true);UserMapper mapper sqlSession.getMapper(UserMapper.class);//测试添加的结果int num mapper.addUser();System.out.println(num);sqlSession.close();} catch (IOException e) {e.printStackTrace();}} mybatis-config配置文件的其他配置
MyBatis 最核心的全局配置文件是 mybatis-config.xml 文件其中包含了
数据库的连接配置信息、Mapper 映射文件的加载路径、全局参数、类型别名等
配置项配置项的解析。。。。configuration包裹所有配置标签是整个配置文件的顶级标签。properties该标签可以引入外部配置的属性也可以自己配置setting全局配置参数用来配置一些改变运行时行为的信息例如是否使用缓存机制是否使用延迟加载是否使用错误处理机制等。typeAliases类型别名用来设置一些别名来代替 Java 的长类型声明environments设置多个连接数据库的环境environment设置具体的连接数据库的环境信息transactionManager事务管理指定 MyBatis 的事务管理器dataSource数据源使其中的 type 指定数据源的连接类型在标签对中可以使用 property 属性指定数据库连接池的其他信息mappers映射器配置 sql 映射文件的位置告知 MyBatis 去哪里加载 sql映射配置 案例演示 ?xml version1.0 encodingUTF-8 ?
!DOCTYPE configuration
PUBLIC -//MyBatis.org//DTD Config 3.0//EN
http://MyBatis.org/dtd/MyBatis-3-config.dtd
configuration
!-- properties标签使用resource属性引入db.properties配置文件 --
properties resourcedb.properties/properties
!--
environments设置多个连接数据库的环境
属性
default设置默认使用的环境的id
--
settings
setting namemapUnderscoreToCamelCase valuetrue/
/settings
environments defaultdevelopment
!--
environment设置具体的连接数据库的环境信息
属性
id设置环境的唯一标识可通过environments标签中的default设置某一
个环境的id表示默认使用的环境
--
environment iddevelopment
!--
transactionManager设置事务管理方式
属性
type设置事务管理方式typeJDBC|MANAGED
typeJDBC设置当前环境的事务管理都必须手动处理
typeMANAGED设置事务被管理例如spring中的AOP
--
transactionManager typeJDBC/
dataSource typePOOLED
!--设置驱动类的全类名--
property namedriver value${db.driver}/
!--设置连接数据库的连接地址--
property nameurl value${db.url}/
!--设置连接数据库的用户名--
property nameusername value${db.username}/
!--设置连接数据库的密码--
property namepassword value${db.password}/
/dataSource
/environment
/environments
!--引入映射文件--
mappers
!-- mapper resourceUserMapper.xml/ --
!--
以包为单位将包下所有的映射文件引入核心配置文件
注意
1. 此方式必须保证mapper接口和mapper映射文件必须在相同的包下
2. mapper接口要和mapper映射文件的名字一致
--
package namecom.java.mapper/
/mappers
/configuration mybatis完成增删改查 添加功能
mapper层接口编写public interface UserMapper {//添加userint addUser(User user);
} mapper.xml文件 insert idaddUserinsert into tb_user(username,password) values(#{username},#{password})
/insert test进行测试 public SqlSession getSqlSession(){InputStream is null;try {is Resources.getResourceAsStream(mybatis-config.xml);} catch (IOException e) {e.printStackTrace();}SqlSessionFactory sqlSessionFactory new SqlSessionFactoryBuilder().build(is);SqlSession sqlSession sqlSessionFactory.openSession();return sqlSession;}Testpublic void testAdd(){User user new User(都是, 121);SqlSession sqlSession getSqlSession();UserMapper mapper sqlSession.getMapper(UserMapper.class);int num mapper.addUser(user);sqlSession.commit();System.out.println(num);} 删除功能
mapper层编写
public interface UserMapper {delete iddelUserByIddelete from tb_user where id #{id}/delete
} mapper.xml文件 delete iddelUserByIddelete from tb_user where id #{id}/delete
test进行测试
Testpublic void testDel() throws IOException {InputStream is Resources.getResourceAsStream(mybatis-config.xml);SqlSessionFactory sqlSessionFactory new SqlSessionFactoryBuilder().build(is);SqlSession sqlSession sqlSessionFactory.openSession();UserMapper mapper sqlSession.getMapper(UserMapper.class);int num mapper.delUserById(1);System.out.println(num);} 修改功能
mapper接口
public interface UserMapper {//修改int updateUser(User user);
}
mapper.xml文件 update idupdateUserupdate tb_user set username #{username},password #{password}where id #{id}/update
test测试
Testpublic void testUpdate() throws IOException {InputStream is Resources.getResourceAsStream(mybatis-config.xml);SqlSessionFactory sqlSessionFactory new SqlSessionFactoryBuilder().build(is);SqlSession sqlSession sqlSessionFactory.openSession();UserMapper mapper sqlSession.getMapper(UserMapper.class);User user new User(1,孙道嗯,123456);int num mapper.updateUser(user);sqlSession.commit();System.out.println(num);} 查询功能
xml写法
注意 如果利用xml写法进行查询就必须确定以下映射关系才能使用 resultType设置默认映射关系 resultMap设置自定义映射关系多用于复杂查询-多表查询 无参数查询查询全部
mapper接口
//查询全部ListUser getUserList();
mapper.xml文件 select idgetUserList resultTypeorg.example.entity.Userselect * from tb_user/select
test测试
Testpublic void test(){try {InputStream is Resources.getResourceAsStream(mybatis-config.xml);SqlSessionFactory sqlSessionFactory new SqlSessionFactoryBuilder().build(is);SqlSession sqlSession sqlSessionFactory.openSession();UserMapper mapper sqlSession.getMapper(UserMapper.class);ListUser userList mapper.getUserList();for (User u:userList) {System.out.println(u);}sqlSession.close();} catch (IOException e) {e.printStackTrace();}}//User{id1, username孙道嗯, password123456}
User{id2, usernamejerry, password456}
User{id4, username都是, password121}
User{id7, username得到, password111}
User{id8, username是分公司, password5555}
User{id9, username反打, password1231}
User{id10, username的发挥, password131}
User{id11, username发达·, password5453}
User{id12, username光辐射大概, password423} 单个参数查询
mapper接口 //单个查询User getUserById(Integer id);
mapper.xml文件 select idgetUserById resultTypeorg.example.entity.Userselect * from tb_user where id #{id}/select
test测试 Testpublic void testGetUserById(){SqlSession sqlSession getSqlSession();UserMapper mapper sqlSession.getMapper(UserMapper.class);int user mapper.delUserById(1);System.out.println(user);} 多个参数查询
mapper接口
//根据username和pwd查询User getUserByNameAndPwd(Param(name) String name,Param(pwd) String pwd);
mapper.xml文件 select idgetUserByNameAndPwd resultTypeorg.example.entity.Userselect * from tb_user whereusername #{name}and password #{pwd}/select
test测试 Testpublic void testGetByNameAndPwd(){SqlSession sqlSession getSqlSession();UserMapper mapper sqlSession.getMapper(UserMapper.class);User user mapper.getUserByNameAndPwd(孙道嗯, 123456);System.out.println(user);} map参数查询
mapper接口 //传递map类型的参数User getUserByMap(MapString,Object map);
mapper.xml文件 select idgetUserByMap resultTypeorg.example.entity.Userselect * from tb_user whereusername #{username}and password #{password}/select
test测试 Testpublic void testMap(){SqlSession sqlSession getSqlSession();UserMapper mapper sqlSession.getMapper(UserMapper.class);MapString,Object map new HashMap();map.put(username,孙道嗯);map.put(password,123456);User userByMap mapper.getUserByMap(map);System.out.println(userByMap);}
//User{id1, username孙道嗯, password123456} 查询单个数据返回数据为map
mapper接口 一条数据对应一个Map将多个Map放入到一个Map集合中但是要配合 注解设置Map集 合的键MapKey注解会把对应查询出的数据中的某一个字段作为建所以必须要保证此字段不能重复所以一般为id。 //查询单个数据返回数据为mapMapKey(id)MapString,Object getUserMapByname(String name);
mapper.xml文件 select idgetUserMapByname resultTypejava.util.Mapselect * from tb_user where username #{name}/select
test测试 Testpublic void testMapByName(){SqlSession sqlSession getSqlSession();UserMapper mapper sqlSession.getMapper(UserMapper.class);MapString, Object map mapper.getUserMapByname(孙道嗯);System.out.println(map);}
//{1{password123456, id1, dept_id2, username孙道嗯}} 查询list的map集合数据
mapper接口
//查询List的map集合MapKey(id)ListMapString,User mapList();
mapper.xml文件 select idmapList resultTypeorg.example.entity.Userselect * from tb_user/select
test测试 Testpublic void testMapList(){SqlSession sqlSession getSqlSession();UserMapper mapper sqlSession.getMapper(UserMapper.class);ListMapString, User maps mapper.mapList();IteratorMapString, User it maps.iterator();while (it.hasNext()){System.out.println(it.next());}}
//User{id1, username孙道嗯, password123456}
User{id2, usernamejerry, password456}
User{id4, username都是, password121}
User{id7, username得到, password111}
User{id8, username是分公司, password5555}
User{id9, username反打, password1231} 查询返回map集合的数据
mapper接口
//查询map集合数据MapKey(id)MapString,User maps();
mapper.xml文件 select idmaps resultTypejava.util.Mapselect * from tb_user/select
test测试 Testpublic void testMaps(){SqlSession sqlSession getSqlSession();UserMapper mapper sqlSession.getMapper(UserMapper.class);MapObject, User maps mapper.maps();System.out.println(maps);}
//{1{password123456, id1, dept_id2, username孙道嗯}, 2{password456, id2, dept_id2, usernamejerry}, 4{password121, id4, dept_id2, username都是}, 7{password111, id7, dept_id1, username得到}, 8{password5555, id8, dept_id1, username是分公司}, 9{password1231, id9, dept_id3, username反打}, 10{password131, id10, dept_id3, username的发挥}, 11{password5453, id11, dept_id2, username发达·}, 12{password423, id12, dept_id2, username光辐射大概}} 添加时获取自增主键
mapper接口
//获取自增主键int getAddUserId(User user);
mapper.xml文件 insert idgetAddUserId useGeneratedKeystrue keyPropertyid insert into tb_user(username,password) values(#{username},#{password})/insert
test测试 Testpublic void testAddUserGetId(){SqlSession sqlSession getSqlSession();UserMapper mapper sqlSession.getMapper(UserMapper.class);User user new User(订单但, 111);int num mapper.getAddUserId(user);System.out.println(num);System.out.println(user);}
//1
User{id13, username订单但, password111} 模糊查询
mapper接口
//模糊查询ListUser getUserByLike(Param(username) String username,Param(password) String password);
mapper.xml文件 sql iduserSqlid,username,password/sqlselect idgetUserByLike resultTypeorg.example.entity.Userselectinclude refiduserSql/includefrom tb_userwhereif testusername ! null and username ! and username like concat(%,#{username},%)/ifif testpassword ! null and password ! and password like concat(%,#{password},%)/if/where/select
test测试 Testpublic void getUserByLike(){SqlSession sqlSession getSqlSession();UserMapper mapper sqlSession.getMapper(UserMapper.class);ListUser user mapper.getUserByLike(道, 111);System.out.println(user);} 分页查询
mapper接口
//分页查询ListUser selectUserByLimit(MapString,Integer map);
mapper.xml文件 select idselectUserByLimit resultTypeorg.example.entity.Userselect * from tb_userlimit #{start},#{pageSize}/select
test测试 Testpublic void testLimit(){SqlSession sqlSession getSqlSession();UserMapper mapper sqlSession.getMapper(UserMapper.class);MapString,Integer map new HashMap();map.put(start,0);map.put(pageSize,2);ListUser users mapper.selectUserByLimit(map);for (User u:users) {System.out.println(u);}}
//User{id1, username孙道嗯, password123456}
User{id2, usernamejerry, password456} mybatis中传递参数
两种常见的方式 ${} 此种方式本质为字符串拼接
#{} 此种方式为占位字符串 select * from ${tableName} where username #{username}
获取单个参数
mapper接口
select(select * from tb_user where id #{id})
User getUserById(Integer id);
test测试 Testpublic void testAddUserGetId(){SqlSession sqlSession getSqlSession();UserMapper mapper sqlSession.getMapper(UserMapper.class);User user mapper.getUserById(1);System.out.println(user);} 获取多个参数
需求查询tb_user表中id为1的数据。此时需要把id和表明都作为参数 注意表名不能使用#{}因为表名位置需要进行字符串拼接#{}占位符会出现语法问题。 示例 select * from ? where id ? mapper接口
Select(select * from ${table} where id #{id})
User selectByIdAndTable(String table,Integer id);
test测试 Testpublic void testAddUserGetId(){SqlSession sqlSession getSqlSession();UserMapper mapper sqlSession.getMapper(UserMapper.class);User user mapper.selectByIdAndTable(tb_user,1);System.out.println(user);}
//此时会报错的找不到参数
方法中给出了两个参数在mybatis处理时参数名称分别是arg0arg1.或者使用param1和param2访问这两个参数。
mapper接口
Select(select * from ${arg0} where id #{arg1})
User selectByIdAndTable(String table,Integer id);
或者
Select(select * from ${param1} where id #{param2})
User selectByIdAndTable(String table,Integer id); 最常用的写法
Select(select * from ${table} where id #{id})User selectByIdAndTable(Param(table) String table,Param(id) Integer id
); Map参数类型
mapper接口
Select(select * from tb_user where username #{username} and password #{password})
User selectByUsernameAndPassword(MapString,Object map);
test测试 Testpublic void testAddUserGetId(){SqlSession sqlSession getSqlSession();UserMapper mapper sqlSession.getMapper(UserMapper.class);//手动将输入放入都Map中MapString,Object map new HashMap();map.put(username,jerry);map.put(password,456);User user userMapper.selectByUsernameAndPassword(map);} 实体参数类型
mapper接口
Insert(insert into tb_user(username,password) values(#{username},#
{password}))
Integer addUser(User user);
test测试 Testpublic void testAddUserGetId(){SqlSession sqlSession getSqlSession();UserMapper mapper sqlSession.getMapper(UserMapper.class);User user new User(河南,111);int num mapper.addUser(user);}//1 总结mybatis执行的时候会自动读取参数user的属性填充到对应的占位符号#{}例如读取到User中的usernaem属性填充到#{username}。 mybatis获取参数方式详解
使用${}格式的占位符时可以表示SQL语句中的任何部分可以是某个值也可以是SQL语句中的某个片段使用这种占位符时MyBatis在处理过程中是先将占位符对应的值拼接到SQL语句中然后将整个SQL语句交给数据进行词法分析、语义分析、编译如果无误就可以直接执行SQL语句如果出现语法错误就会导致程序运行过程中出现异常 使用#{}格式的占位符时由于使用了预编译的做法所以这种处理方式是安全的而${}占位符是先拼接SQL语句再执行的过程并没有预编译的处理所以存在SQL注入的风险的 mybatis关联查询
数据准备
CREATE TABLE tb_dept (
id INT(11) AUTO_INCREMENT COMMENT 部门ID,
name VARCHAR(20) NOT NULL COMMENT 部门名,
PRIMARY KEY (id)
);
-- 在tb_dept表中插入数据
INSERT INTO tb_dept (name) VALUES (Java), (C), (Linux);
-- tb_user 表中增加外键列dept_id
ALTER TABLE tb_user ADD COLUMN dept_id INT;
-- 根据 tb_dept 中id更新tb_user表中dept_id列的值供测试使用
UPDATE tb_user u SET dept_id (SELECT d.id FROM tb_dept d WHERE
nameJava) WHERE u.id 5;
UPDATE tb_user u SET dept_id (SELECT d.id FROM tb_dept d WHERE
nameC) WHERE u.id 5; 创建vo类型
entitty.UserVo
public class UserVO {Integer id;
String username;
String name;
}
mapper接口
Select(select u.id,u.username,d.name from tb_user u left join tb_dept d \n
on u.dept_idd.id;)
ListUserVO findUserDept();
mapper.xml文件
!-- ListUserVO findUserDept(); --
select idfindUserDept resultTypevo.UserVO
select u.id,u.username,d.name
from tb_user u
left join tb_dept d
on u.dept_idd.id;
/select
test测试
Test
public void findUserDeptTest(){try {SqlSession sqlSession getSqlSession();UserMapper userMapper sqlSession.getMapper(UserMapper.class);ListUserVO list userMapper.findUserDept();list.forEach(user - System.out.println(user));} catch (IOException e) {e.printStackTrace();}
} resultMap的应用
需要执行的sql
select d.*,u.id,u.username from tb_dept d
left join tb_user u on d.id u.dept_id
where d.id1;
DeptVo
public class DeptVo {Integer id;
String name;
ListUser users;
}
mapper接口
/**
* 查询当前部门信息包括此部门对应的用户信息
* param id 部门编号
* return 部门信息部门员工信息
*/
DeptVo findDept(Integer id); resultMap属性设置自定义映射id名称 resultMap标签 id 表示自定义映射的唯一标识不能重复
type 查询的数据要映射的实体类的类型id标签设置主键字段映射result标签 设置普通字段映射column 映射具体列数据库中的字段property 具体映射属性实体类中的属性collectionproperty 具体映射的属性oftype 映射类型 mapper.xml文件
?xml version1.0 encodingUTF-8 ?
!DOCTYPE mapper
PUBLIC -//mybatis.org//DTD Mapper 3.0//EN
http://mybatis.org/dtd/mybatis-3-mapper.dtd
!-- namespace最主要的作用就是绑定mapper.xml与对应那个Mapper接口的关系要求
接口名称为全限定名 --
mapper namespacemapper.DeptMapper
resultMap iddeptMap typevo.DeptVoid columnid propertyid/idresult columnname propertyname/resultcollection propertyusers ofTypeentity.Userresult columnid propertyid/idresult columnusername propertyusername/resultresult columnpassword propertypassword/result/collection
/resultMap
!-- DeptVo findDept(Integer id) --select idfindDept resultMapdeptMapselect d.id,name,u.id,username,password fromtb_dept dleft join tb_user u ond.id u.dept_id where d.id#{id};/select
/mapper
test测试
Test
public void findDeptTest(){try {SqlSession sqlSession MyBatisDemo.getSqlSession();DeptMapper deptMapper sqlSession.getMapper(DeptMapper.class);DeptVo vo deptMapper.findVoById(1);System.out.println(vo);} catch (IOException e) {e.printStackTrace();}
} 说明字段名和实体类中的属性名不一致但是字段名符合数据库的规则使用了_实体类中的属性名符合java规则使用了驼峰命名法。可以通过三种方式处理字段名和实体类中的属性映射关系。
起别名
select * from d_name dName from dept
Results注解
//column 数据库的字段property 实体类的属性Results({Result(column create_time,property createTime), Result(column update_time,property updateTime)})Select(select id,name,create_time createTime,update_time updateTime from dept)public ListDept selectAll();
开启字段名转换为驼峰
settings
setting namemapUnderscoreToCamelCase valuetrue/
/settings mybatis中加入log4j查看日志
添加依赖
!-- log4j日志 --
dependency
groupIdlog4j/groupId
artifactIdlog4j/artifactId
version1.2.17/version
/dependency 添加配置
在resource目录中添加即可
log4j.xml
?xml version1.0 encodingUTF-8 ?
!DOCTYPE log4j:configuration SYSTEM log4j.dtd
log4j:configuration xmlns:log4jhttp://jakarta.apache.org/log4j/
appender nameSTDOUT classorg.apache.log4j.ConsoleAppender
param nameEncoding valueUTF-8 /
layout classorg.apache.log4j.PatternLayout
param nameConversionPattern value%-5p %d{MM-dd
HH:mm:ss,SSS} %m (%F:%L) \n /
/layout
/appender
logger namejava.sql
level valuedebug /
/logger
logger nameorg.apache.ibatis
level valueinfo /
/logger
root
level valuedebug /
appender-ref refSTDOUT /
/root
/log4j:configuration
日志的级别FATAL(致命)ERROR(错误)WARN(警告)INFO(信息)DEBUG(调试) 定义SQL片段
简介 mybatis的sql 标签一般是用来封装sql语句、或者复用语句的然后用include标签来调用 创建sql片段示例
sql idselectSqlselect * from tb_user
/sql
调用sql片段
select idgetUserList resultTypeUserinclude refidselectSql/include
/selectsql idif_sqlif testid ! null and id ! and id #{id}/ifif testusername ! null and username ! and username #{username}/if
/sql
调用 select idselectByWhere resultTypeorg.example.entity.Userselect * from tb_userwhereinclude refidif_sql/include/where/select mybatis的动态SQL 动态SQL技术是一种根据特定条件动态拼装SQL语句的功能它存在的意义是为了 解决拼接SQL语句字符串时的问题 简单理解 根据调用方法时给出的参数不同最终生成的SQL语句会不同 动态SQL-if if 一般实现的效果就是根据不同的参数查询出不同的结果。 if test /if 当test条件表达式里面的值为true时才会拼接执行 mapper接口
ListUser getUserByIf(Map map);
mapper.xml文件
!-- selectDynamicIf --
select idgetUserByIf resultTypeentity.User
!-- 11保证语句在没有条件时不会多出where子句报错where 11保证语句的
正确性 --
select * from tb_user where 11if testid ! null and id ! and id#{id}/ifif testusername ! null and username ! and username #{username}/if
/select
test测试
Test
public void findUserDeptTest(){try {SqlSession sqlSession getSqlSession();UserMapper userMapper sqlSession.getMapper(UserMapper.class);Map map new hashMap();map.put(username,孙道嗯);mpa.put(password,111);} catch (IOException e) {e.printStackTrace();}
} 动态sql-where 上面执行的sql语句中 where11有点多余。where可不可以变成动态的 加入where标签即可 mapper.xml文件
mapper namespacemapper.DynamicMapper!-- getuserByWhere --select idgetuserByWhere resultTypeentity.Userselect * from tb_userwhereif testid ! null and id ! and id#{id}/ifif testusername ! null and username ! and username #{username}/if/where/select
/mapper 但是我们修改sql语句为and或者or放在后面程序就会报错。
mapper namespacemapper.DynamicMapper!-- getUserByWhere --select idgetUserByWhere resultTypeentity.Userselect * from tb_userwhereif testid ! null and id ! id#{id} and/ifif testusername ! null and username ! username #{username}/if/where/select
/mapper
当只有第一条数据时就会报错因为后面多了一个and关键字。
select * from tb_suer where id ? and 动态SQL-trim trim用于去掉标签或添加标签内容 常用属性 prefix:在trim标签中的内容的前面添加耨写内容suffix在trim标签中的内容的后面添加某些内容prefixOverrides在trim标签中的内容的前面去掉某些内容suffixOverrides在trim标签中的内容的后面去掉某些内容 mapper.xml文件
select idgetUsrByTrim resultTypeentity.User
select * from tb_user
!-- prefix在执行判断前添加where suffixOverrides判断后去掉and如果还
有or可以通过 and|or的方式来表示多个关键字 --trim prefixwhere suffixOverridesandif testid ! null and id ! id#{id} and/ifif testusername ! null and username ! username #{username}/if/trim
/select 动态SQL-choosewhenotnerwise choose表示此套标签的最外层 类似于 switch when表示判断各种条件类似于case otherwise所有条件都不符合时走这里 类似于default mapper.xml文件
select idgetUserByChoose resultTypeentity.Userselect * from tb_userwherechoosewhen testid ! null and id ! id#{id}/whenwhen testusername ! null and username ! username #{username}/whenotherwisepassword 123/otherwise/choose/where
/select
test测试
Test
public void findUserDeptTest(){try {SqlSession sqlSession getSqlSession();UserMapper userMapper sqlSession.getMapper(UserMapper.class);Map map new HashMap();map.put(id,1);map.put(username,孙道嗯);ListUser userList userMapper.getUserByChoose(map);system.out.println(userList);} catch (IOException e) {e.printStackTrace();}
} 动态SQL-set set 动态的在SQL语句中插入set关键字并会删掉额外的逗号。用于update语句中 mapper接口 //修改用户信息Integer updateUserBySet(User user);
mapper.xml文件 update idupdateUserBySetupdate tb_usersetif testusername ! null and username ! username #{username},/ifif testpassword ! null and password ! password #{password}/if/setwhere id #{id}/update
test测试 Testpublic void updateUserBySet(){SqlSession sqlSession getSqlSession();UserMapper mapper sqlSession.getMapper(UserMapper.class);User user new User(1,但是,3333);Integer num mapper.updateUserBySet(user);System.out.println(num);} 动态SQL-foreach 动态SQL一个常见使用场景是对集合遍历。 mapper接口
Integer delUserByIds(Param(ids)Integer[] ids); 不加当前传递的是数字格式就需要在collection属性上添加 array 如果是List集合 就需要添加 list 属性值 属性解释 collection表示被遍历的对象。如果没有添加Param注解时参数的类型时list集合类型则取值为list。如果参数类型为数组则取值为array否则取值就是Param注解中配置的名称。 item将根据这个属性配置的值来使用数据 separator分隔符用于分隔遍历时生成的多个占位符 oppen和close遍历生成的SQL语句片段的起始字符串和结束字符串。比如open( close) 动态删除案例
mapper.xml文件
!-- Integer delUserByIds(Integer[] ids); --
delete iddelUserByIdsDELETE FROM tb_user WHERE id INforeach collectionids itemid separator, open( close)#{id}/foreach
/delete
test测试
Test
public void findUserDeptTest(){try {SqlSession sqlSession getSqlSession();UserMapper userMapper sqlSession.getMapper(UserMapper.class);Integer num userMapper.delUserByIds(new Integer[]{1,2,3});system.out.println(num);} catch (IOException e) {e.printStackTrace();}
} mybatis的缓存
什么是缓存 存在内存中的临时数据
将用户经常查询的数据放入缓存内存中用户去查询数据就不需要每次都从磁盘上查
询从缓存内存中查询从而提高查询效率解决了高并发系统的性能问题 为什么使用缓存 减少和数据库的交互次数减少系统开销提高系统效率。 什么样的数据需要缓存 经常查询并且不经常改变的数据 mybatis提供的缓存
mybatis系统中默认定义了两级缓存一级缓存二级缓存 ①默认情况下MyBatis默认开启一级缓存SqlSession级别的缓存也称之为本地缓
存SqlSession对象使用到close②二级缓存需要手动开启和配置它是基于SqlSessionFactory级别的缓存简单理解就
是通过同一个SqlSessionFactory创建的SqlSession查询的结果会被缓存 一级缓存 一级缓存称为本地缓存只在SqlSession这个区间有效。 一级缓存相当于一个map 与数据库同一会话期间查询到的数据会放入到本地缓存中。 以后需要获取相同的数据直接从缓存中拿不需要再次查找数据库。 mapper接口
User getUserById(Integer id);
mapper.xml文件
select id resultTypeUserselect * from tb_user where id #{id}
/select
test测试
public void getUserById(){try {SqlSession sqlSession getSqlSession();//一级缓存CacheMapper cacheMapper sqlSession.getMapper(CacheMapper.class);User user cacheMapper.getUserById(2);System.out.println(user);System.out.println(-------------------------------------------);User user1 cacheMapper.selectById(2);System.out.println(user1);//结果为true证明user与user1引用地址都相同从缓存中读取的数据System.out.println(useruser1);//一级缓存结束sqlSession.close();} catch (IOException e) {e.printStackTrace();}
} 一级缓存失效的情况
1不同的SqlSession对应不同的一级缓存
2同一个SqlSession但是查询条件不同
test测试
Test
public void getUserById(){try {SqlSession sqlSession getSqlSession();//一级缓存CacheMapper cacheMapper sqlSession.getMapper(CacheMapper.class);User user cacheMapper.getUserById(2);System.out.println(user);System.out.println(-------------------------------------);User user1 cacheMapper.selectById(5);//查询条件不同System.out.println(user1);//结果为true证明user与user1引用地址都相同从缓存中读取的数据System.out.println(useruser1);//一级缓存结束sqlSession.close();} catch (IOException e) {e.printStackTrace();}
} 3同一个SqlSession两次查询期间执行了任何一次增删改操作
mapper接口
//根据id查询
Select(select * from tb_user where id #{id})
User getUserById(Integer id);//修改信息
Update(update tb_user set username #{username} where id #{id})
Integer UpdateById(
Param(id) Integer id,
Param(username) String username
);
test测试
Test
public void getUserById(){try {SqlSession sqlSession getSqlSession();//一级缓存CacheMapper cacheMapper sqlSession.getMapper(CacheMapper.class);User user cacheMapper.getUserById(2);System.out.println(user);Integer num cacheMapper.UpdateById(2,tom);System.out.println(num);System.out.println(------------------------------------);User user1 cacheMapper.getUserById(5);System.out.println(user1);//结果为true证明user与user1引用地址都相同从缓存中读取的数据System.out.println(useruser1);//一级缓存结束sqlSession.close();} catch (IOException e) {e.printStackTrace();}
} 4同一个SqlSession两次查询期间手动清空了缓存
test测试
Test
public void getUserById(){try {SqlSession sqlSession getSqlSession();//一级缓存CacheMapper cacheMapper sqlSession.getMapper(CacheMapper.class);User user cacheMapper.getUserById(2);System.out.println(user);//手动调用清理缓存方法sqlSession.clearCache();System.out.println(-----------------------------------------);User user1 cacheMapper.getUserById(2);System.out.println(user1);//结果为true证明user与user1引用地址都相同从缓存中读取的数据System.out.println(useruser1);//一级缓存结束sqlSession.close();} catch (IOException e) {e.printStackTrace();}
} 二级缓存 二级缓存也称之为全局缓存因为一级的作用域太低了所以才有了二级缓存 二级缓存基于SqlSessionFactory级别的缓存通过同一个SqlSessionFactory创建的SqlSession查询的结果会被缓存 工作机制 ①一个SqlSession查询一条数据这个数据就会被放在当前SqlSession的一级缓存中②如果当前SqlSession关闭了这个SqlSession对应的一级缓存就没了但我们的需求是
SqlSession关闭一级缓存中的数据被保存在二级缓存中③新的SqlSession查询相同信息就可以从二级缓存中获取内容 开启二级缓存
mapper.xml文件
?xml version1.0 encodingUTF-8 ?
!DOCTYPE mapper
PUBLIC -//mybatis.org//DTD Mapper 3.0//EN
http://mybatis.org/dtd/mybatis-3-mapper.dtd
mapper namespacecom.java.mapper.UserMappercache
evictionFIFO
flushInterval60000
size512
readOnlytrue/
/mapper
解读
创建了一个Fifo缓存每个60秒刷新最多可以存储结果对象或列表512个引用。返回的对象被认为是只读的 可用的清楚策略 LRU – 最近最少使用移除最长时间不被使用的对象。
FIFO – 先进先出按对象进入缓存的顺序来移除它们。
SOFT – 软引用基于垃圾回收器状态和软引用规则移除对象。
WEAK – 弱引用更积极地基于垃圾收集器状态和弱引用规则移除对象。 默认的是 LRU 使用二级缓存 1实体类必须实例化
2必须使用mapper.xml映射
3,因为二级缓存是基于SqlSessionFactory的SqlSession对象要在同一个缓存范围内 新创建一个CacheMapper.xml文件
?xml version1.0 encodingUTF-8 ?
!DOCTYPE mapper
PUBLIC -//mybatis.org//DTD Mapper 3.0//EN
http://mybatis.org/dtd/mybatis-3-mapper.dtd
mapper namespacemapper.CacheMappercacheevictionFIFOflushInterval60000size512readOnlytrue/!-- User selectById(Integer id); --select idselectById resultTypeentity.Userselect * from tb_user where id#{id}/select
/mapper
test测试
Test
public void selectByIdTest(){try {//获取同一个SqlSessionFactory下的SqlSession会话对象SqlSessionFactory sqlSessionFactory MyBatisDemo2.getSqlSessionFactory();//开启2个会话 sqlSession1开启SqlSession sqlSession1 sqlSessionFactory.openSession(true);SqlSession sqlSession2 sqlSessionFactory.openSession(true);//一级缓存CacheMapper cacheMapper sqlSession1.getMapper(CacheMapper.class);User user cacheMapper.selectById(2);System.out.println(user);//一级缓存结束 sqlSession1会话结束sqlSession1.close();System.out.println(---------------------------------------);CacheMapper cacheMapper1 sqlSession2.getMapper(CacheMapper.class);User user1 cacheMapper1.selectById(2);System.out.println(user1);//结果为true证明user与user1引用地址都相同从缓存中读取的数据System.out.println(useruser1);//一级缓存结束 sqlSession2会话结束sqlSession2.close();} catch (IOException e) {e.printStackTrace();}
} 结论 1. 一级缓存默认开启用户访问进来先查看一级缓存是否有查询的数据没有在走数据库查询
2. 当二级缓存开启以后用户访问进来先查看二级缓存是否有查询的数据没有在走一级缓
存如果都没有在走数据库查询