黑马javaWeb笔记重点备份2:mybatis基础(注解方式)、数据库连接池概念、lombok使用

news/2024/10/11 11:35:42/

以下均来自:【黑马程序员JavaWeb开发教程,实现javaweb企业开发全流程(涵盖Spring+MyBatis+SpringMVC+SpringBoot等)】 https://www.bilibili.com/video/BV1m84y1w7Tb/?p=75&share_source=copy_web&vd_source=9332b8fc5ea8d349a54c3989f6189fd3

mybatis_2">mybatis

Mybatis操作数据库

Mybatis操作数据库的步骤:

  1. 准备工作(创建springboot工程、数据库表user、实体类User)

  2. 引入Mybatis的相关依赖,配置Mybatis(数据库连接信息,注意数据库名字,密码,用户名要改成自己的)

  3. 编写SQL语句(注解/XML)

截图:

创建工程各选项设定
选择<a class=mybatis依赖" />

创建springboot工程,并导入 mybatis的起步依赖、mysql的驱动包。

<!-- 仅供参考:只粘贴了pom.xml中部分内容 主要是看哪部分是对应的什么内容,看注释-->
<dependencies><!-- mybatis起步依赖 --><dependency><groupId>org.mybatis.spring.boot</groupId><artifactId>mybatis-spring-boot-starter</artifactId><version>2.3.0</version></dependency><!-- mysql驱动包依赖 --><dependency><groupId>com.mysql</groupId><artifactId>mysql-connector-j</artifactId><scope>runtime</scope></dependency><!-- spring单元测试 (集成了junit) --><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-test</artifactId><scope>test</scope></dependency>
</dependencies>

编写mapper接口和SQL语句

在创建出来的springboot工程中,在引导类所在包下,在创建一个包 mapper。在mapper包下创建一个接口 UserMapper ,这是一个持久层接口(Mybatis的持久层接口规范一般都叫 XxxMapper)。

UserMapper:

import com.itheima.pojo.User;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Select;
import java.util.List;@Mapper  // 程序运行时:框架会自动生成接口的实现类对象(代理对象),并给交Spring的IOC容器管理
public interface UserMapper {//查询所有用户数据@Select("select id, name, age, gender, phone from user")public List<User> list();}

@Mapper注解:表示是mybatis中的Mapper接口

  • 程序运行时:框架会自动生成接口的实现类对象(代理对象),并给交Spring的IOC容器管理

@Select注解:代表的就是select查询,用于书写select查询语句

数据库连接池

数据库连接池是个容器,负责分配、管理数据库连接(Connection)

  • 程序在启动时,会在数据库连接池(容器)中,创建一定数量的Connection对象

允许应用程序重复使用一个现有的数据库连接,而不是再重新建立一个

  • 客户端在执行SQL时,先从连接池中获取一个Connection对象,然后在执行SQL语句,SQL语句执行完之后,释放Connection时就会把Connection对象归还给连接池(Connection对象可以复用)

释放空闲时间超过最大空闲时间的连接,来避免因为没有释放连接而引起的数据库连接遗漏

  • 客户端获取到Connection对象了,但是Connection对象并没有去访问数据库(处于空闲),数据库连接池发现Connection对象的空闲时间 > 连接池中预设的最大空闲时间,此时数据库连接池就会自动释放掉这个连接对象

数据库连接池的好处:

  1. 资源重用
  2. 提升系统响应速度
  3. 避免数据库连接遗漏

常见的数据库连接池

常见的数据库连接池:

  • Druid
  • Hikari (springboot默认)

现在使用更多的是:Hikari、Druid (性能更优越)

想把默认的数据库连接池切换为Druid数据库连接池,只需要完成以下两步操作即可:

参考官方地址:https://github.com/alibaba/druid/tree/master/druid-spring-boot-starter

  1. 在pom.xml文件中引入依赖
<dependency><!-- Druid连接池依赖 --><groupId>com.alibaba</groupId><artifactId>druid-spring-boot-starter</artifactId><version>1.2.8</version>
</dependency>
  1. 在application.properties中引入数据库连接配置

方式1:

spring.datasource.druid.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.druid.url=jdbc:mysql://localhost:3306/mybatis
spring.datasource.druid.username=root
spring.datasource.druid.password=1234

方式2:

//改成自己的名字,密码
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/mybatis
spring.datasource.username=root
spring.datasource.password=1234

注意:spring3要引入下面的依赖,多了个3

<dependency><groupId>com.alibaba</groupId><artifactId>druid-spring-boot-3-starter</artifactId><version>1.2.20</version>
</dependency>

lombok

lombok 介绍

Lombok是一个实用的Java类库,可以通过简单的注解来简化和消除一些必须有但显得很臃肿的Java代码。

通过注解的形式自动生成构造器、getter/setter、equals、hashcode、toString等方法,并可以自动化生成日志变量,简化java开发、提高效率。

注解作用
@Getter/@Setter为所有的属性提供get/set方法
@ToString会给类自动生成易阅读的 toString 方法
@EqualsAndHashCode根据类所拥有的非静态字段自动重写 equals 方法和 hashCode 方法
@Data提供了更综合的生成代码功能(@Getter + @Setter + @ToString + @EqualsAndHashCode)
@NoArgsConstructor为实体类生成无参的构造器方法
@AllArgsConstructor为实体类生成除了static修饰的字段之外带有各参数的构造器方法。

注意:@Data没有包含构造器

实战

删除功能

实现功能:根据主键删除数据,占位符 #{参数} 的使用

  • 接口方法
@Mapper
public interface EmpMapper {/*** 根据id删除数据* @param id    用户id*/@Delete("delete from emp where id = #{id}")//使用#{key}方式获取方法中的参数值public void delete(Integer id);}

@Delete注解:用于编写delete操作的SQL语句

如果mapper接口方法形参只有一个普通类型的参数,#{…} 里面的属性名可以随便写,如:#{id}、#{value}。但是建议保持名字一致。

插入功能

接口方法:

@Mapper
public interface EmpMapper {@Insert("insert into emp(username, name, gender, image, job, entrydate, dept_id, create_time, update_time) values (#{username}, #{name}, #{gender}, #{image}, #{job}, #{entrydate}, #{deptId}, #{createTime}, #{updateTime})")public void insert(Emp emp);}

说明:#{…} 里面写的名称是对象的属性名,不是数据库表的字段名

插入时返回主键

  • 默认情况下,执行插入操作时,是不会主键值返回的。如果我们想要拿到主键值,需要在Mapper接口中的方法上添加一个Options注解,并在注解中指定属性useGeneratedKeys=true和keyProperty=“实体类属性名”,会封装到对象的属性值上

主键返回代码实现:

@Mapper
public interface EmpMapper {//会自动将生成的主键值,赋值给emp对象的id属性@Options(useGeneratedKeys = true,keyProperty = "id")@Insert("insert into emp(username, name, gender, image, job, entrydate, dept_id, create_time, update_time) values (#{username}, #{name}, #{gender}, #{image}, #{job}, #{entrydate}, #{deptId}, #{createTime}, #{updateTime})")public void insert(Emp emp);}

mybatis_228">mybatis查询时的数据封装

我们看到查询返回的结果中大部分字段是有值的,但是deptId,createTime,updateTime这几个字段是没有值的,而数据库中 deptId=null, createTime=null, updateTime=null,这是为什么呢?
原因如下:

  • 实体类属性名和数据库表查询返回的字段名一致,mybatis会自动封装。
  • 如果实体类属性名和数据库表查询返回的字段名不一致,不能自动封装。

解决方案:

  1. 起别名
  2. 结果映射
  3. 开启驼峰命名

起别名:在SQL语句中,对不一样的列名起别名,别名和实体类属性名一样

@Select("select id, username, password, name, gender, image, job, entrydate, " +"dept_id AS deptId, create_time AS createTime, update_time AS updateTime " +"from emp " +"where id=#{id}")
public Emp getById(Integer id);

手动结果映射*:通过 @Results及@Result 进行手动结果映射

@Results({@Result(column = "dept_id", property = "deptId"),@Result(column = "create_time", property = "createTime"),@Result(column = "update_time", property = "updateTime")})
@Select("select id, username, password, name, gender, image, job, entrydate, dept_id, create_time, update_time from emp where id=#{id}")
public Emp getById(Integer id);

@Results源代码:

@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.METHOD})
public @interface Results {String id() default "";Result[] value() default {};  //Result类型的数组
}

开启驼峰命名(推荐):如果字段名与属性名符合驼峰命名规则,mybatis会自动通过驼峰命名规则映射

驼峰命名规则: abc_xyz => abcXyz

  • 表中字段名:abc_xyz
  • 类中属性名:abcXyz
# 在application.properties中添加:
mybatis.configuration.map-underscore-to-camel-case=true

要使用驼峰命名前提是 实体类的属性 与 数据库表中的字段名严格遵守驼峰命名。

模糊查询、concat拼接

下面的语句,like后的模糊查询,由于#{}不能放在引号里,所以换成了$进行字符串拼接,但有字符串注入风险

@Mapper
public interface EmpMapper {@Select("select * from emp " +"where name like '%${name}%' " +"and gender = #{gender} " +"and entrydate between #{begin} and #{end} " +"order by update_time desc")public List<Emp> list(String name, Short gender, LocalDate begin, LocalDate end);
}

以上方式注意事项:

  1. 方法中的形参名和SQL语句中的参数占位符名保持一致

  2. 模糊查询使用${…}进行字符串拼接,这种方式呢,由于是字符串拼接,并不是预编译的形式,所以效率不高、且存在sql注入风险。

  • 解决SQL注入风险的方法
    • 使用MySQL提供的字符串拼接函数:concat(‘%’ , ‘关键字’ , ‘%’)
@Mapper
public interface EmpMapper {@Select("select * from emp " +"where name like concat('%',#{name},'%') " +"and gender = #{gender} " +"and entrydate between #{begin} and #{end} " +"order by update_time desc")public List<Emp> list(String name, Short gender, LocalDate begin, LocalDate end);}

执行结果:生成的SQL都是预编译的SQL语句(性能高、安全)

mybatis_331">mybatis日志

在Mybatis当中我们可以借助日志,查看到sql语句的执行、执行传递的参数以及执行结果。具体操作如下:

  1. 打开application.properties文件

  2. 开启mybatis的日志,并指定输出到控制台

#指定mybatis输出日志的位置, 输出控制台
mybatis.configuration.log-impl=org.apache.ibatis.logging.stdout.StdOutImpl

http://www.ppmy.cn/news/1537428.html

相关文章

汽车网关(GW)技术分析

一、引言 在现代汽车电子系统中&#xff0c;汽车网关&#xff08;Gateway&#xff0c;简称 GW&#xff09;扮演着至关重要的角色。随着汽车电子技术的不断发展&#xff0c;汽车内部的电子控制单元&#xff08;Electronic Control Unit&#xff0c;简称 ECU&#xff09;数量不断…

使用GitLab CI构建持续集成案例

1. 部署GitLab &#xff08;1&#xff09;基础准备 解压软件包并导入镜像&#xff1a; [rootmaster ~]# curl -O http://mirrors.douxuedu.com/competition/Gitlab-CI.tar.gz [rootmaster ~]# tar -zxvf Gitlab-CI.tar.gz [rootmaster ~]# ctr -n k8s.io image import gitla…

计算机视觉的应用36-人工智能时代计算机视觉技术在电力系统中的应用

大家好&#xff0c;我是微学AI&#xff0c;今天给大家介绍一下计算机视觉的应用36-人工智能时代计算机视觉技术在电力系统中的应用。本文综述了人工智能时代计算机视觉技术在电力系统中的应用。文章首先介绍了项目背景&#xff0c;随后详细阐述了计算机视觉技术的模型、技术原理…

学习小课堂

1.多服务节点下Session-Cooki方案如何做&#xff1f; Session-Cookie 方案在单体环境是一个非常好的身份认证方案。但是&#xff0c;当服务器水平拓展成多节点时&#xff0c;Session-Cookie 方案就要面临挑战了。 举个例子&#xff1a;假如我们部署了两份相同的服务 A&#x…

Scala面试题大全~基础题(15题)

1&#xff1a;Scala是什么? Scala是一种多范式的编程语言&#xff0c;它结合了面向对象编程和函数式编程的特性&#xff0c;它支持面向对象、函数式和命令式编程方法。Scala运行在Java虚拟机&#xff08;JVM&#xff09;上&#xff0c;这意味着它可以与Java代码无缝集成。它还…

【正点原子K210连载】第四十四章 人脸68关键点检测实验 摘自【正点原子】DNK210使用指南-CanMV版指南

第四十四章 人脸68关键点检测实验 在上一章节中&#xff0c;介绍了利用maix.KPU模块实现了人脸属性分析&#xff0c;本章将继续介绍利用maix.KPU模块实现的人脸68关键点检测。通过本章的学习&#xff0c;读者将学习到人脸68关键点检测应用在CanMV上的实现。 本章分为如下几个小…

蓝桥杯:求平均年龄

#include<stdio.h> int main() { int num 0; float age 0,sum0; printf("请输入总人数: "); scanf_s("%d" ,& num); for (int i1; i <num;i) { scanf_s("%f", &age); sum age…

Flutter渲染过程

The rendering process is what transforms your widget tree into the actual pixels that are displayed on the screen. It’s like the magic behind the scenes that brings your app’s UI to life! 呈现过程将小部件树转换为显示在屏幕上的实际像素。它就像幕后的魔法&…