Mybatis-9.28
环境:
-
JDK1.8
-
Mysql 5.7
-
maven 3.6.1
-
IDEA
回顾:
-
JDBC
-
Mysql
-
Java基础
-
Maven
-
Junit
MyBatis
-
MyBatis是一款持久层框架
-
避免了所有的JDBC代码和手动设置参数以及获取结果集
-
可以使用简单的XML或注解来配置和映射原生类型、接口和Java的POJO
1.如何获得MyBatis
-
maven仓库
<!-- https://mvnrepository.com/artifact/org.mybatis/mybatis -->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.5.2</version>
</dependency>
1.1.持久化
数据持久化
-
持久化就是将程序的数据在持久状态和瞬时状态转化的过程
-
内存:断电即失
-
数据库,IO文件持久化
1.2.持久层
Dao层,Service层,Controller层...
-
完成持久化工作的代码块
-
层界限十分明显
2.第一个MaBatis程序
思路:搭建环境---->导入Mabatis----->编写代码----->测试
2.1.搭建环境
搭建数据库
create database `mybatis`;
use `mybatis`;
create table `user`(
`id` int(20) not null ,
`name` varchar(30) default null,
`pwd` varchar(30) default null,
primary key (`id`)
)engine =innodb default charset =utf8;
insert into `user`(`id`,`name`,`pwd`) values
(1,'狂神','123456'),
(2,'张三','1234567'),
(3,'李四','12345678')
新建项目
-
新建maven项目
-
导入maven依赖
<!--导入依赖-->
<dependencies>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.28</version>
</dependency>
<!--mybatis-->
<!-- https://mvnrepository.com/artifact/org.mybatis/mybatis -->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.5.11</version>
</dependency>
<!--junit-->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
</dependency>
</dependencies>
<build>
<resources>
<resource>
<directory>mybatis-01/src/main/resources</directory>
<excludes>
<exclude>**/*.properties</exclude>
<exclude>**/*.xml</exclude>
</excludes>
<filtering>true</filtering>
</resource>
<resource>
<directory>src/main/java</directory>
<includes>
<include>**/*.properties</include>
<include>**/*.xml</include>
</includes>
<filtering>true</filtering>
</resource>
</resources>
</build>
2.2创建模块
-
编写mabatis的核心配置文件
<?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">
<!--configuration核心配置文件-->
<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=true&useUnicode=true&characterEncoding=utf-8"/>
<property name="username" value="root"/>
<property name="password" value="root"/>
</dataSource>
</environment>
</environments>
<mappers>
<mapper resource="com/xcl/pojo/UserMapper.xml"/>
</mappers>
</configuration> -
编写mabatis工具类
package com.xcl.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 {
//使用Mybatis第一步:获取sqlSessionFactory对象
try {
String resource = "mybatis-config.xml";
InputStream inputStream = Resources.getResourceAsStream(resource);
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
} catch (IOException e) {
e.printStackTrace();
}
}
//既然有了 SqlSessionFactory,顾名思义,我们可以从中获得 SqlSession 的实例。
//SqlSession完全包括了面向数据库执行SQL命令所需要的所有方法
public static SqlSession getSqlSession() {
return sqlSessionFactory.openSession();
}
}
2.3编写代码
-
实体类
package com.xcl.pojo;
/**
* @author senko
* @date 2022/10/17 10:26
*/
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;
}
@Override
public String toString() {
return "User{" +
"id=" + id +
", name='" + name + '\'' +
", pwd='" + pwd + '\'' +
'}';
}
} -
Dao接口
package com.xcl.dao;
import com.xcl.pojo.User;
import java.util.List;
/**
* @author senko
* @date 2022/10/17 10:38
*/
public interface UserDao {
List<User> getUserList();
} -
接口实现类由原来的UserDaoImpl转变为一个Mapper配置文件
<?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 namespace="com.xcl.dao.UserDao">
<select id="getUserList" resultType="com.xcl.pojo.User">
select * from mybatis.user
</select>
</mapper>
2.4测试
-
junit测试
package com.xcl.dao; import com.xcl.pojo.User; import com.xcl.utils.MybatisUtils; import org.apache.ibatis.session.SqlSession; import org.junit.Test; import java.util.List; /** * @author senko * @date 2022/11/12 14:34 */ public class UserDaoTest { @Test public void test(){ SqlSession sqlSession = MybatisUtils.getSqlSession(); Dao mapper = sqlSession.getMapper(Dao.class); List<User> userList = mapper.getUserList(); for (User user : userList) { System.out.println(user); } sqlSession.close(); } }
3.CRUD
3.1namespace
namespace中的报名要和Dao/mapper接口的报名一致
3.2select
选择查询语句:
-
id:就是对应的namespace中的方法名
-
resulType:Sql语句执行的返回值
-
paramerType:参数类型
-
编写接口
//查询全部用户 List<User> getUserList(); //根据id查询用户 User getUserById(int id); //insert一个用户 int addUser(User user); int updateUser(User user); int deleteUser(int id);
-
编写对应的mapper中的sql语句
<!--namespace绑定一个对应的Dao接口--> <mapper namespace="com.xcl.dao.Dao"> <select id="getUserList" resultType="com.xcl.pojo.User"> select * from mybatis2.user </select> <select id="getUserById" parameterType="int" resultType="com.xcl.pojo.User"> select * from mybatis2.user where id=#{id} </select> <insert id="addUser" parameterType="com.xcl.pojo.User" > insert into mybatis2.user(id,name,pwd) values (#{id},#{name},#{pwd}) </insert> <update id="updateUser" parameterType="com.xcl.pojo.User"> update mybatis2.user set name=#{name},pwd=#{pwd} where id = #{id}; </update> <delete id="deleteUser" parameterType="int"> delete from mybatis2.user where id=#{id} </delete> </mapper>
-
测试
public class UserDaoTest { @Test public void getUserList(){ SqlSession sqlSession = MybatisUtils.getSqlSession(); Dao mapper = sqlSession.getMapper(Dao.class); List<User> userList = mapper.getUserList(); for (User user : userList) { System.out.println(user); } sqlSession.close(); } @Test public void getUserById(){ SqlSession sqlSession = MybatisUtils.getSqlSession(); Dao mapper = sqlSession.getMapper(Dao.class); User user = mapper.getUserById(1); System.out.println(user); sqlSession.close(); } @Test public void addUser(){ SqlSession sqlSession = MybatisUtils.getSqlSession(); Dao mapper = sqlSession.getMapper(Dao.class); int res= mapper.addUser(new User(4,"很爱很爱你","123456")); if (res>0){ System.out.println("插入成功"); } //提交事务 sqlSession.commit(); sqlSession.close(); } @Test public void update(){ SqlSession sqlSession = MybatisUtils.getSqlSession(); Dao mapper = sqlSession.getMapper(Dao.class); mapper.updateUser(new User(4,"hehe","123")); sqlSession.commit();//提交事务 sqlSession.close(); } @Test public void deleteUser(){ SqlSession sqlSession = MybatisUtils.getSqlSession(); Dao mapper = sqlSession.getMapper(Dao.class); mapper.deleteUser(4); sqlSession.commit(); sqlSession.close(); } }
3.3Insert
3.4update
3.5delete
注意:
-
增删需要提交事务
3.6分析错误
-
标签匹配错误
-
resource绑定mapper,需要使用路径
-
程序配置文件必须符合规范
-
NullPointerException,没有注册到资源
-
输出的xml文件中存在乱码问题
-
maven资源没有导出问题
3.7万能的Map
User getUserById2(Map<String,Object> map); int addUser2(Map<String,Object> map);
<select id="getUserById2" parameterType="map" resultType="com.xcl.pojo.User"> select * from mybatis2.user where id=#{id} and name=#{name} </select> <insert id="addUser2" parameterType="map"> insert into mybatis2.user(id,name,pwd) values (#{userid},#{username},#{userpwd}) </insert>
@Test public void addUser2(){ SqlSession sqlSession = MybatisUtils.getSqlSession(); Dao mapper = sqlSession.getMapper(Dao.class); Map<String, Object> map = new HashMap<String,Object>(); map.put("userid",5); map.put("username","hello"); map.put("userpwd","222111"); mapper.addUser2(map); sqlSession.commit(); sqlSession.close(); } @Test public void getUserById2() { SqlSession sqlSession = MybatisUtils.getSqlSession(); Dao mapper = sqlSession.getMapper(Dao.class); Map<String, Object> map = new HashMap<String,Object>(); map.put("id",5); map.put("name","hello"); User user = mapper.getUserById2(map); System.out.println(user); sqlSession.close(); }
Map传递参数,直接在sql中取出key即可【parameterType="map"】
对象传递参数,直接在sql中取对象的属性即可【parameterType="object"】
只有一个基本类型参数的情况下,可以直接在sql中取到
多个参数用map,或者注解
3.8模糊查询
List<User> getUserLike(String value);
1.Java代码执行的时候,传递通配符%%
<select id="getUserLike" resultType="com.xcl.pojo.User"> select * from mybatis2.user where name like #{value} </select>
2.在sql拼接中使用通配符
<select id="getUserLike" resultType="com.xcl.pojo.User"> select * from mybatis2.user where name like "%"#{value}"%"} </select>
测试
public void getUserLike(){ SqlSession sqlSession = MybatisUtils.getSqlSession(); Dao mapper = sqlSession.getMapper(Dao.class); List<User> userLike = mapper.getUserLike("%李%"); for (User user : userLike) { System.out.println(user); } sqlSession.close(); }
4.配置解析
4.1核心配置文件
-
mybatis-config.xml
-
Mybatis的配置文件包含了会影响Mybatis行为的设置和属性信息
configuration(配置) properties(属性) settings(设置) typeAliases(类型别名) typeHandlers(类型处理器) objectFactory(对象工厂) plugins(插件) environments(环境配置) environment(环境变量) transactionManager(事务管理器) dataSource(数据源) databaseIdProvider(数据库厂商标识) mappers(映射器
4.2环境配置
Mybatis可以配置成时应多种环境
不过要记住:尽管可以配置多个环境,但每个 SqlSessionFactory 实例只能选择一种环境。
Mybatis默认的事务管理器JDBC,连接池:POOLED
4.3属性
可以通过properties属性实现引用配置文件
这些属性可以在外部进行配置,并可以进行动态替换。你既可以在典型的 Java 属性文件中配置这些属性,也可以在 properties 元素的子元素中设置。
4.3.1编写一个配置文件
db.properties
driver=com.mysql.jdbc.Driver url=jdbc:mysql://localhost:3306/mybatis2?useSSL=false&useUnicode=true&characterEncoding=utf-8"
在核心配置文件中映入
<!--configuration核心配置文件--> <configuration> <!--引入外部配置文件--> <properties resource="db.properties"> <property name="username" value="root"/> <property name="password" value="root"/> </properties> <environments default="development"> <environment id="development"> <transactionManager type="JDBC"/> <dataSource type="POOLED"> <property name="driver" value="${driver}"/> <property name="url" value="${url}"/> <property name="username" value="${username}"/> <property name="password" value="${password}"/> </dataSource> </environment> </environments> <mappers> <mapper resource="com/xcl/dao/MapperDao.xml"/> </mappers>
-
可以直接引入外部文件
-
可以在其中增加一些属性配置
-
如果两个文件有同一个字段,优先使用外部配置文件
4.4类型别名(typeAliases)
-
类型别名可为 Java 类型设置一个缩写名字
-
意在降低冗余的全限定类名书写
<!--可以给实体类起别名--> <typeAliases> <typeAlias type="com.xcl.pojo.User" alias="User"/> </typeAliases>
也可以指定一个包名,Mybatis会在包名下面搜索需要的Java Bean,比如:
扫描实体类的包,它的默认别名就为这个类的类名,首字母小写
<!--可以通过包名起别名--> <typeAliases> <package name="com.xcl.pojo" /> </typeAliases>
在实体类少的时候使用第一种
实体类多的时候使用第二种
第一种可以DIY起别名(DIY是自定义);第二种不行(默认小写);如果非要改,需要在实体类上增加注解
@Alias("User")使用注解起别名 public class User {
4.5映射器
MapperRegistry:注册绑定Mapper文件
方式一:
<!--每一个Mapper.xml都需要在Mybatis核心配置文件中注册--> <mappers> <mapper resource="com/xcl/dao/MapperDao.xml"/> </mappers>
方式二:使用class文件绑定注册
<mappers> <mapper class="com.xcl.dao.Dao"/> </mappers>
注意点:
-
接口和他的Mapper配置文件必须同名
-
接口和他的Mapper配置文件必须在同一个包下
方式三:使用扫描包进行注入绑定
<mappers> <package name="com.xcl.dao"/> </mappers>
注意点:
-
接口和他的Mapper配置文件必须同名
-
接口和他的Mapper配置文件必须在同一个包下
4.6生命周期和作用域
SqlSessionFactoryBuilder:
-
一但创建了SqlSessionFactory,就不再需要他了
-
局部变量
SqlSessionFactory:
-
可以想象为数据库连接池
-
SqlSessionFactory一旦被创建就应该在应用的运行期间一直存在,没有任何理由丢弃它或重新创建另一个实例
-
因此SqlSessionFactory的最佳作用域是应用作用域
SqlSession:
-
连接到连接池的一个请求
-
关闭请求
5.解决属性名和字段名不一致的问题
数据库中的字段
新建一个项目,拷贝之前的,测试实体类字段不一致的情况
public class User { private int id; private String name; private String password;//原来写的是pwd }
运行结果
User{id=1, name='狂神', password='null'} Process finished with exit code 0
映射文件
select * from mybatis2.user where id=#{id} select id,name,pwd from mybatis2.user where id=#{id}
解决方法
1.起别名
<select id="getUserById" parameterType="int" resultType="com.xcl.pojo.User"> select id,name,pwd as password from mybatis2.user where id=#{id} </select>
2.resultMap
结果映射集
id name pwd id name password
<mapper namespace="com.xcl.dao.Dao"> <resultMap id="UserMap" type="User"> <result column="id" property="id"/> <result column="name" property="name"/> <result column="pwd" property="password"/> </resultMap> <select id="getUserList" resultType="User" resultMap="UserMap"> select * from mybatis2.user </select>
6.日志
6.1日志工厂
STDOUT_LOGGING标准日志输出、
在mybatis-config配置文件中配置日志
<settings> <setting name="logImpl" value="STDOUT_LOGGING"/> </settings>
LOG4J
-
使用 LOG4J可以控制日志信息输送的目的地是控制台、文件、GUI组件
-
可以控制每一条日志的输出格式
-
可以通过定义每一条日志的级别,可以控制日志的生成过程
-
通过一个配置文件来灵活的进行配置,而不需要修改应用的代码
-
先导入 LOG4J的包
<dependency> <groupId>log4j</groupId> <artifactId>log4j</artifactId> <version>1.2.17</version> </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/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
3.配置log4j为日志的实现
<settings> <setting name="logImpl" value="LOG4J"/> </settings>
4.Log4j的使用,直接测试运行刚才的查询
简单实用
1.在要使用Log4j的类中,导入包import org.apache.log4j.Logger;
2.日志对象,参数为当前类的class
static Logger logger=Logger.getLogger(UserDaoTest.class);
3.日志级别
logger.info("info:进入了log4jTest"); logger.debug("debug:进入了log4jTest"); logger.error("error:进入了log4jTest");
7.分页
7.1使用Limit分页
语法:select * from user limit startIndex,pageSize(起始位置,每页显示的数量) select * from user limit 3,4 select * from user limit 3(0~3)
使用Mybatis实现分页
-
接口
List<User> getUserByLimit(Map<String,Integer> map);
-
mapper.xml
<select id="getUserByLimit" parameterType="map" resultMap="UserMap"> select * from mybatis2.user limit #{startIndex},#{pageSize} </select>
-
测试
@Test public void getUserByLimit(){ SqlSession sqlSession = MybatisUtils.getSqlSession(); Dao mapper = sqlSession.getMapper(Dao.class); HashMap<String, Integer> map = new HashMap<String,Integer>(); map.put("startIndex",0); map.put("pageSize",2); List<User> userList = mapper.getUserByLimit(map); for (User user : userList) { System.out.println(user); } sqlSession.close(); }
7.2RowBounds分页
接口
List<User> getUserByBounds((Map<String,Integer> map);
mapper.xml
<select id="getUserByBounds" resultMap="UserMap" parameterType="map"> select * from mybatis2.user </select>
测试
@Test public void getUserByBounds(){ SqlSession sqlSession = MybatisUtils.getSqlSession(); //RowBounds实现 RowBounds rowBounds = new RowBounds(1, 2); //通过Java代码层面实现分页 List<User> userList = sqlSession.selectList("com.xcl.dao.Dao.getUserByBounds", null, rowBounds); for (User user : userList) { System.out.println(user); } sqlSession.close(); }
8.使用注解开发
1.注解在接口上实现
public interface UserMapper { @Select("select * from user") List<User> getUsers(); }
2.需要在核心配置文件中绑定接口
<!--绑定接口--> <mappers> <mapper class="com.xcl.dao.UserMapper"/> </mappers>
3.测试
@Test public void Test(){ SqlSession sqlSession = MybatisUtils.getSqlSession(); UserMapper mapper = sqlSession.getMapper(UserMapper.class); List<User> users = mapper.getUsers(); for (User user : users) { System.out.println(users); } sqlSession.close(); }
本质:反射机制实现
底层:动态代理
CRUD
可以在工具类创建的时候实现自动提交事务
-
自动提交事务
public static SqlSession getSqlSession(){ SqlSession sqlSession= sqlSessionFactory.openSession(true); return sqlSession; // return sqlSessionFactory.openSession(); }
-
编写接口
public interface UserMapper { @Select("select * from user") List<User> getUsers(); @Select("select * from user where id=#{id}") User getUserById(@Param("id") int id);//#{id}对应@Param("id") @Insert("insert into user(id,name,pwd) values (#{id},#{name},#{password})") int addUser(User user); @Update("update user set name=#{name},pwd=#{password} where id=#{id}") int updateUser(User user); @Delete("delete from user where id=#{uid};") int deleteUser(@Param("uid") int id); }
-
测试
public class UserMapperTest { @Test public void Test(){ SqlSession sqlSession = MybatisUtils.getSqlSession(); UserMapper mapper = sqlSession.getMapper(UserMapper.class); List<User> users = mapper.getUsers(); for (User user : users) { System.out.println(users); } sqlSession.close(); } @Test public void getUserById(){ SqlSession sqlSession = MybatisUtils.getSqlSession(); UserMapper mapper = sqlSession.getMapper(UserMapper.class); User user = mapper.getUserById(2); System.out.println(user); sqlSession.close(); } @Test public void addUser(){ SqlSession sqlSession = MybatisUtils.getSqlSession(); UserMapper mapper = sqlSession.getMapper(UserMapper.class); mapper.addUser(new User(7,"夏昌隆","000000")); sqlSession.close(); } @Test public void update(){ SqlSession sqlSession = MybatisUtils.getSqlSession(); UserMapper mapper = sqlSession.getMapper(UserMapper.class); mapper.updateUser(new User(5,"小猪","000000")); sqlSession.close(); } @Test public void delete(){ SqlSession sqlSession = MybatisUtils.getSqlSession(); UserMapper mapper = sqlSession.getMapper(UserMapper.class); mapper.deleteUser(6); sqlSession.close(); } }
注意注册接口
<!--绑定接口--> <mappers> <mapper class="com.xcl.dao.UserMapper"/> </mappers>
关于@Param()注解
-
基本类型的参数或者String类型,需要加上
-
引用类型不需要加
-
如果只有一个基本类型,可以忽略
9.Lombok
说明:
@Data:无参构造,get,set,tostring,hashcode,equals @AllArgsConstructor//有参构造 @NoArgsConstructor//无参构造
导包:
<groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> <version>1.18.12</version> </dependency>
10.多对一
jdbc
CREATE TABLE `teacher` ( `id` INT(10) NOT NULL, `name` VARCHAR(30) DEFAULT NULL, PRIMARY KEY (`id`) ) ENGINE=INNODB DEFAULT CHARSET=utf8; INSERT INTO teacher(`id`, `name`) VALUES (1, '秦老师'); CREATE TABLE `family` ( `id` INT(10) NOT NULL, `name` VARCHAR(30) DEFAULT NULL, PRIMARY KEY (`id`) ) ENGINE=INNODB DEFAULT CHARSET=utf8; INSERT INTO family(`id`, `name`) VALUES (1, 'mama'); 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文件
-
在核心配置中绑定注册Mapper接口或者文件
-
测试
按照查询嵌套处理
<!--思路: 1.查询所有的学生信息 2.根据查出来的学生tid,寻找对应的老师--> <select id="getStudent" resultMap="StudentTeacher"> select * from student </select> <resultMap id="StudentTeacher" type="Student"> <result property="id" column="id"/> <result property="name" column="name"/> <association property="teacher" column="tid" javaType="Teacher" select="getTeacher"/> </resultMap> <select id="getTeacher" resultType="Teacher"> select * from teacher where id=#{id} </select>
按照结果嵌套处理
public List<Student> getStudent2();
<!--方式二 :按照结果嵌套处理--> <select id="getStudent2" resultMap="StudentTeacher2"> select s.id sid,s.name sname,t.name tname from student s,teacher t where s.tid=t.id </select> <resultMap id="StudentTeacher2" type="Student"> <result property="id" column="sid"/> <result property="name" column="sname"/> <association property="teacher" javaType="Teacher"> <result property="name" column="tname"/> </association> </resultMap>
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; }
// 按照结果查询 <mapper namespace="com.xcl.dao.TeacherMapper"> <select id="getTeacher" resultMap="Teacher"> select s.id sid,s.name sname,t.name tname,t.id tid from student s,teacher t where s.tid=t.id and t.id=#{tid} </select> <resultMap id="TeacherStudent" 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="tid"/> </collection> </resultMap> <!--======================================================================--> //按照查询嵌套处理 <select id="getTeacher2" resulyMap="TeacherStudent2"> select * from mybatis2.teacher where id=#{tid} </select> <resultMap id="TeacherStudent2" type="Teacher"> <collection property="students" javaType="ArrayList" ofType="Student" select="getStudentTeacherId" column="id"/> </resultMap> <select id="getStudentTeacherId" resulType="Student"> select * from mybatis2.student where tid=#{tid} </select> </mapper>
1.关联-association【多对一】
2.集合-collection【一对多】
3.javaType & ofType
1.javaType 用来指定实体类中属性的类型
2. ofType用来指定映射到List或者集合中的pojo类型,泛指的约束类型
12.动态SQL
环境搭建
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;
创建一个基础工程
-
导包
-
编写配置文件
driver=com.mysql.jdbc.Driver url=jdbc:mysql://localhost:3306/mybatis2?useSSL=false&useUnicode=true&characterEncoding=utf-8"
<?xml version="1.0" encoding="UTF8" ?> <!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "http://mybatis.org/dtd/mybatis-3-config.dtd"> <!--configuration核心配置文件--> <configuration> <!--引入外部配置文件--> <properties resource="db.properties"> <property name="username" value="root"/> <property name="password" value="root"/> </properties> <settings> <!-- 标准的日志工厂实现--> <setting name="logImpl" value="STDOUT_LOGGING"/> <!-- 开启驼峰命名规则--> <setting name="mapUnderscoreToCamelCase" value="true"/> </settings> <!--可以给实体类起别名--> <typeAliases> <typeAlias type="com.xcl.pojo.Blog" alias="Blog"/> </typeAliases> <!--<!–可以通过包名起别名–>--> <!-- <typeAliases>--> <!-- <package name="com.xcl.pojo" />--> <!-- </typeAliases>--> <environments default="development"> <environment id="development"> <transactionManager type="JDBC"/> <dataSource type="POOLED"> <property name="driver" value="${driver}"/> <property name="url" value="${url}"/> <property name="username" value="${username}"/> <property name="password" value="${password}"/> </dataSource> </environment> </environments> <!--绑定接口--> <mappers> <mapper resource="com/xcl/dao/BlogMapper.xml"/> </mappers> </configuration>
-
编写实体类
@Data public class Blog { private int id; private String title; private String author; private Data creattime; private int views; }
-
编写实体类对应Mapper接口和Mapper.xml文件
public interface BlogMapper { int addBlog(Blog blog); }
<?xml version="1.0" encoding="UTF8" ?> <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd"> <mapper namespace="com.xcl.dao.BlogMapper"> <insert id="addBlog" parameterType="Blog"> insert into mybatis2.blog(id,title,author,create_time,views) values (#{id},#{title},#{author},#{createTime},#{views}) </insert> </mapper>
5.工具类
//获取随机ID public class IDUtils { public static String getId(){ return UUID.randomUUID().toString().replaceAll("-",""); } @Test public void main(){ System.out.println(IDUtils.getId()); } }
package com.xcl.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; public class MybatisUtils { private static SqlSessionFactory sqlSessionFactory; static { try { 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(true); return sqlSession; // return sqlSessionFactory.openSession(); } }
IF
<select id="queryBlogIF" parameterType="map" resultType="com.xcl.pojo.Blog"> select * from blog where 1=1 <if test="title !=null"> and title=#{title} </if> <if test="author != null"> and author = #{author} </if> <if test="views != null"> and views = #{views} </if> </select>
choose(when,otherwise)
哪一个先成立运行那个
<select id="queryBlogChoose" parameterType="map" resultType="Blog"> select * from blog <where> <choose> <when test="author != null"> author = #{author} </when> <when test="title != null"> and title=#{title} </when> <otherwise> and views=#{views} </otherwise> </choose> </where> </select>
trim(where,set)
<select id="queryBlogIF" parameterType="map" resultType="com.xcl.pojo.Blog"> select * from blog <where> <if test="title !=null"> and title=#{title} </if> <if test="author != null"> and author = #{author} </if> <if test="views != null"> and views = #{views} </if> </where> </select>
SQL片段(可以实现代码复用)
<sql id="blog"> <if test="title !=null"> title=#{title} </if> <if test="author != null"> and author = #{author} </if> <if test="views != null"> and views = #{views} </if> </sql>
<select id="queryBlogIF" parameterType="map" resultType="com.xcl.pojo.Blog"> select * from blog <where> <include refid="blog"/> </where> </select>
Foreach
where默认1=1
<select id="queryBlogForeach" parameterType="map" resultType="com.xcl.pojo.Blog"> select * from blog <where> <foreach collection="ids" item="id" open="and (" close=")" separator="or"> id=#{id} </foreach> </where> </select>
@org.junit.Test public void queryForeachBlog(){ SqlSession sqlSession = MybatisUtils.getSqlSession(); BlogMapper mapper = sqlSession.getMapper(BlogMapper.class); HashMap map = new HashMap(); ArrayList<Integer> ids = new ArrayList<Integer>(); ids.add(1); ids.add(2); ids.add(3); ids.add(4); map.put("ids",ids); List<Blog> blogs = mapper.queryBlogForeach(map); for (Blog blog : blogs) { System.out.println(blog); } sqlSession.close(); }
13.缓存
1.一级缓存
实体类
@Data @AllArgsConstructor @NoArgsConstructor public class User { private int id; private String name; private String pwd; }
接口
public interface UserMapper { User queryUserId(@Param("id") int id); int update(User user); }
映射文件
<select id="queryUserId" resultType="User"> select * from user where id=#{id} </select> <update id="update" parameterType="user"> update user set name=#{name},pwd=#{pwd} where id=#{id} </update>
test
@org.junit.Test public void queryUserId(){ SqlSession sqlSession = MybatisUtils.getSqlSession(); UserMapper mapper = sqlSession.getMapper(UserMapper.class); User user = mapper.queryUserId(1); System.out.println(user); sqlSession.clearCache();//手动清理缓存,也会使缓存失效 System.out.println("========================================="); User user2 = mapper.queryUserId(1); System.out.println(user2); System.out.println(user==user2); sqlSession.close(); } @org.junit.Test public void update(){ SqlSession sqlSession = MybatisUtils.getSqlSession(); UserMapper mapper = sqlSession.getMapper(UserMapper.class); User user = mapper.queryUserId(1); System.out.println(user); mapper.update(new User(2,"aaaa","bbbb")); System.out.println("========================================="); User user2 = mapper.queryUserId(1); System.out.println(user2); System.out.println(user==user2); sqlSession.close(); }
2.二级缓存
步骤:
-
开启全局缓存
<!--显示的开启全局缓存--> <setting name="catchEnabled" value="true"/>
-
在要使用二级缓存的Mapper中开启
<!--在当前Mapper.xml中开启二级缓存--> <cache/>
也可以自定义参数
<cache eviction="FIFO" flushInterval="60000" size="512" readOnly="true"/>
-
测试
@org.junit.Test public void queryUserId2(){ SqlSession sqlSession = MybatisUtils.getSqlSession(); UserMapper mapper = sqlSession.getMapper(UserMapper.class); User user = mapper.queryUserId(1); System.out.println(user); sqlSession.close(); System.out.println("========================================="); SqlSession sqlSession2 = MybatisUtils.getSqlSession(); UserMapper mapper2 = sqlSession2.getMapper(UserMapper.class); User user2 = mapper2.queryUserId(1); System.out.println(user2); sqlSession2.close(); }
注意:
二级缓存要将实体类序列化
@Data @AllArgsConstructor @NoArgsConstructor public class User implements Serializable { private int id; private String name; private String pwd; }
需要在同一个Mapper下
所有的数据会先放到一级缓存中
只有当会话提交或者关闭的时候,才会提交到二级缓存中
<!--useCache="false"可以设置不使用二级缓存--> <select id="queryUserId" resultType="User" useCache="false">
<!--flushCache="false"不刷新缓存,太频繁的情况下可以用--> <update id="update" parameterType="user" flushCache="false"> update user set name=#{name},pwd=#{pwd} where id=#{id} </update>
3.自定义缓存
-
导包
<dependency> <groupId>org.mybatis.caches</groupId> <artifactId>mybatis-ehcache</artifactId> <version>1.1.0</version> </dependency>
-
在mapper中指定我们的ehcache缓存实现
<cache type="org.mybatis.caches.ehcache.EhcacheCache"/>
-
ehcache.xml
<?xml version="1.0" encoding="UTF-8"?>标签:mapper,name,id,sqlSession,user,mybatis,public From: https://www.cnblogs.com/xclxcl/p/16945577.html
<ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="http://ehcache.org/ehcache.xsd"
updateCheck="false">
<diskStore path="./tmpdir/Tmp_EhCache"/>
<defaultCache
eternal="false"
maxElementsInMemory="10000"
overflowToDisk="false"
diskPersistent="false"
timeToIdleSeconds="1800"
timeToLiveSeconds="259200"
memoryStoreEvictionPolicy="LRU"/>
<cache
name="cloud_user"
eternal="false"
maxElementsInMemory="5000"
overflowToDisk="false"
diskPersistent="false"
timeToIdleSeconds="1800"
timeToLiveSeconds="1800"
memoryStoreEvictionPolicy="LRU"/>
</ehcache>