MyBatis笔记

目录

一,MyBatis开发步骤

1. 导入MyBatis的坐标和其他相关坐标

2. 创建user数据表

 3. 编写User实体

4. 编写UserMapper映射文件

5. 编写MyBatis核心文件

6.编写测试代码

二,MyBatis的映射文件

 ▲动态sql语句

1.动态 SQL 之:

2.动态SQL之:

3.动态SQL之:

4.动态SQL之

5.动态 SQL 之:

 ★sql片段抽取:

 三,MyBatis的增删改查操作

★MyBatis获取参数值的两种方式(重点)

模糊查询:

批量删除:

1,MyBatis的插入数据操作

1)编写UserMapper映射文件

MyBatis获取插入功能自增的主键:

2) 编写插入实体User的代码

3) 插入操作注意问题

2.MyBatis的修改数据操作

1)编写UserMapper映射文件

2)编写修改实体User的代码

3)修改操作注意问题

3.MyBatis的删除数据操作

1)编写UserMapper映射文件

2)编写删除数据的代码

3) 删除操作注意问题

4.MyBatis的查询数据操作

ResultMap的使用:

四,. MyBatis核心配置文件 

1.MyBatis核心配置文件层级关系:

 2.MyBatis常用配置解析:

1)environments标签

2)mapper标签

★mapper以及mapper配置文件的目录:

3)Properties标签

 4)typeAliases标签★

 5)typeHandlers标签

 6)plugins标签

▲获得分页相关的其他参数:

五,MyBatis相应API 

1,SqlSession工厂对象SqlSessionFactory

 2.SqlSession会话对象

 六,.使用Mybatis的Dao层实现

1,传统开发方式:

1)编写UserDao接口

2). 编写UserDaoImpl实现

​ 3). 测试传统方式

 2.代理开发方式(重点)

七,Mybatis多表查询

1.多对一查询:

多对一时:

 1)创建Order和User实体

 2)创建OrderMapper接口

3)配置OrderMapper.xml

 4)测试结果

★多对一分步查询: 

 2.一对多查询:

一对多时:

 1)修改User实体

 2)创建UserMapper接口

3)配置UserMapper.xml

 4)测试结果

★分步查询

 3.多对多查询:

​ 1)创建Role实体,修改User实体

2)添加UserMapper接口方法

 3)配置UserMapper.xml

 4)测试结果

八,Mybatis的注解开发 

1.MyBatis的常用注解

2.MyBatis的增删改查

★重点配置

​ 3.MyBatis的注解实现复杂映射开发

​ 1)一对一查询:

 2)一对多查询:

 3)多对多查询:

九,MyBatis的缓存

1.MyBatis的一级缓存:

2.MyBatis的二级缓存:

十,MyBatis的逆向工程:

1.概念理解:

2.具体实现步骤

1)pom.xml的配置

2)创建MyBatis的核心配置文件

3)创建逆向工程的配置文件

 3.MyBatis3中的QBC风格

十一,分页插件 

1.分页插件的使用步骤

1)添加依赖

2)配置分页插件

 2.分页插件的使用

1)开启分页功能

2)分页相关数据


一,MyBatis开发步骤

MyBatis开发步骤:

① 添加MyBatis的坐标

② 创建user数据表

③ 编写User实体类

④ 编写映射文件UserMapper.xml

⑤ 编写核心文件SqlMapConfig.xml

⑥ 编写测试类

1. 导入MyBatis的坐标和其他相关坐标

<!--mybatis坐标-->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.4.5</version>
</dependency>
<!--mysql驱动坐标-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.6</version>
<scope>runtime</scope>
</dependency>
<!--单元测试坐标-->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
<!--日志坐标-->
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.12</version>
</dependency>

2. 创建user数据表

 3. 编写User实体

public class User {
private int id;
private String username;
private String password;
//省略get个set方法
}

4. 编写UserMapper映射文件

<?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="userMapper">
<select id="findAll" resultType="com.itheima.domain.User">
select * from User
</select>
</mapper>

5. 编写MyBatis核心文件

<!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN“ "http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
<environments default="development">
<environment id="development">
<transactionManagertype="JDBC"/>
<dataSource type="POOLED">
<property name="driver" value="com.mysql.jdbc.Driver"/><property name="url" value="jdbc:mysql:///test"/>
<property name="username" value="root"/><property name="password" value="root"/>
</dataSource>
</environment>
</environments>
<mappers> <mapper resource="com/itheima/mapper/UserMapper.xml"/> </mappers>
</configuration>

6.编写测试代码

二,MyBatis的映射文件

 ▲动态sql语句

1.动态 SQL 之<if>:

我们根据实体类的不同取值,使用不同的 SQL语句来进行查询。比如在 id如果不为空时可以根据id查询,如果 username 不同空时还要加入用户名作为条件。这种情况在我们的多条件组合查询中经常会碰到。

<select id="findByCondition" parameterType="user" resultType="user">
select * from User
<where>
<if test="id!=0">
and id=#{id}
</if>
<if test="username!=null and username !=''">
and username=#{username}
</if>
</where>
</select>

当查询条件id和username都存在时,控制台打印的sql语句如下:

当查询条件只有id存在时,控制台打印的sql语句如下:

2.动态SQL之<where>:

where标签中有内容时,会自动生成where关键字,并将内容前多余的and或or去掉

where标签中没有内容时,此时where标签没有任何效果

<!--List<Emp> getEmpByCondition(Emp emp);-->
<select id="getEmpByCondition" resultType="Emp">
	select * from t_emp
	<where>
		<if test="empName != null and empName !=''">
			emp_name = #{empName}
		</if>
		<if test="age != null and age !=''">
			and age = #{age}
		</if>
		<if test="sex != null and sex !=''">
			and sex = #{sex}
		</if>
		<if test="email != null and email !=''">
			and email = #{email}
		</if>
	</where>
</select>
  • 注意:where标签不能去掉条件后多余的and/or

 

3.动态SQL之<trim>:

用于去掉标签或添加标签头和尾的内容

若标签中有内容时

prefix/suffix:将trim标签中内容前面或后面添加指定内容

suffixOverrides/prefixOverrides:将trim标签中内容前面或后面去掉指定内容

若标签中没有内容时,trim标签页没有任何效果

<!--List<Emp> getEmpByCondition(Emp emp);-->
<select id="getEmpByCondition" resultType="Emp">
	select * from t_emp
	<trim prefix="where" suffixOverrides="and|or">
		<if test="empName != null and empName !=''">
			emp_name = #{empName} and
		</if>
		<if test="age != null and age !=''">
			age = #{age} and
		</if>
		<if test="sex != null and sex !=''">
			sex = #{sex} or
		</if>
		<if test="email != null and email !=''">
			email = #{email}
		</if>
	</trim>
</select>

4.动态SQL之<choose><when><otherwise>

相当于switch... case... default...

<select id="getEmpByChoose" resultType="Emp">
	select * from t_emp
	<where>
		<choose>
			<when test="empName != null and empName != ''">
				emp_name = #{empName}
			</when>
			<when test="age != null and age != ''">
				age = #{age}
			</when>
			<when test="sex != null and sex != ''">
				sex = #{sex}
			</when>
			<when test="email != null and email != ''">
				email = #{email}
			</when>
			<otherwise>
				did = 1
			</otherwise>
		</choose>
	</where>
</select>

5.动态 SQL 之<foreach>:

循环执行sql的拼接操作,例如:SELECT * FROM USER WHERE id IN (1,2,5)。

<select id="findByIds" parameterType="list" resultType="user">
select * from User
<where>
<foreach collection="array" open="id in(" close=")" item="id" separator=",">
#{id}
</foreach>
</where>
</select>

 测试代码片段如下:

foreach标签的属性含义如下

<foreach>标签用于遍历集合,它的属性:

• collection:代表要遍历的集合元素,注意编写时不要写#{}

• open:代表语句的开始部分

• close:代表结束部分

• item:代表遍历集合的每个元素,生成的变量名

• sperator:代表分隔符

 ★sql片段抽取:

Sql 中可将重复的 sql 提取出来,使用时用 include 引用即可,最终达到 sql 重用的目的

 三,MyBatis的增删改查操作

★MyBatis获取参数值的两种方式(重点)

        ${}   和   #{}

${}本质字符串拼接(会出现sql注入问题)

#{}本质占位符赋值(常用

1.mapper接口方法的参数为单个的字面量类型

        可以通过¥{} 和 #{} 以任意的名称获取参数值,但是需要注意 ¥{} 的单引号问题

2.mapper接口方法的参数为多个

        此时MyBatis会将这些参数放在一个map集合中,以两种方式进行存储

        a>以arg0,arg1...为键,以参数为值

        b>以param1,param2...为键,以参数为值

        因此只需要通过${} 和 #{} 以键的方式(MyBatis设置的键的名称)访问值即可,但是需要注意${} 的单引号问题

3.若mapper接口方法的参数有多个时,可以手动将这些参数放在一个map中存储

        只需通过#{} 和 ${} 以键的方式访问值(map集合的键是自己设置)即可,但是需要注意${}的单引号问题

4.mapper接口方法的参数是实体类(表单数据)的参数时

        只需通过#{} 和 ${} 以属性的方式访问属性值即可,但是需要注意 ${}的单引号问题

5.使用@Param命名参数(改善第二种)

        此时MyBatis会将这些参数放在一个map集合中,以两种方式进行存储

        a>以@Param注解的值为键,以参数为值

        b>以@Param1,@Param2...为键,以参数为值

        因此值需要通过 #{} 和 ${} 以键的方式(注解的值)访问值即可,但是需要注意 ${} 的单引号问题

模糊查询:

在模糊查询中,例如select * from tb_user where username like ...

①当使用#{} 时,like '%#{username}%'就会报错,因为‘%?%’的 ?占位符不能实现作用

        故当使用#{}时 应该使用“%”#{username}“%”来进行拼接(常用

②当使用${}时,like '%${username}%'则可以实现模糊查询

批量删除:

实际应用中多使用动态<foreach>语句

在批量删除中,例如delete from t_user where id in (${ids})

①当使用#{} 时,就无法进行批量删除,因为#{}会带上 ‘ ’ 单引号,导致语句有误

②所以我们应该使用${}来进行批量删除

除此之外,动态设置表名也需要使用 #{ }

1,MyBatis的插入数据操作

1)编写UserMapper映射文件

<mapper namespace="userMapper">
<insert id="add" parameterType="com.itheima.domain.User">
insert into user values(#{id},#{username},#{password})
</insert>
</mapper>

MyBatis获取插入功能自增的主键:

 在mapper映射文件中添加属性

<mapper namespace="userMapper">
<insert id="add" useGeneratedKeys="true" keyProperty="id">
insert into user values(null,#{username},#{password})
</insert>
</mapper>

 useGeneratedKeys:设置当前标签的sql使用了自增的主键

 keyProperty:将自增的主键的值赋值给传输到映射文件中参数的某个属性

eg:

上述方法为void add(User user),则添加操作时不需要知道/添加user的id值,自行将其id自增并赋值到此user对象中。

2) 编写插入实体User的代码

InputStream resourceAsStream = Resources.getResourceAsStream("SqlMapConfig.xml");
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(resourceAsStream);
SqlSession sqlSession = sqlSessionFactory.openSession();
int insert = sqlSession.insert("userMapper.add", user);
System.out.println(insert);
//提交事务
sqlSession.commit();
sqlSession.close();

3) 插入操作注意问题

• 插入语句使用insert标签

• 在映射文件中使用parameterType属性指定要插入的数据类型

• Sql语句中使用#{实体属性名}方式引用实体中的属性值

• 插入操作使用的API是sqlSession.insert(“命名空间.id”,实体对象);

• 插入操作涉及数据库数据变化,所以要使用sqlSession对象显示的提交事务, 即sqlSession.commit()

2.MyBatis的修改数据操作

1)编写UserMapper映射文件

<mapper namespace="userMapper">
<update id="update" parameterType="com.itheima.domain.User">
update user set username=#{username},password=#{password} where id=#{id}
</update>
</mapper>

2)编写修改实体User的代码

InputStream resourceAsStream = Resources.getResourceAsStream("SqlMapConfig.xml");
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(resourceAsStream);
SqlSession sqlSession = sqlSessionFactory.openSession();
int update = sqlSession.update("userMapper.update", user);
System.out.println(update);
sqlSession.commit();
sqlSession.close()

3)修改操作注意问题

• 修改语句使用update标签

• 修改操作使用的API是sqlSession.update(“命名空间.id”,实体对象);

3.MyBatis的删除数据操作

1)编写UserMapper映射文件

<mapper namespace="userMapper">
<delete id="delete" parameterType="java.lang.Integer">
delete from user where id=#{id}
</delete>
</mapper>

2)编写删除数据的代码

InputStream resourceAsStream = Resources.getResourceAsStream("SqlMapConfig.xml");
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(resourceAsStream);
SqlSession sqlSession = sqlSessionFactory.openSession();
int delete = sqlSession.delete("userMapper.delete",3);
System.out.println(delete);
sqlSession.commit();
sqlSession.close();

3) 删除操作注意问题

• 删除语句使用delete标签

• Sql语句中使用#{任意字符串}方式引用传递的单个参数

• 删除操作使用的API是sqlSession.delete(“命名空间.id”,Object);

4.Mybatis中的查询功能:

4.MyBatis的查询数据操作

MyBatis的各种查询功能

1.若查询出的数据只有一条

        a>可以通过实体类对象接收

        b>可以通过list集合接收

        c>可以通过map集合接收

结果:{password=123456,sex=男,id=3,age=23}的形式

2.若查询出的数据有多条

        a>可以通过list集合接收

        b>可以在mapper接口的方法上添加@MapKey注解,此时就可以将每条数据转换的map集合作为值以某个字段的值(需要有唯一性的字段)作为键,放在同一个map集合中

例如:使用id作为字段(@MapKey(“id”))

        则查询结果为{3={name=李四,sex=男,id=3},4={name=王五,sex=女,id=4}}

        注意:一定不能通过实体类对象接收,此时会抛异常TooManyResultsException

注意:

查询功能的标签必须设置resultType 或resultMap

ResultMap的使用:

当字段名和属性名不一致时,就需要使用ResultMap来处理

eg:

 type:设置映射关系中的实体类类型

子标签:

        id:设置主键的元素关系

        result:设置普通字段的映射关系

属性:

        property:设置映射关系中的属性名,必须是type属性所设置的实体类类型中的属性名

        column:设置映射关系中的字段名,必须是sql语句查询出的字段名

四,. MyBatis核心配置文件 

1.MyBatis核心配置文件层级关系:

 2.MyBatis常用配置解析:

注意:

mybatis核心配置文件中,标签的顺序

 先后顺序如下:

properties?,settings?,typeAliases?,typeHandlers?,
objectFactory?,objectWrapperFactory?,reflectorFactory?,
plugins?,environments?,databaseIdProvider?,mappers?

1)environments标签

数据库环境的配置,支持多环境配置

其中,事务管理器(transactionManager)类型有两种

• JDBC:这个配置就是直接使用了JDBC 的提交和回滚设置,它依赖于从数据源得到的连接来管理事务作用域。

• MANAGED:这个配置几乎没做什么。它从来不提交或回滚一个连接,而是让容器来管理事务的整个生命周期(比如JEE 应用服务器的上下文)。 默认情况下它会关闭连接,然而一些容器并不希望这样,因此需要将 closeConnection 属性设置 为 false 来阻止它默认的关闭行为。

其中,数据源(dataSource)类型有三种

• UNPOOLED:这个数据源的实现只是每次被请求时打开和关闭连接。

• POOLED:这种数据源的实现利用“池”的概念将 JDBC 连接对象组织起来。

• JNDI:这个数据源的实现是为了能在如 EJB 或应用服务器这类容器中使用,容器可以集中或在外部配置数据源,然后放置 一个 JNDI 上下文的引用。 

2)mapper标签

该标签的作用是加载映射的,加载方式有如下几种:

• 使用相对于类路径的资源引用,例如:

<mapper resource="org/mybatis/builder/AuthorMapper.xml"/>

• 使用完全限定资源定位符(URL),例如:

<mapper url="file:///var/mappers/AuthorMapper.xml"/>

• 使用映射器接口实现类的完全限定类名,例如:

<mapper class="org.mybatis.builder.AuthorMapper"/>

• 将包内的映射器接口实现全部注册为映射器,例如常用

要求:

1.mapper接口所在的包要和映射文件所在的包一致

2.mapper接口要和映射文件的名字一致

<package name="org.mybatis.builder"/>

★mapper以及mapper配置文件的目录:

 resources下的mapper包应该与mapper接口的包一样

故目录需要如下设置:

注意:

创建resources下的包,需要用 而不是用 .

3)Properties标签

 4)typeAliases标签★

常使用<Package>来以包为单位,将包下的所有类型设置默认的类型别名,即类名不区分大小写

eg:

 5)typeHandlers标签

public class MyDateTypeHandler extends BaseTypeHandler<Date> {
public void setNonNullParameter(PreparedStatement preparedStatement, int i, Date date, JdbcType type) 
{
preparedStatement.setString(i,date.getTime()+"");
}
public Date getNullableResult(ResultSet resultSet, String s) throws SQLException {
return new Date(resultSet.getLong(s));
}
public Date getNullableResult(ResultSet resultSet, int i) throws SQLException {
return new Date(resultSet.getLong(i));
}
public Date getNullableResult(CallableStatement callableStatement, int i) throws SQLException {
return callableStatement.getDate(i);
}
}
<!--注册类型自定义转换器-->
<typeHandlers>
<typeHandler handler="com.itheima.typeHandlers.MyDateTypeHandler"></typeHandler>
</typeHandlers>

 6)plugins标签

① 导入通用PageHelper坐标

<!-- 分页助手 -->
<dependency>
<groupId>com.github.pagehelper</groupId>
<artifactId>pagehelper</artifactId>
<version>3.7.5</version>
</dependency>
<dependency>
<groupId>com.github.jsqlparser</groupId>
<artifactId>jsqlparser</artifactId>
<version>0.9.1</version>
</dependency>

② 在mybatis核心配置文件中配置PageHelper插件

<!-- 注意:分页助手的插件 配置在通用馆mapper之前 -->
<plugin interceptor="com.github.pagehelper.PageHelper">
<!-- 指定方言 -->
<property name="dialect" value="mysql"/>
</plugin>

③ 测试分页代码实现

@Test
public void testPageHelper(){
//设置分页参数
PageHelper.startPage(1,2);
List<User> select = userMapper2.select(null);
for(User user : select){
System.out.println(user);
}
}

▲获得分页相关的其他参数:

五,MyBatis相应API 

1,SqlSession工厂对象SqlSessionFactory

 2.SqlSession会话对象

 六,.使用Mybatis的Dao层实现

1,传统开发方式:

1)编写UserDao接口

2). 编写UserDaoImpl实现

 3). 测试传统方式

 2.代理开发方式(重点)

🔺代理开发方式介绍:     

 1) 编写UserMapper接口

 2)测试代理方式

七,Mybatis多表查询

1.多对一查询:

多对一时:

                创建对一对应的对象,如下图中的private User user

 1)创建Order和User实体

        需要创建对应的get,set方法,并重写toString方法 ,构造器不需要重写 

 2)创建OrderMapper接口

3)配置OrderMapper.xml

<mapper namespace="com.itheima.mapper.OrderMapper">
<resultMap id="orderMap" type="com.itheima.domain.Order">
<result column="uid" property="user.id"></result>
<result column="username" property="user.username"></result>
<result column="password" property="user.password"></result>
<result column="birthday" property="user.birthday"></result>
</resultMap>
<select id="findAll" resultMap="orderMap">
select * from orders o,user u where o.uid=u.id
</select>
</mapper>

 其中还可以配置如下(常用):

javaType:该类型的属性

<resultMap id="orderMap" type="Order">
<result property="id" column="id"></result>
<result property="ordertime" column="ordertime"></result>
<result property="total" column="total"></result>
<association property="user" javaType="User">
<result column="uid" property="id"></result>
<result column="username" property="username"></result>
<result column="password" property="password"></result>
<result column="birthday" property="birthday"></result>
</association>
</resultMap>

 4)测试结果

★多对一分步查询: 

1. 查询员工信息

  • select:设置分布查询的sql的唯一标识(namespace.SQLId或mapper接口的全类名.方法名)

  • column:设置分步查询的条件

//EmpMapper里的方法
/**
 * 通过分步查询,员工及所对应的部门信息
 * 分步查询第一步:查询员工信息
 * @param  
 * @return com.atguigu.mybatis.pojo.Emp
 * @date 2022/2/27 20:17
 */
Emp getEmpAndDeptByStepOne(@Param("eid") Integer eid);

<resultMap id="empAndDeptByStepResultMap" type="Emp">
	<id property="eid" column="eid"></id>
	<result property="empName" column="emp_name"></result>
	<result property="age" column="age"></result>
	<result property="sex" column="sex"></result>
	<result property="email" column="email"></result>
	<association property="dept"
				 select="com.atguigu.mybatis.mapper.DeptMapper.getEmpAndDeptByStepTwo"
				 column="did"></association>
</resultMap>
<!--Emp getEmpAndDeptByStepOne(@Param("eid") Integer eid);-->
<select id="getEmpAndDeptByStepOne" resultMap="empAndDeptByStepResultMap">
	select * from t_emp where eid = #{eid}
</select>

2. 查询部门信息

//DeptMapper里的方法
/**
 * 通过分步查询,员工及所对应的部门信息
 * 分步查询第二步:通过did查询员工对应的部门信息
 * @param
 * @return com.atguigu.mybatis.pojo.Emp
 * @date 2022/2/27 20:23
 */
Dept getEmpAndDeptByStepTwo(@Param("did") Integer did);
<!--此处的resultMap仅是处理字段和属性的映射关系-->
<resultMap id="EmpAndDeptByStepTwoResultMap" type="Dept">
	<id property="did" column="did"></id>
	<result property="deptName" column="dept_name"></result>
</resultMap>
<!--Dept getEmpAndDeptByStepTwo(@Param("did") Integer did);-->
<select id="getEmpAndDeptByStepTwo" resultMap="EmpAndDeptByStepTwoResultMap">
	select * from t_dept where did = #{did}
</select>

 2.一对多查询:

一对多时:

                创建对一对应的对象,如下图中的private User user

                创建对多的集合,如下图中的private List<Order> orderList

                 对一对应对象,对多对应集合

 1)修改User实体

        需要创建对应的get,set方法,并重写toString方法 ,构造器不需要重写

 2)创建UserMapper接口

3)配置UserMapper.xml

        ofType:集合中的类型

<mapper namespace="com.itheima.mapper.UserMapper">
<resultMap id="userMap" type="User">
<result column="id" property="id"></result>
<result column="username" property="username"></result>
<result column="password" property="password"></result>
<result column="birthday" property="birthday"></result>
<collection property="orderList" ofType="Order">
<result column="oid" property="id"></result>
<result column="ordertime" property="ordertime"></result>
<result column="total" property="total"></result>
</collection>
</resultMap>
<select id="findAll" resultMap="userMap">
select *,o.id oid from user u left join orders o on u.id=o.uid
</select>
</mapper>

 4)测试结果

★分步查询

1.查询部门信息

/**
 * 通过分步查询,查询部门及对应的所有员工信息
 * 分步查询第一步:查询部门信息
 * @param did 
 * @return com.atguigu.mybatis.pojo.Dept
 * @date 2022/2/27 22:04
 */
Dept getDeptAndEmpByStepOne(@Param("did") Integer did);
<resultMap id="DeptAndEmpByStepOneResultMap" type="Dept">
	<id property="did" column="did"></id>
	<result property="deptName" column="dept_name"></result>
	<collection property="emps"
				select="com.atguigu.mybatis.mapper.EmpMapper.getDeptAndEmpByStepTwo"
				column="did"></collection>
</resultMap>
<!--Dept getDeptAndEmpByStepOne(@Param("did") Integer did);-->
<select id="getDeptAndEmpByStepOne" resultMap="DeptAndEmpByStepOneResultMap">
	select * from t_dept where did = #{did}
</select>

 2.根据部门id查询部门中的所有员工

/**
 * 通过分步查询,查询部门及对应的所有员工信息
 * 分步查询第二步:根据部门id查询部门中的所有员工
 * @param did
 * @return java.util.List<com.atguigu.mybatis.pojo.Emp>
 * @date 2022/2/27 22:10
 */
List<Emp> getDeptAndEmpByStepTwo(@Param("did") Integer did);
<!--List<Emp> getDeptAndEmpByStepTwo(@Param("did") Integer did);-->
<select id="getDeptAndEmpByStepTwo" resultType="Emp">
	select * from t_emp where did = #{did}
</select>

 3.多对多查询:

 1)创建Role实体,修改User实体

2)添加UserMapper接口方法

 3)配置UserMapper.xml

<resultMap id="userRoleMap" type="com.itheima.domain.User">
<result column="id" property="id"></result>
<result column="username" property="username"></result>
<result column="password" property="password"></result>
<result column="birthday" property="birthday"></result>
<collection property="roleList" ofType="com.itheima.domain.Role">
<result column="rid" property="id"></result>
<result column="rolename" property="rolename"></result>
</collection>
</resultMap>
<select id="findAllUserAndRole" resultMap="userRoleMap">
select u.*,r.*,r.id rid from user u left join user_role ur on 
u.id=ur.user_id
inner join role r on ur.role_id=r.id
</select>

 4)测试结果

八,Mybatis的注解开发 

1.MyBatis的常用注解

@Insert:实现新增

@Update:实现更新

@Delete:实现删除

@Select:实现查询

@Result:实现结果集封装

@Results:可以与

@Result 一起使用,封装多个结果集

@One:实现一对一结果集封装

@Many:实现一对多结果集封装

2.MyBatis的增删改查

 

★重点配置

 3.MyBatis的注解实现复杂映射开发

 1)一对一查询:

 2)一对多查询:

 3)多对多查询:

九,MyBatis的缓存

1.MyBatis的一级缓存:

默认开启,作用域小,仅仅存在于sqlsession域当中,下次查询同样的数据时,就会直接从缓存中直接获取,不需要从数据库重新访问

1)需要是同一个sqlsession

2)需要查询条件相同

3)两次查询期间执行了任意增删改的操作则不行

4)期间手动清空了缓存则不行

2.MyBatis的二级缓存:

二级缓存是SqlSessionFactory级别的

开启条件:

1)在核心配置文件中,设置全局配置属性cacheEnable="true",默认为true,不需要设置

2)在映射文件中设置标签<cache/>

3)二级缓存必须在SqlSession关闭或提交之后有效

4)查询的数据所转换的实体类类型必须实现序列化的接口

使二级缓存失效的情况:

两次查询之间执行了任意的增删改,会使一级和二级缓存都失效。

十,MyBatis的逆向工程:

1.概念理解:

        正向工程:先创建java实体类,由框架负责根据实体类生成数据表

        逆向工程:先创建数据库表,由框架负责根据数据库表,反向生成如下资源:

  • Java实体类
  • Mapper接口
  • Mapper映射文件

2.具体实现步骤

1)pom.xml的配置

<!-- 控制Maven在构建过程中相关配置 -->
<build>
	<!-- 构建过程中用到的插件 -->
	<plugins>
		<!-- 具体插件,逆向工程的操作是以构建过程中插件形式出现的 -->
		<plugin>
			<groupId>org.mybatis.generator</groupId>
			<artifactId>mybatis-generator-maven-plugin</artifactId>
			<version>1.3.0</version>
			<!-- 插件的依赖 -->
			<dependencies>
				<!-- 逆向工程的核心依赖 -->
				<dependency>
					<groupId>org.mybatis.generator</groupId>
					<artifactId>mybatis-generator-core</artifactId>
					<version>1.3.2</version>
				</dependency>
				<!-- 数据库连接池 -->
				<dependency>
					<groupId>com.mchange</groupId>
					<artifactId>c3p0</artifactId>
					<version>0.9.2</version>
				</dependency>
				<!-- MySQL驱动 -->
				<dependency>
					<groupId>mysql</groupId>
					<artifactId>mysql-connector-java</artifactId>
					<version>8.0.27</version>
				</dependency>
			</dependencies>
		</plugin>
	</plugins>
</build>

2)创建MyBatis的核心配置文件

<?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>
    <properties resource="jdbc.properties"/>
    <typeAliases>
        <package name=""/>
    </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>
    <mappers>
        <package name=""/>
    </mappers>
</configuration>

3)创建逆向工程的配置文件

  • 文件名必须是:generatorConfig.xml

<?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="MyBatis3Simple">
        <!-- 数据库的连接信息 -->
        <jdbcConnection driverClass="com.mysql.cj.jdbc.Driver"
                        connectionURL="jdbc:mysql://localhost:3306/mybatis?useSSL=false&amp;serverTimezone=UTC"
                        userId="root"
                        password="111111">
        </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.MyBatis3中的QBC风格

查询

  • selectByExample:按条件查询,需要传入一个example对象或者null;如果传入一个null,则表示没有条件,也就是查询所有数据

  • example.createCriteria().xxx:创建条件对象,通过andXXX方法为SQL添加查询添加,每个条件之间是and关系

  • example.or().xxx:将之前添加的条件通过or拼接其他条件

@Test public void testMBG() throws IOException {
	InputStream is = Resources.getResourceAsStream("mybatis-config.xml");
	SqlSessionFactoryBuilder sqlSessionFactoryBuilder = new SqlSessionFactoryBuilder();
	SqlSessionFactory sqlSessionFactory = sqlSessionFactoryBuilder.build(is);
	SqlSession sqlSession = sqlSessionFactory.openSession(true);
	EmpMapper mapper = sqlSession.getMapper(EmpMapper.class);
    //创建对象
	EmpExample example = new EmpExample();
	//名字为张三,且年龄大于等于20
	example.createCriteria().andEmpNameEqualTo("张三").andAgeGreaterThanOrEqualTo(20);
	//或者did不为空
	example.or().andDidIsNotNull();
	List<Emp> emps = mapper.selectByExample(example);
	emps.forEach(System.out::println);
}

 增改

  • updateByPrimaryKey:通过主键进行数据修改,如果某一个值为null,也会将对应的字段改为null

  • mapper.updateByPrimaryKey(new Emp(1,"admin",22,null,"456@qq.com",3))

  • updateByPrimaryKeySelective():通过主键进行选择性数据修改,如果某个值为null,则不修改这个字段

  • mapper.updateByPrimaryKeySelective(new Emp(2,"admin2",22,null,"456@qq.com",3));

十一,分页插件 

1.分页插件的使用步骤

1)添加依赖

<!-- https://mvnrepository.com/artifact/com.github.pagehelper/pagehelper -->
<dependency>
	<groupId>com.github.pagehelper</groupId>
	<artifactId>pagehelper</artifactId>
	<version>5.2.0</version>
</dependency>

2)配置分页插件

  • 在MyBatis的核心配置文件(mybatis-config.xml)中配置插件

<plugins>
	<!--设置分页插件-->
	<plugin interceptor="com.github.pagehelper.PageInterceptor"></plugin>
</plugins>

 2.分页插件的使用

1)开启分页功能

  • 在查询功能之前使用PageHelper.startPage(int pageNum, int pageSize)开启分页功能

  • pageNum:当前页的页码

    • pageSize:每页显示的条数

@Test
public void testPageHelper() throws IOException {
    InputStream is = Resources.getResourceAsStream("mybatis-config.xml");
    SqlSessionFactoryBuilder sqlSessionFactoryBuilder = new SqlSessionFactoryBuilder();
    SqlSessionFactory sqlSessionFactory = sqlSessionFactoryBuilder.build(is);
    SqlSession sqlSession = sqlSessionFactory.openSession(true);
    EmpMapper mapper = sqlSession.getMapper(EmpMapper.class);
    //访问第一页,每页四条数据
    PageHelper.startPage(1,4);
    List<Emp> emps = mapper.selectByExample(null);
    emps.forEach(System.out::println);
}

2)分页相关数据

方法一:直接输出

@Test
public void testPageHelper() throws IOException {
    InputStream is = Resources.getResourceAsStream("mybatis-config.xml");
    SqlSessionFactoryBuilder sqlSessionFactoryBuilder = new SqlSessionFactoryBuilder();
    SqlSessionFactory sqlSessionFactory = sqlSessionFactoryBuilder.build(is);
    SqlSession sqlSession = sqlSessionFactory.openSession(true);
    EmpMapper mapper = sqlSession.getMapper(EmpMapper.class);
    //访问第一页,每页四条数据
    Page<Object> page = PageHelper.startPage(1, 4);
    List<Emp> emps = mapper.selectByExample(null);
    //在查询到List集合后,打印分页数据
    System.out.println(page);
}
  • 分页相关数据:

```
Page{count=true, pageNum=1, pageSize=4, startRow=0, endRow=4, total=8, pages=2, reasonable=false, pageSizeZero=false}[Emp{eid=1, empName='admin', age=22, sex='男', email='456@qq.com', did=3}, Emp{eid=2, empName='admin2', age=22, sex='男', email='456@qq.com', did=3}, Emp{eid=3, empName='王五', age=12, sex='女', email='123@qq.com', did=3}, Emp{eid=4, empName='赵六', age=32, sex='男', email='123@qq.com', did=1}]
```

方法二:使用PageInfo

  • 在查询获取list集合之后,使用PageInfo<T> pageInfo = new PageInfo<>(List<T> list, intnavigatePages)获取分页相关数据

  • list:分页之后的数据

    • navigatePages:导航分页的页码数

@Test
public void testPageHelper() throws IOException {
    InputStream is = Resources.getResourceAsStream("mybatis-config.xml");
    SqlSessionFactoryBuilder sqlSessionFactoryBuilder = new SqlSessionFactoryBuilder();
    SqlSessionFactory sqlSessionFactory = sqlSessionFactoryBuilder.build(is);
    SqlSession sqlSession = sqlSessionFactory.openSession(true);
    EmpMapper mapper = sqlSession.getMapper(EmpMapper.class);
    PageHelper.startPage(1, 4);
    List<Emp> emps = mapper.selectByExample(null);
    PageInfo<Emp> page = new PageInfo<>(emps,5);
    System.out.println(page);
}
  • 分页相关数据:

```
PageInfo{
pageNum=1, pageSize=4, size=4, startRow=1, endRow=4, total=8, pages=2, 
list=Page{count=true, pageNum=1, pageSize=4, startRow=0, endRow=4, total=8, pages=2, reasonable=false, pageSizeZero=false}[Emp{eid=1, empName='admin', age=22, sex='男', email='456@qq.com', did=3}, Emp{eid=2, empName='admin2', age=22, sex='男', email='456@qq.com', did=3}, Emp{eid=3, empName='王五', age=12, sex='女', email='123@qq.com', did=3}, Emp{eid=4, empName='赵六', age=32, sex='男', email='123@qq.com', did=1}], 
prePage=0, nextPage=2, isFirstPage=true, isLastPage=false, hasPreviousPage=false, hasNextPage=true, navigatePages=5, navigateFirstPage=1, navigateLastPage=2, navigatepageNums=[1, 2]}
```
  • 其中list中的数据等同于方法一中直接输出的page数据

常用数据:

  • pageNum:当前页的页码

  • pageSize:每页显示的条数

  • size:当前页显示的真实条数

  • total:总记录数

  • pages:总页数

  • prePage:上一页的页码

  • nextPage:下一页的页码

  • isFirstPage/isLastPage:是否为第一页/最后一页

  • hasPreviousPage/hasNextPage:是否存在上一页/下一页

  • navigatePages:导航分页的页码数

  • navigatepageNums:导航分页的页码,[1,2,3,4,5]

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值