Today’s sharing started, please give us more advice ~
Introduction of mybatis
1 What is Mybatis
MyBatis is an excellent persistence layer framework
MyBatis avoids almost all of the JDBC code and the process of manually setting parameters and fetching result sets
MyBatis can configure and map native information using simple XML or annotations to map interfaces and Plain Old Java Objects to records in the database.
2 persistence and persistence layers
persistence
Save temporary data that was stored in memory to a permanentable storage device.
JDBC is a persistence mechanism. File IO is also a persistence mechanism.
The need for persistence is due to memory defects
The persistence layer
—-> DAO layer [Data Access Object]
3. Advantages of Mybatis
Decouple SQL from program code
Flexible with no impact on the application
Mybatis builds quickly
Lombox plugin and Free Mybatis plugn plugin can be installed for easy use
Process: POM environment – > Mybatis – ConfigXML configuration file – > Tools – > Entity – > Interface – > Interface implementation – > Test class
1.pom.xml
2.mybatis-config.xml
3.SqlSessionUtil utility class (used to get sessions)
4. Entity class UserInf
5. The interface UserMapper
6.List selectUser();
Interface implementation usermapper.xml
Don’t forget to register in Mybatis-config.xml
7. Test
Mybatis add delete change check
session.commit(); // Commit transaction, important! If you don’t write, you won’t commit to the database
1 the namespace
As one of the attributes in Mapper, namespace is the only basis for mapper interface and XML implementation.
2 select
UserMapper Method for adding an interface
// Query users by id
UserInf selectUserById(@Param(“id”)int id);
Usermapper. XML adds method mapping
test
3 insert
UserMapper Method for adding an interface
// Add user information
int addUserInf(UserInf userInf);
Usermapper. XML adds method mapping
test
4 update
UserMapper Method for adding an interface
// Modify user information
int updateUserInf(UserInf userInf);
Usermapper. XML adds method mapping
test
5 delete
UserMapper Method for adding an interface
// Delete the user based on the ID
int deleteUser(@Param(“id”)int id);
Usermapper. XML adds method mapping
test
6 Fuzzy Query
Type 1: Add SQL wildcards to Java code.
2. Concatenate wildcards in SQL statements, which causes SQL injection
Note 7 points
All add, delete and change operations need to commit a transaction!
Interface all common parameters, as far as possible to write @param parameter, especially multiple parameters, must write!
Sometimes, depending on your business needs, you can consider using map to pass parameters!
In order to standardize operation, in the SQL configuration file, we try to write Parameter Parameter and resultType!
Mybatis configuration details
1 Core configuration file
Mybatis -confifig. XML system core configuration file
The MyBatis configuration file contains Settings and property information that will deeply affect MyBatis behavior
Some properties and configuration description:
Configuration
Properties
Settings
typeAliases
typeHandlers
objectFactory
Plugins
Environments
Environment (environment variable)
transactionManager
A dataSource
DatabaseIdProvider (Database vendor Identity)
Mappers (mapper)
2 Environments
Different departments may require different environments based on production requirements. You can configure multiple environments, but only one environment can be used at the same time. One of the environments must be specified as the default operating environment (specified by default).
Child element node: environment
A specific set of environment, by setting the ID to distinguish, ID to ensure that the only!
Child element node: transactionManager – [transactionManager]
MyBatis, there are two types of transaction manager (i.e., type = “[JDBC | MANAGED]”) in a separate MyBatis no additional configuration is required
Child element node: dataSource
The dataSource element uses the standard JDBC dataSource interface to configure the resources of the JDBC connection object.
There are three kinds of built-in data types (type = “[UNPOOLED | POOLED | JNDI]”))
3 Mappers
Mapper: Defines the mapping SQL statement file
3.1 Different ways of introducing resources
3.2 Mapper File Template
4 Properties
The properties property can be changed dynamically using configuration files or Java code
When a property is configured in more than one place, the value in the propertie is overwritten by resouce and by method pass-throughs in Java code.
You can configure default property values in the form of placeholders
4.1 Optimization using configuration Files
The new config. The properties
Import the configuration file and display the property values with placeholders
5 typeAliases
Code redundancy to solve the problem of too long package names.
The first way
User can be used in all places where com.lyj.entity.userINF is used
The second way
All entity classes in the com.lyj.entity package can be referenced using the first letter of the class name (e.g. Com.lyj.entity. UserInf is replaced by UserInf).
You can also customize aliases by annotating the entity class
@Alias(“user”)
public class UserInf { … }
6 Settings
You can add Settings for MyBatis
Database hump name conversion Settings
Log Displays log Settings
ResultMap(Result set Mapping)
Developed to solve data mapping problems
1 Resolve the inconsistency between database and entity class attribute names
Problem solved: Inconsistent property and field names
For various reasons, database property fields do not correspond exactly to entity class property fields.
For example:
Now the database table attributes are:
Entity class attribute values are:
Query statement:
Because the PWD does not exist in the entity class, it cannot be injected when the value is injected. The password attribute is empty.
The solution
Use an alias (shortened to PWD password)
Use result set mapping ->ResultMap
2 Solving many-to-one result set mapping (Association association attribute)
Understanding more than one:
There are many students for one teacher.
Database concept understanding: students have a TID corresponding to the teacher ID.
Understanding the entity class concept: the student owns a teacher object.
2.1 Processing by query nesting
Entity class student and teacher
StudentMapper Adds an interface
// Query all students
public List queryAllStudents();
Studentmapper. XML add a corresponding method (for teacher object attribute use association attribute)
Test (use the association attribute for the object attribute teacher)
2.2 Nesting according to results.
3 solving one-to-many result set mapping (Collection set)
One to many understanding:
A teacher has more than one student
Understanding the concept of database: the teacher has an ID corresponding to the student TID.
The teacher has a List of student objects.
3.1 Processing by query nesting.
Entity class Student and Teacher
TeacherMapper add method
public Teacher getTeacher(int id);
Teachermapper.xml added implementation
test
3.2 Nesting according to results
Dynamic SQL
Dynamic SQL refers to the generation of different SQL statements according to different query conditions.
1 the environment
Utils utility class: randomly generates ids
The entity entity class
Other normal layout, add data to the database.
2 if statement
Need: query blog by author name and blog name! If the author name is empty, the query is based on the blog name, otherwise, the query is based on the author name
XML file implementation
Note: All if statements are executed in sequence, so an error occurs when title is null and author is not. The introduction of the where
3 where clause
XML file implementation
Note: When the label containing where has a return value, the where character can be automatically added, AND when the detection label contains AND OR OR character, the character will be removed.
4 choose statements
Using the if and WHERE collocation can solve most SQL query concatenation, but sometimes we need to jump out of accepting parameters immediately if a condition is not null. At this point we can use the Choose implementation, the equivalent of switch in programming languages.
XML implementation:
It reads switch-case-otherwise.
5 the foreach statement
Foreach is the equivalent of a for loop, and can be used when we need to query multiple items at once.
Testing:
Select * from blog where (id=1 or id=2 or id=3)
6 set statements
When we need to modify the operation, the set operation combined with if will show the previous query problems.
Before using the set tag, the name =SQL statement concatenation would fail when the author was empty. In this case, using the set tag is a good solution.
After using the set tag
** The set tag is similar to where. When the inner tag returns a value, the set character is automatically added. When the inner tag contains a character, the ** is automatically removed
Seven SQL fragment
In the normal data query process, using SELECT * directly is undoubtedly very dangerous for data security, we will use the form of fields to replace this method, but in the case of too many fields, it is too troublesome and difficult to maintain the code repeatedly. Custom SQL fragments are a good solution to this problem.
The SQL tag works well with the incloud tag.
Log factories and pagination
1 Log Factory
Mybatis can configure log to process information, can use its own log factory, can also use the third party package.
Mybatis built-in log factory provides log function, specific log implementation has the following tools:
SLF4J
Apache Commons Logging
Log4j 2
Log4j
JDK logging
Standard logging implementation:
2 Log4j
Using Log4j, we can control the destination of log messages: console, text, GUI components…
We can also control the output format of each log;
Use:
Guide package
Change log factory Settings
Create the configuration file log4j.properties
use
** Note: **log4j packages use apache packages, will automatically generate a log folder in the current directory, can display log records.
3 limit implements paging
** Paging: ** I remember a JavaWeb project where the teacher asked me to practice paging queries using Java code. At the time, a utility class was used to deal specifically with paging logic, which in retrospect is not too difficult.
There are two main approaches, one at the MySQL level and the other at the Java code level.
3.1 Implementation of paging
Mysql grammar:
Steps:
The SQL statement
If we had many different types of paging, writing a different utility class for each type would make our code redundant, and generics would solve this problem.
Blog entity class
PageModel generic class to implement a basic paging data.
If you want to add data with different paging characteristics to the PageModel, you can use inheritance to do this.
Utility class processing
The test class
I thought I was done with the pagination, but I still couldn’t abstract the Mapper out, and the pagination failed.
3.2 RowBounds paging
Method of use
3.3 PageHelper
Method of use
Mybatis cache
1 introduction
What is a Cache?
Temporary data exists in memory.
By storing the data frequently queried by users in the cache (memory), users can query data from the cache instead of from disk (relational database data files), thus improving the query efficiency and solving the performance problems of high concurrency system.
Why cache?
Reduce the number of interactions with the database, reduce system overhead, improve system efficiency.
What kind of data can be cached?
Data that is frequently queried and infrequently changed.
2 Mybatis cache
MyBatis includes a very powerful query caching feature that makes it very easy to customize and configure the cache. Caching can greatly improve query efficiency.
MyBatis system defines two levels of cache by default: level 1 cache and level 2 cache
By default, only level 1 caching is enabled. (SQLsession-level cache, also known as local cache)
Level 2 caching, which needs to be manually enabled and configured, is namespace-level caching.
To improve scalability, MyBatis defines Cache interface Cache. We can customize the level 2 Cache by implementing the Cache interface
3 Level 1 Cache
Level 1 caching is also known as local caching.
It is enabled by default.
Sqlsession-level cache.
We execute the same query in the same session, and will not repeat the SQL read, but will read from the cache.
3.1 Four cases of level 1 cache invalidation
Different sqlSession
The same sqlSession, different query conditions
SqlSession is the same, two queries between the execution of the operation!
If sqlSession is the same, manually clear level-1 cache.
session.clearCache(); // Clear the cache manually
4 Level 2 Cache
Level 2 cache is also called global cache, level 1 cache scope is too low, so was born level 2 cache
Namespace-level caching, one namespace for each level 2 cache;
Working mechanism
A session queries a piece of data and the data is placed in the level 1 cache of the current session.
If the current session is closed, the level 1 cache for that session is gone. But what we want is for the session to close and the data from the level 1 cache to be saved to the level 2 cache;
The new session queries the information and can retrieve the content from the level 2 cache.
The data detected by different mapper is stored in its own cache (map).
4.1 Use of level 2 Cache
Mybatis -config. XML enables global caching
Configure the official document for caching in the namespace where you want to enable caching
# This more advanced configuration creates a FIFO cache, refreshed every 60 seconds, that can store up to 512 references to the result object or list, and the returned objects are considered read-only, so modifying them may conflict with callers in different threads.
test
Data is stored from tier 1 cache to tier 2 cache only after the session ends.
5 Third-party Cache EhCache
Import corresponding dependencies
Enable EhCache in the corresponding mapper configuration file.
Create a new ehcache.xml file
Today’s share has ended, please forgive and give advice!