[Java Web] 009 -- MyBatis (Getting Started & CRUD & Dynamic SQL)

Table of contents

foreword

What is MyBatis?

1. Getting Started with MyBatis

1. Quick start

①. Case introduction

②. Implementation process

③ Summary

④, extension: configure SQL prompt

2. Introduction to JDBC

①. Essence

②, JDBC operation database code example

③, the original JDBC problems

④ How does MyBatis solve the problems existing in the original JDBC?

⑤ Summary

3. Database connection pool

①. Comparison with or without database connection pool

②. Advantages of database connection pool

③, how to implement the database connection pool

④ Summary

4、lombok

①. Introduction

2. Basic operation of MyBatis

1. Environment preparation

①. Requirements Description

②, preparation work

2. Delete

①, delete according to the primary key

②, log output

③, precompiled SQL

④, SQL injection

⑤. Parameter placeholders (the placeholders are not only #{}, but also ${})

⑥ Summary

3. Add (insert data)

①. New example

②, primary key return

③ Summary

4. Update

①. Update example

② Summary

5. Query

①. Example: Query by ID

②, MyBatis data encapsulation

③, condition query

④, parameter name description

6. XML mapping file (implement MyBatis through XML file)

①, specification (three points)

②, XML mapping file plug-in (MyBatisX)

③. How to choose annotations and XML?

④ Summary

Three, MyBatis dynamic SQL

1. Label

①, basic writing

②. Case: Improve the operation of updating employees and change it to dynamic SQL

③ Summary

2. Label

①. Batch delete operation

② Summary

3. Label (these two labels are used together)

4. Summary


foreword

What is MyBatis?

MyBatis official website: MyBatis Chinese website

1. Getting Started with MyBatis

1. Quick start

①. Case introduction

Case : Use MyBatis to query all user data

Write SQL statements in Java and send them to the server

Implementation steps :

Note : In the development of MyBatis, we only need to define the Mapper interface, and there is no need to define its implementation class, because when the program is running, the bottom layer of the framework will automatically generate the implementation class object of this interface.

②. Implementation process

Ⅰ. Create a SpringBoot project:

Check MyBatis related dependencies:

Ⅱ. Delete redundant files and keep the project tidy:

Ⅲ. Creation of database tables and entity classes:

The creation of database tables can be solved by directly executing SQL files in the database;

Entity class creation:

Ⅳ. Configure the connection information of the database -- application.properties (four elements):

Ⅴ. Create Mapper interface:

Ⅵ. After the basic code is written, perform unit testing:

Show results:

③ Summary

first step:

Step two:

third step:

the fourth step:

④, extension: configure SQL prompt

We can configure SQL hints in the Mapper interface:

Configuration method:

However, the configuration prompt at the beginning cannot recognize the data table information. The solution is to configure the MySQL database connection in IDEA

2. Introduction to JDBC

①. Essence

②, JDBC operation database code example

For the encapsulation result data here, how many fields are required to be parsed, and the final effect is displayed:

③, the original JDBC problems

  • Hardcoded: every change requires recompilation
  • Encapsulated data is bloated and cumbersome
  • Frequent creation/release of database connections will waste resources and lead to performance degradation

④ How does MyBatis solve the problems existing in the original JDBC?

When we use SpringBoot to integrate MyBatis for database operations, we mainly focus on two points:

⑤ Summary

3. Database connection pool

Similar to thread pool:

①. Comparison with or without database connection pool

If there is no database connection pool: (create as you use)

And with the database connection pool: (a certain number of connection objects are initialized at the beginning), so that the connection can be reused instead of creating a new connection every time, and the database connection pool also has ( Idle time detection, when it detects that the connection object assigned to the client is idle for more than the specified time, it will release the connection and return it to the connection pool)

②. Advantages of database connection pool

③, how to implement the database connection pool

SpringBoot project default connection pool: (HikariCP comes from Japanese, meaning "light", which means it is fast)

And Druid is Alibaba's open source database connection pool project:

Switch database connection pool : (mainly switch dependencies in pom.xml) GitHub has detailed introduction

Running effect display:

Structure diagram:

④ Summary

4、lombok

Simplify the method of the entity class:

①. Introduction

But if you want to use lombok, you must first introduce the dependency of lombok:

Example:

Precautions:

lombok plugin:

2. Basic operation of MyBatis

1. Environment preparation

①. Requirements Description

②, preparation work

For details, please refer to the quick start case in No. 1

Points to note in entity classes:

Mapper interface: (adding the @Mapper annotation means that the program will automatically create a proxy object of the interface at runtime, and put this proxy object into the IOC container)

2. Delete

①, delete according to the primary key

Example :

Delete data by ID :

EmpMapper.java (delete here has a return value, and returns the affected operand)

unit test:

Show results:

②, log output

The effect display after running:

③, precompiled SQL

Using precompiled SQL has two advantages:

④, SQL injection

Example: (the way of directly splicing SQL)

In precompiled SQL, this method will not work: (This is because no matter what you enter in precompiled SQL, the parameters you enter will be added to the placeholder as a complete data?)

⑤. Parameter placeholders (the placeholders are not only #{}, but also ${})

However, ${} will directly splice the parameters into the SQL statement, and there is a risk of SQL injection, so in general, just use the #{} method

⑥ Summary

3. Add (insert data)

①. New example

Example :

New employee: (Mapper)

unit test:

Show results:

Write out the SQL statement first, and then consider how to execute this statement in MyBatis: (property names are generally named in camel case)

②, primary key return

By default, performing basic insert operations will not return the primary key value. If we want to get this primary key value, what should we do? (Add annotation @Options() )

③ Summary

4. Update

①. Update example

Example : Modify employee information based on primary key

Update data: (SQL statement)

(Mapper):

unit test:

Show results:

② Summary

5. Query

①. Example: Query by ID

SQL statements:

Mapper:

unit test:

Show results:

我们仔细看一下示例中的效果展示,结果发现,前面的数据都返回回来了,但是最后的三个属性却显示为null:

这就需要看一下MyBatis中的数据封装

②、MyBatis的数据封装

属性没有封装成功的原因就是因为类中的属性名与表中的字段名不一致

解决方案一:给字段起别名,让别名与实体类属性一致

解决方案二:通过@Results@Result注解手动映射封装(因为其写法过于臃肿,实际开发中一般不怎么用)

解决方案三:开启MyBatis的驼峰命名自动映射开关

application.properties:

开启之后,就可以按照原来的写法返回查询了

但使用第三种方式是有前提的,你需要严格按照书写规范,数据库中的字段名用下划线分隔,类中的属性名采用驼峰命名的方式,才能自动完成映射

③、条件查询

示例:

Mapper语句

【注意点】:#{}是不能出现在‘’中的,那么在进行模糊查询的时候,我们可以把 #{} 改为 ${}

应将其改为:

单元测试:

效果展示:

但是由于模糊查询这里我们使用的是 ${} 的方式实现的,这就会导致性能低,存在SQL注入问题的风险,我们可以通过 concat 字符串拼接函数来解决该问题:

④、参数名说明

这是因为在1.x版本中,在对Mapper接口进行编译的过程中,它并不会保留方法的形参名称,就比如:name, gender, begin, end 并不会在编译之后的字节码文件中保留,在生成的字节码文件中最终形成的形参的名字就成了下列的形式:

此时,就无法将形参和名称对应起来,所以需要额外加上一个@Param注解进行解释,而在2.x版本,在编译时,这些形参名会被保留下来:

6、XML映射文件(通过XML文件实现MyBatis)

①、规范(三点)

示例:创建一个XML映射文件

Ⅰ、在 resources 目录下创建包:(不用.,而是使用/ 分隔)

Ⅱ、创建XML文件,XML语法规范可以在MyBatis官网查询到

问题:为什么要遵循以上三点规范?

:因为两个文件是独立的,没有任何关联,我们需要通过以上规范来给它们建立关联关系

②、XML映射文件插件(MyBatisX)

可以实现语法的快速定位:

③、如何选择注解和XML?

简单来说:

④、小结

三、MyBatis动态SQL

我们想实现的效果:这个查询是根据输入的条件动态组装的,如我们要查询姓名,则只根据姓名进行查询,而实现这种查询的方式就是动态SQL

1、<if>标签

①、基础写法

XML语句:

单元测试:

效果展示:(没有查询 entrydate 与 update_time)

我们将单元测试语句改为下列形式:

如果XML中的语句没变,则会出现以下错误:(提示语法错误,多了一个and)

解决办法:将where关键字替换为<where>标签,用来动态生成where关键字,以及自动清除语句中的and 或者 or

 

②、<if>案例:完善更新员工操作,改为动态SQL

In the update method written before, if some fields are not assigned empty values, the corresponding fields will also be assigned empty values:

So it needs to be changed to dynamic update: (Since we installed MyBatisX before, we can use its automatic generation)

Generate: (the label will be generated according to the method name, if this is update, the update label will be generated for you)

Transform the SQL statement:

unit test:

Effect display: (only the assigned fields are updated)

However, the modified SQL statement above is still not perfect. It needs to replace the set keyword with the <set> tag , which is similar to <where>

③ Summary

2. <foreach> tag

①. Batch delete operation

Example:

Batch delete employees: (Mapper)

(XML):

unit test:

② Summary

3. <sql><include> tags (these two tags are used together)

If there are a lot of repeated statements in the XML, you can use the <sql><include> tag for reuse

4. Summary

Guess you like

Origin blog.csdn.net/qq_41071754/article/details/129977607