JavaWeb后端基础知识(2)包括(MyBatis)

JavaWeb后端基础知识(2)

目录

JavaWeb后端基础知识(2)

一. MyBatis

1.什么是Mybatis?

2.步骤

(1)准备工作

(2)引入Mybatis的相关依赖,配置Mybatis

(3)编写SQL语句(注解或XML)

3. JDBC介绍

(1)JDBC:

(2)本质

4. 数据库连接池

(1)简介

(2)优势

(3)标准接口:DataSource

5. lombok

(1)简介

(2)注解

(3)依赖

6.基础操作(依据注解)

【1】删除

(1)案例

(2)注意事项

【2】日志输出

【3】 预编译SQL(使用#{}就会形成预编译SQL)

(1)优势

【4】SQL注入

(1)简介

(2)参数占位符

【5】删除

(1)案例

(2)新增(主键返回)

【6】更新

【7】数据封装

(1)方案一:给字段起别名,让别名与实体类属性一致(一般不用)

(2)方案二:通过@Results,@Result注解手动陕射封装(一般不用)

(3)在application.properties中添加(推荐)

【8】模糊匹配的问题

(1)问题

(2)通过concat函数解决

(3)在springBoot的1.x版本或单独使用mybatis要加@Param注解

7.基础操作(依据XML)

【1】规范

(4)案例

【2】选择

8. Mybatis动态SQL

[1]

(1)相关标签

(2)案例

[2]

(1)形参

(2)案例

[3]

(1)内容

(2)案例


一. MyBatis

1.什么是Mybatis?

(1)MyBatis是一款优秀的持久层框架,用于简化JDBC的开发。

(2)MyBatis本是Apache的一个开源项目iBatis,2010年这个项目由apache迁移到了googlecode,并且改名为MyBatis 。2013

年11月迁移到Github。

(3)官网:https://mybatis.org/mybatis-3/zh/index.html

2.步骤

(1)准备工作

(创建springboot工程、数据库表user、实体类User)

(2)引入Mybatis的相关依赖,配置Mybatis

(写在MyBatis自带的application.properties中)

#配置数据库的连接信息-四要素

#驱动类名称

spring.datasource,driver-class-name=com.mysql.cj.jdbc.Driver

#数据库连按的uzl(mybatis要换成自己的数据库名)

spring.datasource.url=jdbc:mysql://localhost:3306/mybatis

#连接数据库的用户名

spring.datasource.username=root

#连接数据库的密码(自己的)

spring.datasource.password=123456

(3)编写SQL语句(注解或XML)

1)在接口上添加@Mapper注解//在运行时,会自动生成该接口的实现类对象(代理对象),并且将该对象交给IOC容器管理

2)在方法上加@Select注解,括号里加sql语句。

3)案例

①接口

@Mapper

public interface UserMapper {

//查询全部用户信息

@Select("select *from user")

public list<user> list();

}

②单元测试

@springBootTest //springboot格合单元测试的注解

class SpringbootMybatisQuickstartApplicationTests(

@Autowired

private UserMapper userMapper;

@Test

public void testlistUser(){

List<ser>userList =userMapper.list();

userList.stream().forEach(user ->{

System.out.println(user);

});

}

}

3. JDBC介绍

(1)JDBC:

(Java DataBase Connectivity),就是使用java语言操作关系型数据库的一套API。

(2)本质

1)sun公司官方定义的一套操作所有关系型数据库的规范,即接口,

2)各个数据库厂商去实现这套接口,提供数据库驱动jar包。

3)我们可以使用这套接口(JDBC)编程,真正执行的代码是驱动jar包中的实现类。

4. 数据库连接池

(1)简介

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

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

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

(2)优势

1)资源重用

2)提升系统响应速度

3)避免数据库连接遗漏

(3)标准接口:DataSource

1)官方(sun)提供的数据库连接池接口,由第三方组织实现此接口。

2)功能:获取连接 Connection getConnection()throws sQlException;

3)常见产品:C3PO DBCP Druid Hikari(默认)

4)Druid(德鲁伊)

Druid连接池是阿里巴巴开源的数据库连接池项目,功能强大,性能优秀,是Java语言最好的数据库连接池之一

5)切换Druid数据库连接池

①pom.xml中:(Druid依赖)

<dependency>

<groupld>com.alibaba</groupld>

<artifactld>druid-spring-boot-starter</artifactld>

<version>1.2.8</version>

</dependency>

②application.properties中(数据库连接信息,已经做过了)

spring.datasource.driver-class-name=com.mysql.cj.jdbc.Drivei

spring.datasource.url=jdbc:mysql://localhost:3306/mybatis

spring.datasource.username=root

spring.datasource.password=1234

5. lombok

(1)简介

Lombok是一个实用的]ava类库,能通过注解的形式自动生成构造器、getter/setter、equals、hashcode、tostring等方法,并可以自动化生成日志变量,简化java开发、提高效率。

(2)注解

①@Getter/@Setter 为所有的属性提供get/set方法

②@ToString 会给类自动生成易阅读的 toString 方法

③@EqualsAndHashcode 根据类所拥有的非静态字段自动重写 equals 方法和 hashcode 方法

④@Data 提供了更综合的生成代码功能(@Getter+@Setter+@ToString+ @EqualsAndHashcode)(等于1+2+3,使用最多!!!)

⑤@NoArgsConstructor 为实体类生成无参的构造器方法

⑥@AllArgsConstructor 为实体类生成除了static修饰的字段之外带有各参数的构造器方法,

(3)依赖

<!--lombok-->

<dependency>

<groupId>org.projectlombok</groupId>

<artifactId>lombok</artifactId>

</dependency>

6.基础操作(依据注解)

【1】删除
(1)案例

@Mapper

public interface EmpMapper {

//根据ID删除数据

@Delete("delete from emp where id = #{id}(占位符)")

public void delete(Integer id);

}

(2)注意事项

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

【2】日志输出

可以在application.properties中,打开mybatis的日志,并指定输出到控制台。

#指定mybatis输出日志的位置,输出控制台

mybatis.configuration.log-impl= org.apache. ibatis .logging. stdout. StdOutlmpl

【3】 预编译SQL(使用#{}就会形成预编译SQL)
(1)优势

①性能更高

②更安全(防止SQL注入)

【4】SQL注入
(1)简介

SQL注入是通过操作输入的数据来修改事先定义好的SOL语句,以达到执行代码对服务器进行攻击的方法

如:检查登录时的sql语句

select count(*)from emp where username ='zhangsan' and password='111';

可以输入帐号111密码‘or'1' ='1就形成了

select count(*)from emp where username=‘111'and password=‘’or ‘1'=’1';此时一定可以登录成功。

(2)参数占位符

1)#{...}

①执行SQL时,会将#{...}替换为?,生成预编译SQL,会自动设置参数值。

②使用时机:参数传递,都使用#{...}

2)${...}

①拼接SQL。直接将参数拼接在SQL语句中,存在SQL注入问题。

②使用时机:如果对表名、列表进行动态设置时使用.

【5】删除
(1)案例

@Insert("insert into emp(username, name, gender, image, job, entrydate, dept id, create time, update time) " +

“values(#{username}, #{namel, #{gender}, #{image}, #{job}, #{entrydate}, #{deptld), #{createTime}, #updateTime})")

public void insert(Emp emp);(上面的参数都为emp的成员变量)

(2)新增(主键返回)

1)描述:在数据添加成功后,需要获取插入数据库数据的主键

如:添加套餐数据时,还需要维护套餐菜品关系表数据。

2)实现

在@Insert注解上面加上@Options(keyProperty="id",useGeneratedKeys = true)会自动将生成的主键值,赋值给emp对象的id属性(“id”可换成其他属性)。

【6】更新

@Update注解

【7】数据封装

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

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

(1)方案一:给字段起别名,让别名与实体类属性一致(一般不用)

@Select("select id,username, password, name, gender, image, job, entrydate,dept_id deptId, create_time createTime, update_time updaterime from emp where id m f{id)")

(2)方案二:通过@Results,@Result注解手动陕射封装(一般不用)

@Results({

@Result(column ="dept_id",property= "deptId"),

@Result(column="create_time",property = "createTime"),

@Result(column = "update_time", property = "updaterime")

})

(3)在application.properties中添加(推荐)

#开启mybatis的驼峰命名自动映射开关a_column—>aCloumn

mybatis.configuration.map-underscore-to-camel-case=true

【8】模糊匹配的问题
(1)问题

@select("select * from emp where name like '%{name}%' and gender = #{gender} and " +"entrydate between #{begin} and #{end} order by update time desc ")

#{}不能出现在引号中,因此模糊匹配中#{}换成${},但有风险,性能低、不安全、存在SQL注入问题

(2)通过concat函数解决

@Select("select * from emp where name like concat('%',#{name},'%') and gender = #{gender) and "+"entrydate between #{becin} and #{end} order by update_time desc“}

public List<Emp>list(String name,Short gender,LocalDate begin,LocalDate end);

(3)在springBoot的1.x版本或单独使用mybatis要加@Param注解

@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 (@Param("name")String name, @Param("gender")short gender ,

@Param("begin")localDate begin ,@Param("end")localDate end);

7.基础操作(依据XML)

【1】规范

(1)XML映射文件的名称与Mapper接口名称一致,并且将XML映射文件和Mapper接口放置在相同包下(同包同名)

(2)XML映射文件的namespace属性为Mapper接口全限定名一致。

(3)XML映射文件中sql语句的id与Mapper接口中的方法名一致,并保持返回类型一致。

(4)案例

1)Mapper接口

@Mapper

public interface EmpMapper {

public List<Emp> list (String name, Short gender , LocalDate begin , LocalDate end);

}

2)XML映射文件

<mapper namespace="com.itheima.mapper.EmpMapper">

<select id="list" resultType="com.itheima.pojo.Emp">

select * from emp where name like concat('%',#{name},"%’) and gender = #gender) and entrydate between #{begin} and #{end} order by update time desc

</select>

</mapper>

(resultType:单条记录所封装的类型,要全类名)

【2】选择

使用Mybatis的注解,主要是来完成一些简单的增删改查功能。如果需要实现复杂的SQL功能,建议使用XML来配置映射语句。

8. Mybatis动态SQL

[1]<if>
(1)相关标签

<if>:用于判断条件是否成立。使用test属性进行条件判断,如果条件为true,则拼接SQL。test属性是用来指定条件的。

<where>:where 元素只会在子元素有内容的情况下才插入where子句。而且会自动去除子句的开头的AND 或OR。

<set>

动态地在行首插入 SET 关键字,并会删掉额外的逗号。(用在update语句中)

(2)案例

<where>

<if test="name != null">

namd like concat('&',#{name},'$')

</if>

<if test "gender ! null">

and gender = figender}

</if>

<if test="begin != null and end != null">

and entrydate between #{begin} and f{end}

</if>

</where>

[2]<foreach>

<!--批借删除员工(18,19,20)-->

(1)形参

collection:遍历的集合

item:遍历出来的元素

separator: 每一次遍历使用的分隔符

open: 遍历开始前拼接的片段

close: 遍历结束后拼接的片段

(2)案例

<delete id="deleteByIds">

delete from emp where id in

<foreach collection="ids" item="id" separator="," open="(" close=")">

#{id}

</foreach>

</delete>

[3]<sql><include>
(1)内容

<sql>:定义可重用的 SQL 片段。

<include>:通过属性refid,指定包含的sql片段。

(2)案例

<sql id="commonSelect“>

select id,username, password, name, gender,image, job, entrydate.

dept id, create time, update time from emp

</sql>

<include refid="commonSelect"/>

  • 17
    点赞
  • 18
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值