Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

30 minutes getting started with MyBatis

2025-02-24 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Database >

Share

Shulou(Shulou.com)06/01 Report--

The purpose of this article is to tell the most boring basic knowledge in the most popular language

When the project framework SSH (spring, Struts, Hibernate) went down, SSM (spring, SpringMVC, MyBatis) became popular, and most projects gradually turned to SSM, so MyBatis has become a must-learn knowledge for Java programmers. This article makes a small summary of mybatis syntax in order to let readers learn to use MyBatis in the least time.

Outline of the article:

What is MyBatis?

The introduction of MyBatis

Configuration of MyBatis

SQL syntax of MyBatis

A wave of operating principle and practical operation

1. What is MyBatis?

MyBatis, formerly known as ibatis, an open source project of Apache, was renamed MyBatis when it migrated to Google code.

In terms of what has been said on the Internet, it is:

MyBatis is an excellent persistence layer framework that supports customized SQL, stored procedures, and advanced mapping. MyBatis avoids almost all JDBC code and manually setting parameters and getting result sets. MyBatis can use simple XML or annotations to configure and map native information, mapping interfaces and Java's POJOs (Plain Ordinary Java Object, ordinary Java objects) to records in the database.

2. The introduction of MyBatis

If it is a traditional project, you can directly download the corresponding jar package and import it into the project at the following address:

1 http://central.maven.org/maven2/org/mybatis/mybatis/3.4.6/mybatis-3.4.6.jar

If you build a project for maven, you only need to add the following dependency to pom.xml and reimport it:

one

2 org.mybatis

3 mybatis

4 x.x.x

five

If it is a gradle-built project, you only need to add the following code to the configuration:

1Universe / https://mvnrepository.com/artifact/org.mybatis/mybatis

2compile group: 'org.mybatis', name:' mybatis', version: '3.4.6'

3. Configuration and initialization of MyBatis

After the introduction of mybatis, we need to learn the configuration of mybatis. Although popular frameworks such as springboot no longer need to be configured by XML, as a novice, we still need to learn some explanations about the configuration of mybatis, which will help us to understand the principle of mybatis.

Basic configuration of mybatis:

one

two

four

five

six

seven

eight

nine

ten

eleven

twelve

thirteen

fourteen

fifteen

sixteen

seventeen

eighteen

nineteen

twenty

twenty-one

twenty-two

twenty-three

twenty-four

twenty-five

twenty-six

twenty-seven

twenty-eight

twenty-nine

This is a standard mybatis configuration file, and in many cases, this configuration is sufficient, but in order to have a better understanding of the future use, let's explain the common subtags under the configuration tag in the configuration file:

Properties tag: used to define some common attributes for easy use in configuration files

Settings tag: used to set configurations that change the behavior of the MyBatis runtime

Environments tags: for configuration to accommodate multiple environments

Mappers tags: settings for mapper mapper

Here is a brief explanation of each label:

1.properties tag

When we need to configure some values as a variable, we can add a property tag under the properties tag, where the attribute name refers to the variable name and the attribute value is the value, such as:

one

two

three

Once defined, you can use it in the configuration file, such as:

one

two

three

2.settings tag

Each setting in the settings tag is used to adjust the running behavior of the mybatis. We can add some of these setting when we need to use them. The common configuration and explanation of each setting are as follows:

one

2 # sets any cache that has been configured by all mappers in the configuration file, default false.

three

4 # delayed loading global switch. When enabled, all associated objects are loaded late. Default is false.

five

6 # whether a single statement is allowed to return multiple result sets. Default is true.

seven

8 # whether to use column labels instead of column names. Default is true

nine

10 # whether to allow JDBC to support automatic generation of primary keys. Default is false

eleven

12 # specify how MyBatis should automatically map columns to fields or attributes

thirteen

14 # specifies the behavior of automatically mapping unknown columns (or unknown attribute types) of the target. Default is NONE.

15 # NONE: no response

16 # WARNING: output reminder log

17 # FAILING: mapping failed (SqlSessionException thrown)

eighteen

19 # configure the default actuator. Default is SIMPLE

20 # SIMPLE is a common actuator.

21 # REUSE executor reuses preprocessing statements

22 # BATCH executor will reuse statements and perform batch updates

twenty-three

24 # sets the timeout, which determines the number of seconds the driver waits for the database to respond.

twenty-five

26 # set a prompt value for the number of driven result sets (fetchSize)

twenty-seven

28 # whether paging is allowed in nested statements. Set to false if allowed.

twenty-nine

30 # whether to enable automatic hump naming rule (camel case) mapping. Default is false.

thirty-one

thirty-two

3. Environments

Environments is created to configure multi-environment data sources. After we have defined various environments, we only need to set the environment from which the data sources are loaded in the code, or modify the default in the environments tag to achieve the effect of switching environments.

The basic configuration of environments is as follows:

one

2 # define an environment configuration named development

three

4 # set the type of transaction manager, including JDBC and MANAGED Liang

five

six

seven

8 # data Source Settings

nine

ten

eleven

twelve

thirteen

fourteen

fifteen

sixteen

When we need to add an environment configuration, we just need to copy and paste an environment and change the value of the properties in it.

4.mappers

The mappers tag is actually used for high-speed mybatis where to find our written SQL statement, that is, the mapping file. When we write a table corresponding to the mapper.xml, we only need to add a mapper under the mappers.

There are several ways for mappers to find mapper:

1. Locate according to the mapper.xml file:

If these mapper.xml are in a folder xxx in resources, set them with the resource property

one

two

three

four

two。 Implement the fully qualified class name based on the mapper interface:

After we have set the namespace in these mapper.xml, we can set it through the full-path class of the mapper interface implementation class. For example, after AMapper.xml sets namespace to the com.xxx.dao.AMapper class, we can use the class attribute to specify the mapper to be looked up here, but only if:

AMapper.xml and AMapper.java must be under the same package.

one

two

three

four

3. Packet mapping

Some people will say, if we have a lot of tables, isn't it hard to write row by line? mybatis provides a way to introduce the mapper by package for ease of use, but the premise is

All mapper.xml and mapper.java must be in the same package.

one

two

three

4. URL mapping:

If your mapper is not in the project, but in another file, mybatis provides a way to introduce mapper.xml through URL.

one

two

three

four

5. SQL syntax of MyBatis

Writing code under the existing framework, in most cases, does not need to care about the underlying things of mybatis, and a lot of work is focused on writing mapper files. So it is necessary to learn to write SQL statements under mybatis. Let's first look at a standard mapper file format:

one

two

three

four

As you can see, the root structure of a mapper file starts with the mapper tag, but what is the use of namespace in the mapper tag? What should he write?

We know that there is a programming idea called interface-oriented programming, which is to separate the specific logic implementation from the interface in the business requirements, only expose the interface, and realize the business through the interface. When the business requirements change, only the implementation class needs to be modified, and there is no need to change the existing docking code to reduce the impact on the system.

Mybatis is based on this idea, after specifying the interface corresponding to the mapper in namespace, there is no need to write the interface implementation class, mybatis will automatically help you find the corresponding SQL statement to be executed through this binding.

For example, to create an interface for XxxMapper.java in com.xxx.dao, you need to write a method to query user information according to the user.

1package com.xxx.dao

2public interface XxxMapper {

3 / / query a piece of user information based on name

4 Map selectUserByName (@ Param ("name") String name)

5}

At this point, we can set the namespace in mapper.xml to correspond to the above API:

one

two

three

four

5 select * from user where name = # {name}

six

seven

In a specific business implementation class, it is used as follows:

1@Service

2public class XxxServiceImpl implements CustomerInfoService {

3 @ Resource

4 private XxxMapper xxxMapper=null

5 @ Override

6 public Map getUser (String name) {

7 return xxxMapper.selectUserByName (name)

8}

9}

As you can see, from the process of writing the SQL statement to the final business call SQL statement, we did not write any implementation class for the XxxMapper interface, this is based on the idea of interface programming, mybatis has dealt with these things, we just need to correspond the SQL mapping file and the interface class in namespace, and we can use it.

After knowing how to set the root node mapper, we need to learn how to write SQL statements in the mapper node. After the mapper tags, mybatis provides a lot of semantic tags for us to write SQL statements and configuration mapping files. Here are a few non-frequently used child tags:

1. Select: the label used to write query statements

2. Update: the label used to write update statements

3. Insert: the label used to write insert statements

4. Delete: the label used to write delete statements

5. Sql: a label that writes a block of statements that can be referenced by other statements

6. ResultMap: define the mapping relationship between database results and entity attributes

These tags are necessary for us to write SQL statements, and their use is described below.

1. Select tag

In a project, most of the functions involve queries, so mybatis also has a lot of attributes for the select element, so here are just a few of the most commonly used attributes and their explanations:

one

fourteen

15 # SQL statement is written.

sixteen

seventeen

2. Update tag 1

eight

9 # write the SQL statement of update.

ten

eleven

3. Insert tag 1

thirteen

14 # write the SQL statement of insert.

fifteen

sixteen

4. Delete tag 1

eight

9 # write the SQL statement of delete.

ten

eleven

5. Sql tag

The SQL node is used to write SQL code snippets that can be reused, and when we have written a code snippet in SQL, it can be used in other statements.

As we all know, it is very painful to change the table name after the SQL is full, because the table name is written in the SQL statement, but in mybatis, we can use the sql tag to define the table name. If you introduce this code block in all SQL:

1user

two

Dynamic makes the table name dynamic with include in the statement.

four

5select * from

six

7 where name = # {name}

eight

There are many other similar uses, such as uniformly defining query fields with sql blocks, and then calling them where needed. We need to use these tags flexibly in the actual use process to reduce the code amount and complexity of SQL.

6. ResultMap tag

The resultMap tag is used to represent the mapping relationship between database query results and entity objects. It is a complex tag in the mapping file. There are two commonly used attributes:

one

six

7 # child node.

eight

nine

And it has a lot of child nodes:

one

2 # constructor: when a class is instantiated, it is used to inject the result into the constructor

three

4 # idArg:ID parameter; marking the result as ID can help improve the overall performance

five

6 # arg: a common result injected into the constructor

seven

eight

9 # An ID result; marking as a result of ID can help improve overall performance

ten

11 # Common results injected into a field or JavaBean property

twelve

13 # an association of a complex type; many results will be packaged as this type

fourteen

15 # A collection of complex types

sixteen

17 # use the result value to decide which resultMap to use

eighteen

19 # result mapping based on certain values

twenty

21!

twenty-two

For example, if you want to map the fields of query results in hump style, you can define a resultMap to match the object and entity attributes one by one:

one

two

three

four

five

six

In SQL, you can directly use this resultMap as the return type:

one

2 select id,nick_name,gmt_created,gmt_modified from user where name = # {name}

three

The above example uses only the two most commonly used subtags in resultMap:,. There are many other tags can be written as advanced resultMap, because the length is long, and the article is designed to get started, so I will not give an example to explain each tag here, those who are interested can do it on their own Baidu.

6. A wave of operating principle and practical operation

After reading a wave of grammar, the brain seems to be in a state of incomprehension, as if talking about the use of configuration files and mapper. When we learn to write these mapper, how on earth should we use it?

At this point, we have to mention the running process of mybatis, let's first learn about several interfaces / classes provided by mybatis:

SqlSessionFactoryBuilder: the constructor of SqlSessionFactory, which is used to create SqlSessionFactory, using the Builder design pattern.

The SqlSessionFactory:SqlSession factory class, which creates SqlSession objects in the form of factories, adopts the Factory factory design pattern.

SqlSession: the interface that executes SQL

Because the operation of mybatis is so complex that it is far from being mastered in 30 minutes, it is only summarized here as the four largest processes:

Load configuration to create SqlSessionFacotry

Obtain SqlSession through sqlSessionFactory

SqlSession finds and converts Mapper

SqlSession executes SQL statements in mapper

Once we know the running process, we can do it for a while. Although these things are no longer visible to mainstream development frameworks, the author decides to abandon all the frameworks and build a blank project with maven to do it:

Create a maven project on idea and introduce mybatis and mysql dependencies into pom

This is simple and does not describe much.

The dependencies in pom are:

one

two

3 org.mybatis

4 mybatis

5 3.2.7

six

seven

8 mysql

9 mysql-connector-java

10 6.0.6

eleven

twelve

Create a configuration file called mybatis-config.xml in resources with the following contents:

one

two

four

five

six

seven

eight

nine

ten

eleven

twelve

thirteen

fourteen

fifteen

sixteen

seventeen

eighteen

nineteen

twenty

twenty-one

twenty-two

twenty-three

twenty-four

twenty-five

twenty-six

twenty-seven

twenty-eight

twenty-nine

Create a table structure:

1DROP TABLE IF EXISTS `user`

2CREATE TABLE `user` (

3 `id`int (11) NOT NULL AUTO_INCREMENT

4 `name` varchar (255) DEFAULT NULL

5 `gmt_ created` varchar (255) DEFAULT NULL

6 `gmt_ modified` varchar (255) DEFAULT NULL

7 PRIMARY KEY (`id`)

8) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8mb4

9Mutual-insert a number

10INSERT INTO `user`VALUES ('1customers,' hello mybatis', null, null)

Create the entity class of User.java under java (Note: to simplify the code, getter and serter have been removed and added by yourself in practice):

1public class User {

2 private Integer id

3 private String name

4 private String gmtCreated

5 private String gmtModified

6 / / getter and setter...

7}

Create a mapping class for UserMapper.java under java:

1public interface UserMapper {

2 User getUserByName (@ Param ("name") String name)

3}

Create a mapper folder under resources and a xml file for UserMapper under mapper:

one

two

three

four

5 select * from user where name = # {name}

six

seven

Start mybatis to execute SQL

According to the above running process, you can write a test class:

1 public static void main (String args []) {

2 try {

3 String resource = "mybatis-config.xml"

4// 1. Get the input stream of the configuration file

5 InputStream inputStream = Resources.getResourceAsStream (resource)

6// 2. Read the configuration file and create a SqlSessionFactory with SqlSessionFactoryBuilder

7 SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder () .build (inputStream)

8// 3. Get a SqlSession from SqlSessionFactory

9 SqlSession s = sqlSessionFactory.openSession ()

10// 4. Find Mapping SQL Fil

11 UserMapper mapper=s.getMapper (UserMapper.class)

12// 5. Perform CURD operation

13 User user=mapper.getUserByName ("hello mybatis")

fourteen

15 if (usernames are null) {

16 System.out.print ("query succeeded, my rank is:" + user.getName ())

17}

eighteen

19} catch (Exception e) {

20 e.printStackTrace ()

21}

22}

View the output:

1 query succeeded. My rank is: hello mybatis

The great task has been completed! Interested readers can write their own original mybatis test project according to the above process. If you have any questions or need source code, please follow the official account or add Wechat: sisi-ceo. Let's conquer the mountain of writing code together.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Database

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report