我用的mysql版本
本地meavn仓库
1.搭建mybatis
1.开发环境
1.meavn中导入相关的依赖mybatis,mysql,junit,log4j…
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.miao</groupId>
<artifactId>tong</artifactId>
<version>1.0-SNAPSHOT</version>
<packaging>jar</packaging>
<dependencies>
<!--mybatis核心-->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.5.1</version>
</dependency>
<!--junit测试-->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
<!--mysql驱动-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.45</version>
</dependency>
</dependencies>
</project>
2.创建mybatis 的核心配置文件
- 核心配置文件主要用于配置连接数据库的环境以及MyBatis的全局配置信息
- 核心配置文件存放的位置是src/main/resources目录下
- 注意标签configuration中的标签是具有前后顺序之分的
<?xml version="1.0" encoding="UTF-8" ?>
<!--xml的约束-->
<!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
<!--设置连接数据库的环境-->
<!--default来指明使用哪一个environment因为可能存在多个并且有多个不同id的environment-->
<environments default="development">
<environment id="development">
<!--transactionManager:设置事务管理器
属性:type:设置事务管理的方式
JDBC:表示使用JDBC中原生的事务管理方式
MANAGED:被管理,例如spring
-->
<transactionManager type="JDBC"/>
<!--datasource:设置数据源
属性:type:设置数据源的类型
type="POOLED|UNPOOLED|JNDI"
POOLED:表示使用数据库连接池
UNPOOLED:表示不适用数据库连接池
JNDI:表示使用上下文中的数据源
-->
<dataSource type="POOLED">
<property name="driver" value="com.mysql.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost:3306/guli"/>
<property name="username" value="root"/>
<property name="password" value="001225"/>
</dataSource>
</environment>
</environments>
<!--引入mabtais映射文件-->
<mappers>
//属性是name的话必须
1.mapper和接口所在的包结构要一致【也就是说src下接口的结构是啥在resource下mapper文件所在的结构就是啥】
2.mapper和接口名字必须一样
//而resource可以在不同包一般在核心配置文件目录下
<mapper resource="mappers/UserMapper.XML"></mapper>
</mappers>
</configuration>
3.创建mapper接口
mybatis中的mapper接口就相当于以前的dao。但是区别在于,mapper仅仅是接口,我们不需要提供实现类。
4.创建Mybatis的映射文件
java概念 | 数据库概念 |
---|---|
类 | 表 |
属性 | 字段/列 |
对象 | 记录/行 |
1、映射文件的命名规则:
表所对应的实体类的类名+Mapper.xml
例如:表t_user,映射的实体类为User,所对应的映射文件为UserMapper.xml
因此一个映射文件对应一个实体类,对应一张表的操作
MyBatis映射文件用于编写SQL,访问以及操作表中的数据
MyBatis映射文件存放的位置是src/main/resources/mappers目录下
2、 MyBatis中可以面向接口操作数据,要保证两个一致:
a>mapper接口的全类名和映射文件的命名空间(namespace)保持一致
b>mapper接口中方法的方法名和映射文件中编写SQL的标签的id属性保持一致
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.miao.mapper.UserMapper">
<!--int insertUser();
mapper接口要保证两个一致
1.mapper接口的全类名和映射文件的namespace要一致
2.mapper接口中的方法名要和映射文件的sql中的id名一致
-->
<insert id="insertUser">
insert into t_user values(null,'admin','123456',23,'男','12345@qq.com')
</insert>
</mapper>
5.创建测试对象
//读取MyBatis的核心配置文件
InputStream is = Resources.getResourceAsStream("mybatis-config.XML");
// 创建SqlSessionFactoryBuilder对象
SqlSessionFactoryBuilder sqlSessionFactoryBuilder = new SqlSessionFactoryBuilder();
// 通过核心配置文件所对应的字节输入流创建工厂类SqlSessionFactory,生产SqlSession对象
SqlSessionFactory sqlSessionFactory = sqlSessionFactoryBuilder.build(is);
// 创建SqlSession对象,此时通过SqlSession对象所操作的sql都必须手动提交或回滚事务
SqlSession sqlSession = sqlSessionFactory.openSession();
// 创建SqlSession对象,此时通过SqlSession对象所操作的sql都会自动提交
// SqlSession session sqlSessionFactory.openSession(true); 注意这一点
// 通过代理模式创建UserMapper接口的代理实现类对象
UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
// 调用UserMapper接口中的方法,就可以根据UserMapper的全类名匹配元素文件,
// 通过调用的方法名匹配 映射文件中的SQL标签,并执行标签中的SQL语句
int result = userMapper.insertUser();
sqlSession.commit();
System.out.println(result);
sqlSession.close();
}
5.加入日志功能
1.导入相关的meavn
<!-- log4j日志 -->
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.17</version> </dependency>
2.在resources下创建log4j.xml
日志的级别
FATAL(致命)>ERROR(错误)>WARN(警告)>INFO(信息)>DEBUG(调试)
从左到右打印的内容越来越详细
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE log4j:configuration SYSTEM "log4j.dtd">
<log4j:configuration xmlns:log4j="http://jakarta.apache.org/log4j/">
<appender name="STDOUT" class="org.apache.log4j.ConsoleAppender">
<param name="Encoding" value="UTF-8" />
<layout class="org.apache.log4j.PatternLayout">
<param name="ConversionPattern" value="%-5p %d{MM-dd HH:mm:ss,SSS} %m (%F:%L) \n" />
</layout>
</appender>
<logger name="java.sql">
<level value="debug" />
</logger>
<logger name="org.apache.ibatis">
<level value="info" />
</logger>
<root>
<level value="debug" />
<appender-ref ref="STDOUT" />
</root>
</log4j:configuration>
6.完成mybatis增删查改
1.mapper层
public interface UserMapper {
//添加用户信息
int insertUser();
//修改用户信息
int updateUser();
//删除用户信息
int deleteUser();
//查看某个用户信息
User lookUser();
//查看全部用户信息
List<User> lookAllUser();
}
2.pojo层
创建对象实体并且提供get/set方法
3.映射文件xml层
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.miao.mapper.UserMapper">
<!--int insertUser();
mapper接口要保证两个一致
1.mapper接口的全类名和映射文件的namespace要一致
2.mapper接口中的方法名要和映射文件的sql中的id名一致
-->
<insert id="insertUser">
insert into t_user values(null,'admin','123456',23,'男','12345@qq.com')
</insert>
<update id="updateUser">
update t_user set id=1,username="苗苗",password=666,age=1,gender='n',email="222222" where id=2
</update>
<delete id="deleteUser">
delete from t_user where id=3
</delete>
<select id="lookUser" resultType="com.miao.pojo.User">
select * from t_user where id=4
</select>
<select id="lookAllUser" resultType="U">
select * from t_user
</select>
3.utiles层
public class GetSession {
public static SqlSession getSqlSession() throws IOException {
//读取MyBatis的核心配置文件
InputStream is = Resources.getResourceAsStream("mybatis-config.XML");
// 创建SqlSessionFactoryBuilder对象
SqlSessionFactoryBuilder sqlSessionFactoryBuilder = new SqlSessionFactoryBuilder();
// 通过核心配置文件所对应的字节输入流创建工厂类SqlSessionFactory,生产SqlSession对象
SqlSessionFactory sqlSessionFactory = sqlSessionFactoryBuilder.build(is);
// 创建SqlSession对象,此时通过SqlSession对象所操作的sql都必须手动提交或回滚事务
SqlSession sqlSession = sqlSessionFactory.openSession();
return sqlSession;
}
}
4.测试
@Test
public void test1() throws IOException {
SqlSession sqlSession = GetSession.getSqlSession();
// 通过代理模式创建UserMapper接口的代理实现类对象
UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
// 调用UserMapper接口中的方法,就可以根据UserMapper的全类名匹配元素文件,
// 通过调用的方法名匹配 映射文件中的SQL标签,并执行标签中的SQL语句
List<User> list = userMapper.lookAllUser();
for (User u:list
) {
System.out.println(u);
}
sqlSession.commit();
sqlSession.close();
}
5.查询时候的注意事项
1、查询的标签select必须设置属性resultType或resultMap,用于设置实体类和数据库表的映射关系
resultType:自动映射,用于属性名和表中字段名一致的情况
resultMap:自定义映射,用于一对多或多对一或字段名和属性名不一致的情况
6.引入外部properties文件
使用${key}来访问
1.编写properties文件
jdbc.driver=com.mysql.jdbc.Driver
jdbc.username=root
jdbc.password=001225
jdbc.url=jdbc:mysql://localhost:3306/guli
2.在mybatis核心配置文件中导入
<?xml version="1.0" encoding="UTF-8" ?>
<!--xml的约束-->
<!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
<!--引入外部Properties-->
<properties resource="jdbc.properties"></properties>
<!--设置连接数据库的环境-->
<environments default="development">
<environment id="development">
<transactionManager type="JDBC"/>
<dataSource type="POOLED">
<property name="driver" value="${jdbc.driver}"/>
<property name="url" value="${jdbc.url}"/>
<property name="username" value="${jdbc.username}"/>
<property name="password" value="${jdbc.password}"/>
</dataSource>
</environment>
</environments>
<!--引入mabtais映射文件-->
<mappers>
<mapper resource="mappers/UserMapper.XML"></mapper>
</mappers>
</configuration>
7.typeAliases的使用
作用:设置类型别名为了在映射文件中的resultType中使用
- 先在mybatis的核心配置中引入
<!--设置类型别名为了在映射文件中的resultType中使用-->
<typeAliases>
方式一:只能单个设置,不写alias默认会用类名【不区分大小写】
<typeAlias type="com.miao.pojo.User" alias="U"></typeAlias>
方式二:整个包下的都设置
<package name="com.miao.pojo"></package>
</typeAliases>
- 在mapper的映射文件中使用
<select id="lookAllUser" resultType="U">
select * from t_user
</select>
7.mybatis获取参数值的两种方式
有两种方式:${}和#{}
大多数情况我们是要从浏览器中接收到参数然后再传入sql中。
- ${}本质是字符串拼接,若字符串类型或日期类型的字段经行赋值需要手动加单引号
- #{}本质是占位符赋值,若此时字符串为字符串类型或日期类型的字段经行赋值时可以自动添加单引号【可以避免sql注入】
1.单个字面量类型的参数
字面量类型指的是:字符串、基本数据类型以及对应的包装类
User lookeUserOne(String username);
<select id="lookeUserOne" resultType="U">
select * from t_user where username=#{username}
或者
select * from t_user where username ='${name}'
</select>
2.多个字面量类型的参数
若mapper接口中的方法参数为多个时
1.此时MyBatis会自动将这些参数放在一个map集合中,
- 以arg0,arg1…为键,以参数为值;
- 以param1,param2…为键,以参数为值;
因此只需要通过KaTeX parse error: Expected 'EOF', got '#' at position 4: {}和#̲{}访问map集合的键就可以获…{}需要手动加单引号
User lookeUserTwo(String username,String password);
<select id="lookeUserTwo" resultType="U">
select * from t_user where username=#{arg0} and password=#{arg1}
或者
select * from t_user where username=#{param1} and password=#{param2}
</select>
2.使用手动的方式将参数放到map集合中
User lookeUserTwoo(Map<String,String> map);
<select id="lookeUserTwoo" resultType="U">
select * from t_user where username=#{username} and password=#{password}
</select>
SqlSession sqlSession = GetSession.getSqlSession();
// 通过代理模式创建UserMapper接口的代理实现类对象
UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
// 调用UserMapper接口中的方法,就可以根据UserMapper的全类名匹配元素文件,
// 通过调用的方法名匹配 映射文件中的SQL标签,并执行标签中的SQL语句
HashMap<String, String> sh = new HashMap<String, String>();
sh.put("username","苗苗");
sh.put("password","666");
User user = userMapper.lookeUserTwoo(sh);
System.out.println(user);
sqlSession.commit();
sqlSession.close();
3.参数类型为实体类型
//插入单个用户信息参数为对象
void insertUserOne(User user);
<select id="insertUserOne" resultType="U">
insert into t_user values (null,#{username},#{password},#{age},#{gender},#{email})
</select>
User user1 = new User(null,"同同",777,2,"女","333333");
userMapper.insertUserOne(user1);
4.使用@Param注解
手动并自动创建map,此时mybatis会将这些参数放在map中,以两种方式经行存储。
1.以@Param注解的value属性值为键,以参数为值
2.以param1,param2为键,以参数位置
注意:javaben不能使用@Param
//查看某个用户信息多个参数
User lookeUserTwo(@Param("username")String username,@Param("password") String password);
<select id="lookeUserTwo" resultType="U">
select * from t_user where username=#{username} and password=#{password}
</select>
8.resultType注意事项:
1.当结果是javabean 的时候,如果核心配置文件中typeAlias指明了别名就用别名没有指明别名就写javabean的路径。
2.如果结果是基本数据类型的时候mybatis提供了默认的别名:
<select id="lookTotalUser" resultType="Integer">
select count(*) from t_user
</select>
9.map的注意事项:
1.查询一条数据为map集合
实体类与map的区别:
1.实体类属性值给定了,值会返回。【相当于属性是key而值是value】
2.map属性值并没有给定,可以自己设,值会返回【用的最多因为很多时候从数据库返回数据的时候并没有对应的实体类】
注意:如果查询的数据里面有null则不会显示
//查询用户使用map来封装
Map<String,Object> lookeUserThree(@Param("id") Integer id);
<select id="lookeUserThree" resultType="map">
select * from t_user where id=#{id}
</select>
2.查询多条数据为map集合
方式一:
/*** 查询所有用户信息为map集合 *
@return * 将表中的数据以map集合的方式查询,一条数据对应一个map;若有多条数据,就会产生多个map集合,此 时可以将这些map放在一个list集合中获取 */
List<Map<String, Object>> getAllUserToMap();
<select id="getAllUserToMap" resultType="map"> select * from t_user </select>
方式二:
/*** 查询所有用户信息为map集合 *
@return * 将表中的数据以map集合的方式查询,一条数据对应一个map;若有多条数据,就会产生多个map集合,并 且最终要以一个map的方式返回数据,此时需要通过@MapKey注解设置map集合的键,值是每条数据所对应的 map集合 */
@MapKey("id")
Map<String, Object> getAllUserToMap();
<!--Map<String, Object> getAllUserToMap();-->
<!-- { 1={password=123456, sex=男, id=1, age=23, username=admin}
, 2={password=123456, sex=男, id=2, age=23, username=张三}
, 3={password=123456, sex=男, id=3, age=23, username=张三} }-->
<select id="getAllUserToMap" resultType="map">
select * from t_user </select>
2.map作为参数传递多个值
User lookeUserTwoo(Map<String,String> map);
<select id="lookeUserTwoo" resultType="U">
select * from t_user where username=#{username} and password=#{password}
</select>
HashMap<String, String> sh = new HashMap<String, String>();
sh.put("username","苗苗");
sh.put("password","666");
User user = userMapper.lookeUserTwoo(sh);
10.特殊的SQL的执行
1.模糊查询
List<User> testMohu(@Param("mohu") String mohu);
<!--有三种方式实现模糊查询-->
<select id="testMohu" resultType="User">
<!--select * from t_user where username like '%${mohu}%'-->
<!--select * from t_user where username like concat('%',#{mohu},'%')-->
select * from t_user where username like "%"#{mohu}"%" </select>
2.批量删除
int deleteMore(@Param("ids") String ids);
这里解释一下为什么要使用string类型:我们设想的sql语句是这样的:
delete from t_user where id in(1,2,3)
in里面是我们要想删除的id号所以在这里我们要使用String类型传参数的时候就如"1,2,3"
<delete id="deleteMore"> delete from t_user where id in (${ids}) </delete>
<!--不适用#{ids}是因为#{}是占位符而且传入是字符串的时候会自动添加单引号''
此时sql语句就成为delete from t_user where id in('1,2,3')这是错误的
-->
3.动态设置表名字
List<User> getAllUser(@Param("tableName") String tableName);
<select id="getAllUser" resultType="User">
select * from ${tableName} </select>
<!--这里说明一下为什么不使用#{}因为它是占位符而且传入是字符串的时候会自动添加单引号''-->
4.添加功能获取自增的主键
也就是当我们id是自增字段的时候我们添加一条数据的时候可以去获得到这个自增的字段。
int insertUser(User user);
<!--
useGeneratedKeys:设置使用自增的主键
keyProperty:因为增删改有统一的返回值是受影响的行数,因此只能将获取的自增的主键放在传输的参 数user对象的某个属性中-->
<insert id="insertUserp" useGeneratedKeys="true" keyProperty="id">
insert into t_user values(null,#{username},#{password},#{age},#{gender},#{email})
</insert>
User user =new User(null,"丽丽",2,2,"男","22222") ;
userMapper.insertUserp(user);
System.out.println(user);
11.当属性名和字段名不一致的情况
方式一:起别名
Emp find(@Param("id")Integer id);
<select id="find" resultType="E">
select emp_id empId,emp_name empName,age,gender,dept_id deptId from t_emp where emp_id=#{id}
</select>
方式二:在核心配置文件开启字段转换驼峰
<settings>
<setting name="mapUnderscoreToCamelCase" value="true"/>
</settings>
<select id="find" resultType="E">
select emp_id ,emp_name ,age,gender,dept_id from t_emp where emp_id=#{id}
</select>
方式三:使用resultMap自定义映射
<!--resultMap:设置自定义映射 属性:
id:表示自定义映射的唯一标识
type:查询的数据要映射的实体类的类型
子标签:
id:设置主键的映射关系 result:设置普通字段的映射关系
association:设置多对一的映射关系(处理实体类型的属性)
collection:设置一对多的映射关系 (处理集合类型的属性)
属性:
property:设置映射关系中实体类中的属性名 column:设置映射关系中表中的字段名-->
<resultMap id="map" type="E">
<id property="id" column="emp_id"></id>
<result property="empName" column="emp_name"></result>
<result property="age" column="age"></result>
<result property="gender" column="gender"></result>
<result property="deptId" column="dept_id"></result>
</resultMap>
<select id="find" resultMap="map">
select emp_id ,emp_name ,age,gender,dept_id from t_emp where emp_id=#{id}
</select>
1.多对一映射处理
例如:一个学生表对应一个部门。
1.1联级方式处理映射关系
public class Emp {
private int id;
private String empName;
private int age;
private String gender;
private Dept dept;}
public class Dept {
private int deptId;
private String deptName;}
public interface EmpMapper {
Emp find(@Param("id")Integer id);
}
<resultMap id="map" type="E">
<id property="id" column="emp_id"></id>
<result property="empName" column="emp_name"></result>
<result property="age" column="age"></result>
<result property="gender" column="gender"></result>
<result property="dept.deptId" column="dept_id"></result>
<result property="dept.deptName" column="dept_name"></result>
</resultMap>
<select id="find" resultMap="map">
select e.*,d.* from t_emp e left join t_dept d on e.dept_id=d.dept_id WHERE e.dept_id=#{id}
</select>
1.2使用assocaition来处理
<resultMap id="map" type="E">
<id property="id" column="emp_id"></id>
<result property="empName" column="emp_name"></result>
<result property="age" column="age"></result>
<result property="gender" column="gender"></result>
<association property="dept" javaType="D">
<id property="deptId" column="dpet_id"></id>
<result property="deptName" column="dept_name"></result>
</association>
</resultMap>
<select id="find" resultMap="map">
select e.*,d.* from t_emp e left join t_dept d on e.dept_id=d.dept_id WHERE e.dept_id=#{id}
</select>
注意:javaType可以忽略如果加上的话就要写出dept的类型是说明如果在mybatis核心文件指明了dept的类型的别名要一定使用那个别名。
1.3使用分布查询【以后用的最多】
https://www.cnblogs.com/zbh355376/p/14986307.html
核心在于:分开查询,让第一个查询的条件传递给第二个查询。
public interface EmpMapper {
Emp find(@Param("id")Integer id);
}
public interface DeptMapper {
Dept find(@Param("deptId")Integer deptId);
}
public class Emp {
private int id;
private String empName;
private int age;
private String gender;
private Dept dept;}
<!--EmpMapper.xml-->
<resultMap id="map" type="E">
<id property="id" column="emp_id"></id>
<result property="empName" column="emp_name"></result>
<result property="age" column="age"></result>
<result property="gender" column="gender"></result>
<!--
select:设置分步查询,查询某个属性的值的sql的标识(namespace.sqlId)
column:将sql以及查询结果中的某个字段设置为分步查询的条件
property:就是emp中Dept的成员名
-->
<association property="dept" select="com.miao.mapper.DeptMapper.find"
<!--注意find这个方法的返回时要和emp中的dept属性类型一致-->
column="dept_id"></association>
</resultMap>
<select id="find" resultMap="map">
select * from t_emp where dept_id=#{id}
</select>
<!--DeptMapper.xml-->
<select id="find" resultType="D">
select * from t_dept where dept_id=#{deptId}
</select>
分布查询的优点:可以实现延迟加载
但是必须在核心配置文件中设置全局配置信息:
**lazyLoadingEnabled:**延迟加载的全局开关。当开启时,所有关联对象都会延迟加载。
MyBatis中的延迟加载也称为懒加载,是指在进行表的关联查询时,按照设置延迟规则推迟对关联对象的select查询。在真正使用数据的时候才发起查询,不用的时候不查询关联的数据,延迟加载又叫做按需查询
aggressiveLazyLoading:当开启时,任何方法的调用挥霍加载该对象的所有属性。否则,每个属性会按需加载此时就可以实现按需加载,获取的数据是什么就会执行对应的sql。
此时可以通过设置association和collection中的fetchType属性来设置当前分布查询是否使用延迟加载,fetchType=“lazy”(延迟)/“eager”(立即)
<settings>
<setting name="mapUnderscoreToCamelCase" value="true"/>
<!--开启延迟加载-->
<setting name="lazyLoadingEnabled" value="true"/>
<!--开始按需加载-->
<setting name="aggressiveLazyLoading" value="true"/>
</settings>
2.一对多映射处理
例如:一个部门里面存在了多个学生。
2.1使用coolection
注意:对一就用对象对多就用集合。
public class Dept {
private int deptId;
private String deptName;
private List<Emp> emps;
.....
}
public interface DeptMapper {
Dept find(@Param("deptId")Integer deptId);
Dept findCooletion(@Param("deptId")Integer deptId);
}
<resultMap id="fc" type="D">
<result property="deptId" column="dept_id"></result>
<result property="deptName" column="dept_name"></result>
<!--ofType指的是集合里面的是什么类型的【这里的E是因为在mybatis】-->
<collection property="emps" ofType="E">
<result property="id" column="emp_id"></result>
<result property="emptName" column="empt_name"></result>
<result property="age" column="age"></result>
<result property="gender" column="gender"></result>
</collection>
</resultMap>
<select id="findCooletion" resultMap="fc">
select e.*,d.* from t_emp e right join t_dept d on e.dept_id=d.dept_id WHERE e.dept_id=1
</select>
2.2使用分布查询
public class Dept {
private int deptId;
private String deptName;
private List<Emp> emps;}
public class Emp {
private int id;
private String empName;
private int age;
private String gender;
private Dept dept;}
public interface DeptMapper {
Dept findCooletionFenBu(@Param("deptId")Integer deptId);
public interface EmpMapper {
List<Emp> findAll(@Param("deptId")Integer deptId);
}
<!--DeptMapper.xml-->
<resultMap id="fc1" type="D">
<result property="deptId" column="dept_id"></result>
<result property="deptName" column="dept_name"></result>
<collection property="emps" select="com.miao.mapper.EmpMapper.findAll" column="dept_id">
</collection>
</resultMap>
<select id="findCooletionFenBu" resultMap="fc1">
select * from t_dept where dept_id=#{deptId}
</select>
<!--EmpMapper.xml-->
<select id="findAll" resultType="E">
SELECT * FROM t_emp where dept_id=#{deptId}
</select>
12.动态SQL
为了解决是否要把条件拼接到SQL中。
1.if
f标签可通过test属性的表达式进行判断,若表达式的结果为true,则标签中的内容会执行;反之标签中的内容不会执行【实现了按需拼接sql】
List<Emp> findIf(Emp emp);
<select id="findIf" resultType="E">
select * from t_emp where 1=1
<!--注意''中间无空格-->
<if test="empName !='' and empName !=null ">
and emp_name=#{empName}
</if>
<if test="age !=null and age !=''">
and age=#{age}
</if>
</select>
Emp e = new Emp(null,"张三", null, "男",null);
List<Emp> anIf = mapper.findIf(e);
2.where
where和if一般结合使用:
a>若where标签中的if条件都不满足,则where标签没有任何功能,即不会添加where关键字
b>若where标签中的if条件满足,则where标签会自动添加where关键字,并将条件最前方多余的
and去掉
注意:where标签不能去掉条件最后多余的and
<select id="findIf" resultType="E">
select * from t_emp
<where>
<if test="empName !='' and empName !=null ">
and emp_name=#{empName}
</if>
<if test="age !=null and age !=' '">
and age=#{age}
</if>
</where>
</select>
3.trim
trim用于去掉或添加标签中的内容
常用属性:
prefix:在trim标签中的内容的前面添加某些内容
prefixOverrides:在trim标签中的内容的前面去掉某些内容
suffix:在trim标签中的内容的后面添加某些内容
suffixOverrides:在trim标签中的内容的后面去掉某些内容
<select id="findIf" resultType="E">
select * from t_emp
<trim prefix="where" suffixOverrides="and">
<if test="empName !='' and empName !=null ">
emp_name=#{empName}
</if>
<if test="age !=null and age !=' '">
age=#{age}
</if>
</trim>
</select>
4.choose、when、otherwise
choose、when、 otherwise相当于if…else if…else
<select id="getEmpListByChoose" resultType="Emp">
select <include refid="empColumns"></include> from t_emp
<where>
<choose>
<when test="ename != '' and ename != null">
ename = #{ename}
</when>
<when test="age != '' and age != null">
age = #{age}
</when>
<when test="sex != '' and sex != null">
sex = #{sex}
</when>
<when test="email != '' and email != null">
email = #{email}
</when>
</choose>
</where>
</select>
5.foreach
1.批量增加
//如果不用@Param的话mybatis会自动把list放入map中取除的话键为list
void inserForeach(@Param("emps") List<Emp> emps);
<select id="inserForeach">
insert into t_emp values
<!--clooection:@param的参数
item:每一条数据用什么来表示
separator:每条数据之间的分隔符
-->
<foreach collection="emps" item="E" separator=",">
(#{E.id} ,#{E.empName},#{E.age},#{E.gender},null)
</foreach>
</select>
2.批量删除
方式一:
void deleteForeach(@Param("ids") Integer[] ids);
<select id="deleteForeach">
delete from t_emp where emp_id in
(
<foreach collection="ids" item="A" separator=",">
#{A}
</foreach>
)
</select>
方式二:
open:代表把什么放在前边,close:把上面放在后面
void deleteForeach(@Param("ids") Integer[] ids);
<select id="deleteForeach">
delete from t_emp where emp_id in
<foreach collection="ids" item="A" separator="," open="(" close=")">
#{A}
</foreach>
</select>
方式三:
void deleteForeach(@Param("ids") Integer[] ids);
<select id="deleteForeach">
delete from t_emp where emp_id
<foreach collection="ids" item="or" >
#{A}
</foreach>
</select>
6.SQL片段
sql片段,可以记录一段公共sql片段,在使用的地方通过include标签进行引入
<sql id="empColumns">
eid,ename,age,sex,did
</sql>
select <include refid="empColumns"></include> from t_emp
13.MyBatis的缓存
1.一级缓存
一级缓存是SqlSession级别的,通过同一个SqlSession查询的数据会被缓存,下次查询相同的数据,就会从缓存中直接获取,不会从数据库重新访问【注意一级缓存是默认开启的】
使一级缓存失效的四种情况:
-
不同的SqlSession对应不同的一级缓存
-
同一个SqlSession但是查询条件不同
-
同一个SqlSession两次查询期间执行了任何一次增删改操作
mapper1.getid(1);
//增删改操作
xxxxxxxxxxxxxx
mapper1.getid(1);
- 同一个SqlSession两次查询期间手动清空了缓存
2.二级缓存
二级缓存是SqlSessionFactory级别,通过同一个SqlSessionFactory创建的SqlSession查询的结果会被
缓存;此后若再次执行相同的查询语句,结果就会从缓存中获取
二级缓存开启的条件:
a>在核心配置文件中,设置全局配置属性cacheEnabled=“true”,默认为true,不需要设置
b>在映射文件中设置标签
c>二级缓存必须在SqlSession关闭或提交之后有效【因为默认先保存到了一级缓存,一级缓存只有在关闭或者提交的时候才提交给二级缓存】
d>查询的数据所转换的实体类类型必须实现序列化的接口
使二级缓存失效的情况:
两次查询之间执行了任意的增删改,会使一级和二级缓存同时失效
3.二级缓存的相关配置
在mapper配置文件中添加的cache标签可以设置一些属性:
①eviction属性:缓存回收策略,默认的是 LRU。
LRU(Least Recently Used) – 最近最少使用的:移除最长时间不被使用的对象。
FIFO(First in First out) – 先进先出:按对象进入缓存的顺序来移除它们。
SOFT – 软引用:移除基于垃圾回收器状态和软引用规则的对象。
WEAK – 弱引用:更积极地移除基于垃圾收集器状态和弱引用规则的对象。
②flushInterval属性:刷新间隔,单位毫秒
默认情况是不设置,也就是没有刷新间隔,缓存仅仅调用语句时刷新
③size属性:引用数目,正整数
代表缓存最多可以存储多少个对象,太大容易导致内存溢出
④readOnly属性:只读, true/false
true:只读缓存;会给所有调用者返回缓存对象的相同实例。因此这些对象不能被修改。这提供了 很重
要的性能优势。
false:读写缓存;会返回缓存对象的拷贝(通过序列化)。这会慢一些,但是安全,因此默认是
false。
4.mybatias缓存查询的顺序
先查询二级缓存,因为二级缓存中可能会有其他程序已经查出来的数据,可以拿来直接使用。
如果二级缓存没有命中,再查询一级缓存
如果一级缓存也没有命中,则查询数据库
SqlSession关闭之后,一级缓存中的数据会写入二级缓存
5.可以整合第三方缓存
14.mybatis逆向工程
正向工程:先创建Java实体类,由框架负责根据实体类生成数据库表。 Hibernate是支持正向工
程的。
逆向工程:先创建数据库表,由框架负责根据数据库表,反向生成如下资源:
Java实体类
Mapper接口
Mapper映射文件
1.meavn
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>tong</groupId>
<artifactId>li</artifactId>
<version>1.0-SNAPSHOT</version>
<packaging>jar</packaging>
<dependencies>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.5.1</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.16</version>
</dependency>
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.17</version>
</dependency>
</dependencies>
<!--下面是逆向工程的核心配置-->
<build>
<!--构建过程中用到的插件-->
<plugins>
<plugin>
<!-- 具体插件,逆向工程的操作是以构建过程中插件形式出现的 -->
<groupId>org.mybatis.generator</groupId>
<artifactId>mybatis-generator-maven-plugin</artifactId>
<version>1.3.0</version>
<configuration>
<!--mybatis的代码生成器的配置文件-->
<configurationFile>src/main/resources/generatorConfig.XML</configurationFile>
<!--允许覆盖生成的文件-->
<!--有时候我们的数据库表添加了新字段,需要重新生成对应的文件。常规做法是手动删除旧文件,然后在用 MyBatis Generator 生成新文件。当然你也可以选择让 MyBatis Generator 覆盖旧文件,省下手动删除的步骤。-->
<!--值得注意的是,MyBatis Generator 只会覆盖旧的 po、dao、而 *mapper.xml 不会覆盖,而是追加,这样做的目的是防止用户自己写的 sql 语句一不小心都被 MyBatis Generator 给覆盖了-->
<overwrite>true</overwrite>
<verbose>true</verbose>
<!--将当前pom的依赖项添加到生成器的类路径中-->
<!--<includeCompileDependencies>true</includeCompileDependencies>-->
</configuration>
<!-- 插件的依赖 -->
<dependencies>
<dependency>
<groupId>org.mybatis.generator</groupId>
<artifactId>mybatis-generator-core</artifactId>
<version>1.3.2</version>
</dependency>
<!-- MySQL驱动 -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.16</version>
</dependency>
</dependencies>
</plugin>
</plugins>
</build>
</project>
2.插件配置文件
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE generatorConfiguration
PUBLIC "-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN"
"http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd">
<generatorConfiguration>
<!--
targetRuntime: 执行生成的逆向工程的版本
MyBatis3Simple: 生成基本的CRUD(清新简洁版)
MyBatis3: 生成带条件的CRUD(奢华尊享版)
-->
<context id="DB2Tables" targetRuntime="MyBatis3">
<!-- 数据库的连接信息 -->
<jdbcConnection driverClass="com.mysql.cj.jdbc.Driver"
connectionURL="jdbc:mysql://localhost:3306/guli?
serverTimezone=UTC"
userId="root"
password="001225">
</jdbcConnection>
<!-- javaBean的生成策略-->
<javaModelGenerator targetPackage="com.atguigu.mybatis.pojo"
targetProject=".\src\main\java">
<property name="enableSubPackages" value="true" />
<property name="trimStrings" value="true" />
</javaModelGenerator>
<!-- SQL映射文件的生成策略 -->
<sqlMapGenerator targetPackage="com.atguigu.mybatis.mapper"
targetProject=".\src\main\resources">
<property name="enableSubPackages" value="true" />
</sqlMapGenerator>
<!-- Mapper接口的生成策略 -->
<javaClientGenerator type="XMLMAPPER"
targetPackage="com.atguigu.mybatis.mapper" targetProject=".\src\main\java">
<property name="enableSubPackages" value="true" />
</javaClientGenerator>
<!-- 逆向分析的表 -->
<!-- tableName设置为*号,可以对应所有表,此时不写domainObjectName -->
<!-- domainObjectName属性指定生成出来的实体类的类名 -->
<table tableName="t_emp" domainObjectName="Emp"/>
<table tableName="t_dept" domainObjectName="Dept"/>
</context>
</generatorConfiguration>
3.mybatis核心配置文件
<?xml version="1.0" encoding="UTF-8" ?>
<!--xml的约束-->
<!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
<!--引入外部Properties-->
<properties resource="jdbc.properties"></properties>
<!--自动开启数据列转换驼峰-->
<settings>
<setting name="mapUnderscoreToCamelCase" value="true"/>
<setting name="mapUnderscoreToCamelCase" value="true"/>
<!--开启延迟加载-->
<setting name="lazyLoadingEnabled" value="true"/>
<!--开始按需加载-->
<setting name="aggressiveLazyLoading" value="true"/>
</settings>
<!--设置类型别名为了在映射文件中的resultType中使用-->
<!-- <typeAliases>-->
<!-- <typeAlias type="com.atguigu.mybatis.pojo.Dept" alias="D"></typeAlias>-->
<!-- <typeAlias type="com.atguigu.mybatis.pojo.Emp" alias="E"></typeAlias>-->
<!-- </typeAliases>-->
<!--设置连接数据库的环境-->
<environments default="development">
<environment id="development">
<transactionManager type="JDBC"/>
<dataSource type="POOLED">
<property name="driver" value="${jdbc.driver}"/>
<property name="url" value="${jdbc.url}"/>
<property name="username" value="${jdbc.username}"/>
<property name="password" value="${jdbc.password}"/>
</dataSource>
</environment>
</environments>
<!--引入mabtais映射文件-->
<mappers>
<package name="com.atguigu.mybatis.mapper"/>
</mappers>
</configuration>
4.jdbc.properties和log4j
jdbc.driver=com.mysql.cj.jdbc.Driver
jdbc.username=root
jdbc.password=001225
jdbc.url=jdbc:mysql://localhost:3306/guli?serverTimezone=UTC
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE log4j:configuration SYSTEM "log4j.dtd">
<log4j:configuration xmlns:log4j="http://jakarta.apache.org/log4j/">
<appender name="STDOUT" class="org.apache.log4j.ConsoleAppender">
<param name="Encoding" value="UTF-8" />
<layout class="org.apache.log4j.PatternLayout">
<param name="ConversionPattern" value="%-5p %d{MM-dd HH:mm:ss,SSS} %m (%F:%L) \n" />
</layout>
</appender>
<logger name="java.sql">
<level value="debug" />
</logger>
<logger name="org.apache.ibatis">
<level value="info" />
</logger>
<root>
<level value="debug" />
<appender-ref ref="STDOUT" />
</root>
</log4j:configuration>
15.分页插件
若我们自己手动取设置的话需要设置这么多的东西,而有了插件则我们只需要设置pagesize而pagenum[从页面传输过来]
limit index,pageSize
pageSize:每页显示的条数
pageNum:当前页的页码
index:当前页的起始索引,index=(pageNum-1)*pageSize
count:总记录数
totalPage:总页数
totalPage = count / pageSize;
if(count % pageSize != 0){
totalPage += 1;
}
pageSize=4,pageNum=1,index=0 limit 0,4
pageSize=4,pageNum=3,index=8 limit 8,4
pageSize=4,pageNum=6,index=20 limit 8,4
首页 上一页 2 3 4 5 6 下一页 末页
1.添加依赖
<dependency>
<groupId>com.github.pagehelper</groupId>
<artifactId>pagehelper</artifactId>
<version>5.2.0</version>
</dependency>
2.配置分页插件
在mybatis的核心配置文件中而配置插件
<plugins>
<!--设置分页插件-->
<plugin interceptor="com.github.pagehelper.PageInterceptor"></plugin>
</plugins>
3.分页插件的使用
a>在查询功能之前使用PageHelper.startPage(int pageNum, int pageSize)开启分页功能
pageNum:当前页的页码
pageSize:每页显示的条数
//查询功能开启之前开启分页功能
PageHelper.startPage(1,10);
List<Emp> emps = mapper.selectByExample(null);
//或者
PageHelper.startPage(1,10);
Page<Emp> emps = (Page)mapper.selectByExample(null);
下面是获取更为详细的内容:
b>在查询获取list集合之后,使用PageInfo pageInfo = new PageInfo<>(List list, int
navigatePages)获取分页相关数据
list:分页之后的数据
navigatePages:导航分页的页码数
c>分页相关数据
PageInfo{
pageNum=8, pageSize=4, size=2, startRow=29, endRow=30, total=30, pages=8,
list=Page{count=true, pageNum=8, pageSize=4, startRow=28, endRow=32, total=30,
pages=8, reasonable=false, pageSizeZero=false},
prePage=7, nextPage=0, isFirstPage=false, isLastPage=true, hasPreviousPage=true,
hasNextPage=false, navigatePages=5, navigateFirstPage4, navigateLastPage8,
navigatepageNums=[4, 5, 6, 7, 8]
}
pageNum:当前页的页码
pageSize:每页显示的条数
size:当前页显示的真实条数
total:总记录数
pages:总页数
prePage:上一页的页码
nextPage:下一页的页码
isFirstPage/isLastPage:是否为第一页/最后一页
hasPreviousPage/hasNextPage:是否存在上一页/下一页
navigatePages:导航分页的页码数
navigatepageNums:导航分页的页码,[1,2,3,4,5]