2021-08-22

9、Lombok

  • Lombok 项目是一个 java 库,可自动插入编辑器并构建工具,将 java 向上弹出。
    切勿再编写其他获取器或等于方法,用一个注释,您的类有一个功能齐全的建设者,自动记录变量,等等。

使用步骤

  1. 在IDEA中安装插件!

    在这里插入图片描述

  2. 在项目中导入lombok的jar包

    <dependency>
                <groupId>org.projectlombok</groupId>
                <artifactId>lombok</artifactId>
                <version>1.18.20</version>
            </dependency>
    
  3. 注解列表:

    @Getter and @Setter
    @FieldNameConstants
    @ToString
    @EqualsAndHashCode
    @AllArgsConstructor, @RequiredArgsConstructor and @NoArgsConstructor
    @Log, @Log4j, @Log4j2, @Slf4j, @XSlf4j, @CommonsLog, @JBossLog, @Flogger, @CustomLog
    @Data
    @Builder
    @SuperBuilder
    @Singular
    @Delegate
    @Value
    @Accessors
    @Wither
    @With
    @SneakyThrows
    @val
    @var
    experimental @var
    @UtilityClass
    Lombok config system
    Code inspections
    Refactoring actions (lombok and delombok)
    
  4. 重点掌握:

  • @Data 他会帮你生成get、set,equals,toString,hashCode等方法!!
    
  • @AllArgsConstructor 会帮你生成有参构造
    
  • @NoArgsConstructor 会帮你生成无参构造
    

基本上一个实体类,用这三个注解就够了,而且用了这个注解依然可以自己在手写定义其它的重载的方法!

在这里插入图片描述

10、多对一处理

多对一:

在这里插入图片描述

  • 多个学生,对应一个老师
  • 对于学生这边而言,叫做关联.. 多个学生,关联一个老师【多对一】
  • 对于老师而言,集合,一个老师,有很多学生 【一对多】

SQL:

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 `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);

测试环境搭建

  1. 导入lombok
  2. 新建实体类 Teacher Student
  3. 建立Mapper接口
  4. 建立Mapper.xml文件
  5. 在核心配置文件中绑定注册我们的Mapper接口或者文件
  6. 测试查询是否成功

按照查询嵌套处理

<!--
    思路: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
        是一个集合就用:collection
        我们这里是一个Teacher对象,因此用association
        -->
        <association property="teacher" column="tid" select="getTeachers" javaType="Teacher"/>
        <!--这里的 select="getTeachers" 要和下面select中的 id中的语句要一样,但你想取什么名子都行, -->
    </resultMap>
    <select id="getTeachers" resultType="Teacher">
        select * from teacher where id = #{id}
    </select>

测试结果:

在这里插入图片描述

按照结果嵌套处理

    <select id="getStudent2" resultMap="getST">
        select student.id,student.name,teacher.name as tname from student,teacher where student.tid=teacher.id
    </select>
    <resultMap id="getST" type="Student">
        <result property="id" column="id"/>
        <result property="name" column="name"/>
        <association property="teacher" javaType="Teacher">
            <result property="name" column="tname"/>
        </association>
    </resultMap>

测试结果

在这里插入图片描述

多对一就是:

  • 子查询
  • 联表查询

11、一对多处理

比如:一个老师拥有多个学生!

对于老师而言,就是一对多的关系!

环境搭建

数据库和刚才一样

实体类

public class Student {
    private int id;
    private String name;
    private int tid;
}
public class Teacher {
    private int id;
    private String name;
    private List<Student> students;
}

按照结果嵌套处理

  • 尽量使用这种情况,因为这种情况出错还可以调试sql语句
<select id="getTeacher" resultMap="teacher_student" parameterType="_int">
        select teacher.id as tid,teacher.name as tname,student.id as sid,student.name as sname
        from student ,teacher
        where student.tid=teacher.id and teacher.id=#{tid}
    </select>
    <resultMap id="teacher_student" type="Teacher" >
        <result property="id" column="tid"/>
        <result property="name" column="tname"/>
        <!--这里的集合是List集合,属性的类型是集合中的泛型为student类型
        集合中的泛型信息,我们使用ofType获取
        -->
        <collection property="students" ofType="Student" >
            <result property="id" column="sid"/>
            <result property="name" column="sname"/>
            <result property="tid" column="tid"/>
        </collection>
    </resultMap>

测试结果:

在这里插入图片描述

按照查询嵌套处理

  • 这种方式sql语句简单,但出错不好调试
<select id="getTeacher2" resultMap="ts" parameterType="_int">
        select * from teacher where id = #{teacher_id}
    </select>
    <resultMap id="ts" type="Teacher">
        <result property="id" column="id"/>
        <result property="name" column="name"/>
        <collection property="students" ofType="Student" javaType="ArrayList" select="getStudent" column="id"/>
    </resultMap>
    <select id="getStudent" resultType="Student">
        select * from student where tid =#{123456}
    </select>

测试结果

在这里插入图片描述

小结

  1. 关联 - association 【多对一】
  2. 集合 - collection 【一对多】
  3. javaType & ofType
    1. javaType 用来指定实体类中属性的类型
    2. ofType 用来指定映射到List或者集合中的pojo类型,泛型中的约束类型!

注意点:

  • 保证sql的可读性,尽量保证通俗易懂
  • 注意一对多和多对一中,属性名的字段的问题!
  • 如果问题不好排查错误,可以使用日志,建议使用Log4j

面试高频

  • MySQL引擎
  • InnoDB的底层原理
  • 索引
  • 索引优化!

12、动态SQL

  • 什么是动态SQL:动态SQL就是指根据不同的条件生成不同的SQL语句
  • 利用动态SQL这一特性可以彻底摆脱拼接SQL语句的痛苦

如果你之前用过 JSTL 或任何基于类 XML 语言的文本处理器,你对动态 SQL 元素可能会感觉似曾相识。在 MyBatis 之前的版本中,需要花时间了解大量的元素。借助功能强大的基于 OGNL 的表达式,MyBatis 3 替换了之前的大部分元素,大大精简了元素种类,现在要学习的元素种类比原来的一半还要少。

  • if
  • choose (when, otherwise)
  • trim (where, set)
  • foreach

搭建环境

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

创建一个基础工程

  1. 导包

  2. 编写配置文件

  3. 编写实体类

    package com.feng.pojo;
    
    import lombok.AllArgsConstructor;
    import lombok.Data;
    import lombok.NoArgsConstructor;
    
    import java.util.Date;
    
    @Data
    @AllArgsConstructor
    @NoArgsConstructor
    public class Blog {
        private int id;
        private String title;
        private String author;
        private Date createTime;//属性名跟字段不一致
        private int views;
    
    }
    

    在Mybatis中开启驼峰命名规则:

    < setting name="mapUnderscoreToCamelCase" value="true"/>
    
  4. 编写实体类对应Mapper接口和Mapper.XML文件

IF

  <select id="getBlogIf" parameterType="map" resultType="Blog">
        select * from blog where 1=1
        <if test="title !=null">
            and title=#{title}
        </if>
        <if test="author !=null">
            and author=#{author}
        </if>
    </select>
  • 上面这个where这里有问题 假如没有 1=1 会怎样

  • 在这里插入图片描述

  • 假设用了where语句,第一句没有匹配上,直接匹配的第二句,那么where语句会自动帮你将and去掉

修改上面的SQL语句

  <select id="getBlogIf" parameterType="map" resultType="Blog">
        select * from blog
        <where>
        <if test="title !=null">
             title=#{title}
        </if>
        <if test="author !=null">
            and author=#{author}
        </if>
        </where>
    </select>

测试类

//IF查询
    @Test
    public void textIf(){
        SqlSession sqlSession = MybatisUtils.getSqlSession();
        BlogMapper mapper = sqlSession.getMapper(BlogMapper.class);
        Map map = new HashMap<>();
        //map.put("title","编程改变人生");
        map.put("author","小明");
        List<Blog> blogIf = mapper.getBlogIf(map);
        for (Blog blog : blogIf) {
            System.out.println(blog);
        }
        sqlSession.close();
    }

choose (when, otherwise)

  • choose中只会有一个语句的到满足,即选择一个sql语句拼接,而if是判断拼接的条件
  <select id="getBlogChoose" parameterType="map" resultType="Blog">
        select * from blog
        <where>
            <choose>
                <when test="title!=null">
                    title=#{title}
                </when>

                <when test="author!=null">
                    and author=#{author}
                </when>
                <otherwise>
                    and views=#{views}
                </otherwise>

            </choose>
        </where>
    </select>

测试

  //Choose查询
    @Test
    public void textChoose(){
        SqlSession sqlSession = MybatisUtils.getSqlSession();
        BlogMapper mapper = sqlSession.getMapper(BlogMapper.class);
        Map map = new HashMap<>();
        map.put("title","编程改变人生");//这里直接就选择choose中的第一个sql语句,也直接跳出了SQL语句
        map.put("author","小明");
        map.put("views",999);
        List<Blog> blogIf = mapper.getBlogChoose(map);
        for (Blog blog : blogIf) {
            System.out.println(blog);
        }
        sqlSession.close();
    }

trim (where, set)

where:

在这里插入图片描述

  <select id="getBlogIf" parameterType="map" resultType="Blog">
        select * from blog
        <where>
        <if test="title !=null">
             title=#{title}
        </if>
        <if test="author !=null">
            and author=#{author}
        </if>
        </where>
    </select>

set:

在这里插入图片描述

<update id="updateBlog" parameterType="map"  >
        update blog
        <set>
            <if test="title !=null">
                title = #{title},
            </if>
            <if test="author">
                author =#{author}
            </if>
        </set>
        where id =#{id}
    </update>
//update更新
    @Test
    public void textset(){
        SqlSession sqlSession = MybatisUtils.getSqlSession();
        BlogMapper mapper = sqlSession.getMapper(BlogMapper.class);
        Map map = new HashMap<>();
        map.put("title","编程改变人生2");
        //map.put("author","小明");
        //map.put("views",999);
        map.put("id","92ed752144e7491cacfa7e29fae4fc64");
        mapper.updateBlog(map);

        sqlSession.close();
    }

在这里插入图片描述

这里它自己去除了逗号。

所谓的动态SQL,本质还是SQL语句,只是我们可以在SQL层面,去执行逻辑代码

SQL片段

有的时候,我们可能会将一些功能的部分抽取出来,方便复用!

  1. 使用SQL标签抽取公共的部分

      <sql id="if-title">
         <if test="title !=null">
             title=#{title}
         </if>
         <if test="author !=null">
             and author=#{author}
         </if>
     </sql>
    
  2. 在需要使用的地方使用Include标签引用即可

    <select id="getBlogIf" parameterType="map" resultType="Blog">
            select * from blog
            <where>
            <include refid="if-title"></include>
            </where>
        </select>
    

注意事项:

  • 最好基于单表来定义SQL标签
  • 不要存在where标签
  • 一般只用一些if语句在里面

Foreach

select * from user where 1=1 and ( id=1 or id=2 or id=3  )

<foreach item="item" index="index" collection="list"
      open="(" separator="," close=")">
        #{item}
  </foreach>
-- 这个例子这样写 遍历id集合
<foreach item="id"  collection="ids"
      open="(" separator="or" close=")">
        #{id}
  </foreach>
  
  

在这里插入图片描述

<!--    select * from user where 1=1 and ( id=1 or id=2 or id=3  )-->
    <select id="getBlog" parameterType="map" resultType="Blog">
        select * from blog
        <where>
            <foreach collection="ids" item="id" open="(" close=")" separator="or">
                id =#{id}
            </foreach>

        </where>
    </select>

测试

 @Test
    public void getBlog(){
        SqlSession sqlSession = MybatisUtils.getSqlSession();
        BlogMapper mapper = sqlSession.getMapper(BlogMapper.class);
        Map map = new HashMap<>();
        //用一个集合来存放ids中的数据
        ArrayList list = new ArrayList<>();

        //list.add(1);
        //list.add(2);
        //不添加数据时,它是不会走where的,查询的是所有的结果
        map.put("ids",list);
        List<Blog> blog = mapper.getBlog(map);
        for (Blog blog1 : blog) {
            System.out.println(blog1);
        }
        sqlSession.close();
    }

动态SQL就是在拼接SQL语句,我们只要保证SQL的正确性,按照SQL的格式,去排列组合就可以了

建议:

  • 先在Mysql中写出完整的SQL语句在对应的去修改成为我们的动态SQL语句即可!
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值