Java面试题系列——JavaSE面试题(Mybatis二)

"本文详细介绍了Mybatis中的级联配置,包括两种不同的配置方式:通过resultMap进行配置以及利用association和collection。同时,讨论了一级缓存和二级缓存的工作原理,指出它们在减少数据库访问和提升性能上的作用。最后,提到了Mybatis防止SQL注入的机制,即使用#{}
摘要由CSDN通过智能技术生成

1、Mybatis级联的配置

级联(cascade)在计算机科学里指多个对象之间的映射关系,建立数据之间的级联关系提高管理效率。

第一种配置方式:(resultmap进行配置)

1.定义四个实体。User   Role    Privilege   Resource:

public class User implements Serializable {
private String id;
private String username;
private String password;

private Set<Role> role = new HashSet<Role>();

public class Role implements Serializable {
private String id;
private String name;
private String des;

private Set<Privilege> privilege = new HashSet<Privilege>();

public class Privilege implements Serializable {  private String id;  private String name;  private String des;

private Set<Resource> resource = new HashSet<Resource>();  private Privilege parent;  private Set<Privilege> child = new HashSet<Privilege>();

public class Resource implements Serializable {
private String id;
private String uri;
private String des;
}


2.需求:我通过用户名username查找出该用户对应的角色以及角色对应的权限和资源
 

3.UserMapper.xml的查询方法为
 

  <resultMap type="user" id="userResult">
<id column="id" property="id"/>
<result column="username" property="username"/>
<collection property="role" javaType="java.util.Set" resultMap="roleResult"/>
</resultMap>

<resultMap type="role" id="roleResult">
<id column="rid" property="id"/>
<result column="rname" property="name"/>
<result column="rdes" property="des"/>
<collection property="privilege" javaType="java.util.Set" resultMap="privilegeResult"/>
</resultMap>

<resultMap type="privilege" id="privilegeResult">
<id column="pid" property="id"/>
<result column="pname" property="name"/>
<collection property="resource" javaType="java.util.Set" resultMap="resourceResult"/>
</resultMap>

<resultMap type="resource" id="resourceResult">
<id column="resid" property="id"/>
<result column="resuri" property="uri"/>
</resultMap>

<select id="findUserByUserName" parameterType="string" resultMap="userResult">
  select u.id,u.username,r.id as rid,r.name as rname,r.des as rdes,p.id as pid,p.name as pname,res.id as resid,res.uri as resuri
  from tb_user u
  left join user_role ur on ur.user_id=u.id
  join tb_role r on r.id=ur.role_id
  join role_privilege rp on rp.role_id=r.id
  join tb_privilege p on p.id=rp.privilege_id
  join tb_resource res on res.privilege_id=p.id
  where u.username=#{username}
</select>

5.UserMapper.java定义方法
 

public interface UserMapper {

User findUserByUserName(@Param(value="username")String username);

}

第二种配置方式:(利用association,collection)

    <resultMap id="usersResult" type="com.zlwh.member.model.Users">
        <result property="id" column="id"/>
        <result property="loginName" column="login_name"/>
        <result property="userName" column="user_name"/>
        <result property="password" column="password"/>
        <result property="email" column="email"/>
        <result property="status" column="status"/>
        <result property="userType" column="user_type"/>
        <result property="memberType" column="member_type"/>
        <result property="imgPath" column="img_path"/>
        <result property="imgStatus" column="img_status"/>
        <result property="identification" column="identification"/>
        <result property="certificateCode" column="certificate_code"/>
        <result property="countyCode" column="county_code"/>
        <result property="schoolId" column="school_id"/>
        <result property="classId" column="class_id"/>
        <result property="grade" column="grade"/>
        <result property="sex" column="sex"/>
        <result property="birthday" column="birthday"/>
        <result property="mobile" column="mobile"/>
        <result property="inviteCode" column="invite_code"/>
        <result property="subjectId" column="subject_id"/>
        <result property="certificationStatus" column="Certification_status"/>
        <result property="createTime" column="create_time"/>
        <result property="validTime" column="valid_time"/>
        <result property="institutionId" column="institution_id"/>
        <result property="depName" column="dep_name"/>
        <result property="jobName" column="job_name"/>
        <association column="school_id" property="school"
        javaType="com.zlwh.member.model.School" select="getSchoolById" />
    </resultMap>
  
         <resultMap id="schoolResult" type="com.zlwh.member.model.School">
        <result property="id" column="id"/>
        <result property="schoolName" column="school_name"/>
        <result property="schoolCode" column="school_code"/>
        <result property="county" column="county"/>
        <result property="address" column="address"/>
        <result property="phase" column="phase"/>
    </resultMap>
      
    <select id="getSchoolById" resultMap="schoolResult">
        SELECT * FROM school WHERE id = #{id}
    </select>
  
    <resultMap id="usersResultForT" type="com.zlwh.member.model.Users">
        <result property="id" column="id"/>
        <result property="loginName" column="login_name"/>
        <result property="userName" column="user_name"/>
        <result property="inviteCode" column="invite_code"/>
        <collection property="userSubscriptions" column="id" select="getUserSubscriptionsByUserId" ></collection>
    </resultMap>
  

  
    <resultMap id="userSubscriptionResult" type="com.zlwh.member.model.UserSubscription">
        <result property="id" column="id"/>
        <result property="userId" column="user_id"/>
        <result property="subscriptionId" column="subscription_id"/>
        <result property="beginDate" column="begin_date"/>
        <result property="endDate" column="end_date"/>
        <result property="status" column="status"/>
        <result property="createTime" column="create_time"/>
        <result property="orderId" column="order_id"/>
        <result property="orderPrice" column="order_price"/>
        <result property="payTime" column="pay_time"/>   
    </resultMap>
  
    <select id="getStudentsByInviteCode" resultMap="usersResultForT">
        <![CDATA[SELECT id,login_name,user_name,invite_code FROM users    WHERE invite_code = #{inviteCode} and member_type=1]]>
    </select>



<select id="getById" resultMap="usersResult">
        SELECT <include refid="commonColumns" />
        <![CDATA[
            FROM users
            WHERE
                id = #{id}
        ]]>
    </select>

  
    <!-- 查所有已支付的订阅 -->
     <select id="getUserSubscriptionsByUserId" resultMap="userSubscriptionResult">
        SELECT * FROM user_subscription WHERE (status=1 or status=3) and user_id = #{userId} order by subscription_id asc
    </select>
  




    <!-- 用于select查询公用抽取的列 -->
    <sql id="commonColumns">
        <![CDATA[
            id ,
            login_name ,
            user_name ,
            password ,
            email ,
            status ,
            user_type ,
            member_type ,
            img_path ,
            img_status ,
            identification ,
            certificate_code ,
            county_code ,
            school_id ,
            class_id ,
            grade ,
            sex ,
            birthday ,
            mobile ,
            invite_code ,
            subject_id ,
            Certification_status ,
            create_time ,
            valid_time ,
            institution_id ,
            dep_name ,
            job_name
        ]]>
    </sql>

2、Mybatis的一二级缓存是什么样的?

缓存定义:缓存其实就是存储在内存中的临时数据,这里的数据量会比较小,一般来说,服务器的内存也是有限的,不可能将所有的数据都放到服务器的内存里面,所以, 只会把关键数据放到缓存中,缓存因为速度快,使用方便而出名!

mybatis一级缓存:

mybatis一级缓存是默认开启的,它在一个sqlSession会话里面的所有查询操作都会保存到缓存中,一般来说一个请求中的所有增删改查操作都是在同一个sqlSession里面的,所以我们可以认为每个请求都有自己的一级缓存,如果同一个sqlSession会话中2 个查询中间有一个 insert 、update或delete 语句,那么之前查询的所有缓存都会清空。

mybatis二级缓存:

二级缓存是mapper级别的,Mybatis默认是没有开启二级缓存的。 第一次调用mapper下的SQL去查询用户的信息,查询到的信息会存放代该mapper对应的二级缓存区域。 第二次调用namespace下的mapper映射文件中,相同的sql去查询用户信息,会去对应的二级缓存内取结果。

3、Mybits的缺点有哪些?

(1)、MyBatis框架的优点:
  1. 与JDBC相比,减少了50%以上的代码量。
  2. MyBatis是最简单的持久化框架,小巧并且简单易学。
  3. MyBatis灵活,不会对应用程序或者数据库的现有设计强加任何影响,SQL写在XML里,从程序代码中彻底分离,降低耦合度,便于统一管理和优化,可重用。
  4. 提供XML标签,支持编写动态SQL语句(XML中使用if, else)。
  5. 提供映射标签,支持对象与数据库的ORM字段关系映射(在XML中配置映射关系,也可以使用注解)。
(2)、MyBatis框架的缺点:
  1. SQL语句的编写工作量较大,尤其是字段多、关联表多时,更是如此,对开发人员编写SQL语句的功底有一定要求。
  2. SQL语句依赖于数据库,导致数据库移植性差,不能随意更换数据库。

4、Mybatis如何防止SQL注入?

MyBatis提供了两种支持动态 sql 的语法 #{} 和 ${},其中${} 是简单的字符串替换,而 #{} 在预处理时,会把参数部分用一个占位符 ? 代替,可以有效的防止sql的注入。

持续更新中,敬请期待!

参考文章:

https://www.iteye.com/blog/zhaoshijie-2102660

mybatis的级联和延迟加载配置_Leven.的博客-CSDN博客

mybatis学习之级联 - 简书

mybatis一级缓存和二级缓存的区别是什么-java教程-PHP中文网

mybatis 优缺点(优点和缺点) - 走看看

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

小海海不怕困难

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值