[MyBatis series ②] Two ways of Dao layer development

Table of contents

1. Traditional development

1.1, code

1.2. Existing problems

2. Agent development

2.1. Development Specifications

2.2, code


⭐mybatis series ①: add, delete, modify and check

1. Traditional development

In the traditional mybatis development, the corresponding interface is implemented in the data access layer, and the sql statement configured in the corresponding mapping file is found in the form of "namespace.id" in the implementation class, while the agent development is to find the corresponding interface type. execution method.

1.1 , code

Mapping file configuration:

The Dao layer code is as follows:

1.2 、Existing problems

The previous code is the basic usage method, and it also has hard-coded problems, as follows:

The parameter passed by calling the selectList() method here is the namespace.id value in the mapping configuration file

It is not convenient to write in this way for later maintenance. If you use the Mapper proxy method, there is no hard-coding problem:

From the above description, we can see the purpose of the Mapper proxy method:

Solve the hard coding in the native way

Simplify post-execution SQL

The Mybatis official website also recommends using the Mapper proxy. The picture below is the picture of the official website:

2. Agent development

The development of the DAO layer is realized by the agent development method of Mybatis, which is the mainstream of the enterprise.

The Mapper interface development method only requires programmers to write the Mapper interface (equivalent to the Dao interface), and the Mybatis framework creates the dynamic proxy object of the interface according to the interface definition. The method body of the proxy object is the same as the above Dao interface implementation class method.

2.1 , development specification

Mapper interface development needs to follow the following specifications:

1. The namespace in the Mapper.xml file is the same as the fully qualified name of the mapper interface

2. The Mapper interface method name is the same as the id of each statement defined in Mapper.xml

3. The input parameter type of the Mapper interface method is the same as the parameterType of each sql defined in mapper.xml

4. The output parameter type of the Mapper interface method is the same as the resultType of each sql defined in mapper.xml

Illustration:

2.2 , code

The following are the specific simulated MVC steps:

The corresponding directory is as follows:

①Control layer: use the test framework to do a simple simulation:

②Business layer:

③Data access layer:

④ Write the mapping file:

⑤Load the mapping file in the configuration file:

⑥Test:

The result is as expected!

        

Guess you like

Origin blog.csdn.net/qq_60735796/article/details/132478391