Introduction to mastery of mybatis combat tutorial (Classic)

What is mybatis

Mybatis is an excellent persistence layer framework that supports common SQL queries, stored procedures and advanced mapping. Mybatis eliminates almost all the manual setting of JDBC code and parameters and the retrieval of result sets. Mybatis uses simple XML or annotations for configuration and original mapping, and maps the interface and Java POJOs (plan old Java objects) into records in the database

Basic idea of ORM tool

Whether hibernate or mybatis are used, you can tell that they have one thing in common:

1. Get sessionfactory from configuration file (usually XML configuration file) 2. Generate session from sessionfactory 3 Complete the data addition, deletion, modification, query and transaction submission in the session 4. Close the session after running out. 5. There is a mapping configuration file between the Java object and the database, which is usually an XML file.

One of mybatis in action: building a development environment

Build the development environment of mybatis. Select eclipse J2EE version, MySQL 5.1, JDK 1.7, and mybatis 3.0 2.0. Jar package. These software tools can be downloaded from their official websites.

First, create a dynamic web project named mybaits

1. At this stage, you can directly establish a java project, but generally you are developing a web project. This series of tutorials is also web at the end, so you can establish a web project from the beginning. 2. Add mybatis-3.2 0-SNAPSHOT. jar,mysql-connector-java-5.1. 22-bin. Jar to the Lib directory of the web project 3. Create MySQL test database and user table. Note that UTF-8 coding is used here

Create a user table and insert a piece of test data

Program code

So far, the preliminary preparations have been completed. Now let's really configure the mybatis project.

1. Create two source directories in mybatis, namely Src_ user,test_ SRC, which is created as follows, right-click javaresource

2. Set mybatis configuration file: XML, in SRC_ Create this file in the user directory, as follows:

Program code

3. Create the Java class corresponding to the database and the mapping file

In SRC_ Create package under user: com yihaomen. mybatis. Model and create a user class under this package:

Program code

At the same time, create the user mapping file user xml:

Program code

These configuration files are explained below:

1.Configuration. XML is used by mybatis to establish sessionfactory. It mainly contains things related to database connection and the alias corresponding to Java class, such as < typealias alias alias = "user" type = "com. Yihaomen. Mybatis. Model. User" / > this alias is very important. You can use it in the mapping of specific classes, such as user The resulttype in XML corresponds to this. To maintain consistency, of course, the resulttype here has another separate definition method, which will be discussed later.

2. Configuration. The < mapper resource = "COM / yihaomen / mybatis / model / user. XML" / > in XML is the XML configuration file containing the classes to be mapped.

3. In user XML file mainly defines various SQL statements, parameters of these statements, and types to be returned

Start test

In test_ SRC source directory to create com yihaomen. Test this package and create a test class test:

Program code

Now run this program to get the query results. Congratulations, the environment is successfully built and configured. The next chapter will describe the interface based operation mode, addition, deletion, modification and query. The whole project directory structure is as follows:

Mybatis in action part 2: programming by interface

In the previous chapter, the eclipse and MySQL environment has been built, and a simple query has been implemented. Please note that this method uses the sqlsession instance to directly execute the mapped SQL statements:

In fact, there are simpler and better methods. Use the interface that reasonably describes the parameters and the return value of SQL statements (such as iuseroperation. Class), so that you can now use the simpler and safer code without string text and conversion errors. The following is the detailed process:

In SRC_ User source directory to create com yihaomen. mybatis. The inter package and establish the interface class iuseroperation. The contents are as follows:

Program code

Please note that there is a method name, selectuserbyid, which must be the same as user The ID of the select configured in XML corresponds to (< select id = "selectuserbyid")

Rewrite test code

The structure diagram of the whole project is now as follows:

Run the test program and you can see the results.

Mybatis in action part 3: add, delete, modify and query data

As mentioned earlier, programming in the way of interface. One thing to pay attention to in this way is. In user In the configuration file of XML, mapper namespace = "com. Yihaomen. Mybatis. Inter. Iuseroperation". The namespace is very important and cannot be wrong. It must be consistent with the package and interface defined by us. If there is inconsistency, errors will occur. This chapter mainly completes the following things on the basis of interface programming in the previous lecture:

1. Query data with mybatis, including list 2 Add data with mybatis 3 Update data with mybatis 4. Delete data with mybatis

Query data, as mentioned earlier, mainly depends on the query list

Query the list, that is, return the list. In our example, that is, list < user >, this way returns data in the user The returned type resultmap is configured in XML. Note that it is not resulttype, and the corresponding resultmap should be configured by ourselves

Program code

The statement to query the list is in user xml

Program code

Add a method in iuseroperation interface: public list < user > selectusers (string username);

Now do the test in the test class

Program code

You can now test in the main method:

Program code

As you can see, the results are successfully queried. If you are querying a single data, you can use the method used in the second lecture.

Adding data with mybatis

Add a method in iuseroperation interface: public void addUser (user);

In user Configuration in XML

Program code

Then write the test method in test:

Program code

Update data with mybatis

The method is similar. First, add a method in iuseroperation: public void addUser (user);

Then configure user xml

Program code

The general test methods of test class are as follows:

Program code

Delete data with mybatis

Similarly, iuseroperation addition method: public void deleteuser (int ID);

Configure user xml

Program code

Then write the test method in the test class:

Program code

In this way, all addition, deletion and modification queries are completed. Note that session should be called when adding, changing and deleting Commit(), so that you can really operate the database. Otherwise, it is not committed.

So far, you should know all the simple single table operations. Next time, I will talk about multi table joint query and result set selection.

Mybatis in action part 4: query related data

With the foundation of the previous chapters, some simple applications can be processed, but in actual projects, it is often associated table queries, such as many to one, one to many, etc. How are these queries handled? Let's talk about this. We first create an article table and initialize the data

Program code

You should find that the userid corresponding to these articles is 1, so you need the data with id = 1 in the user table user. You can modify it to meet your own conditions According to the rule of ORM, the table has been created, so an object must be corresponding to it, so we add a class of article

Program code

Notice how the article user is defined. It is a user object defined directly. Not int type.

Many to one implementation

Scenario: reading all articles published by a user. Of course, it still needs to be in user The select statement is configured in XML, but the key point is what kind of data the resultmap of the select corresponds to. This is the key point. Association should be introduced here. The definition is as follows:

Program code

After this configuration, you can see it by combining the select statement with the mapping corresponding to the resultmap. Use association to get the associated users, which is a many-to-one situation, because all articles belong to the same user.

There is another processing method, which can reuse the resultmap we defined earlier. We defined a resultlistuser earlier to see how to implement the second method:

Program code

The corresponding mapping in association can be extracted independently to achieve the purpose of reuse.

OK, now write the test code in the test class:

Program code

One thing is missing. We must add a method with the same ID and name corresponding to select in the iuseroperation interface:

Then run the test.

Mybatis in action part 5: integration with spring3

In this series of articles, we mentioned the examples of simply connecting the database with mybatis, then adding, deleting, modifying and querying, and multi table joint query. However, in actual projects, spring is usually used to manage the datasource. Make full use of spring's interface based programming and the convenience brought by AOP and IOC. There are many similarities between managing mybatis with spring and managing hibernate. Today's focus is on data source management and bean configuration.

You can download the source code and compare it. The source code does not have a jar package. It is too large and the space is limited There are screenshots. You can see which jar packages are used. The source code is at the end of this article

1. First, make a change to the previous engineering structure in SRC_ Create the config folder under the user source code directory, and the original mybatis configuration file configuration XML to this folder, and create the spring configuration file: ApplicationContext. XML in the config folder XML, the main configuration in this configuration file:

Program code

[b] The focus here is org mybatis. spring. Sqlsessionfactorybean and org mybatis. spring. mapper. Mapperfactorybean [b] implements the spring interface and generates objects. See the mybatis spring code for details. ( http://code.google.com/p/mybatis/ ), if you only use the fixed mode, this configuration is good.

Then write the test program

The corresponding results can be obtained by running

Drawing:

The jar packages used are as follows:

Mybatis in action part 6: integration with spring MVC

Previous articles have talked about the integration of mybatis and spring. But at this time, all projects are not web projects, although I have always created web projects. Today, we will directly integrate mybatis with spring MVC. The source code is downloaded at the end of this article The configuration mainly includes the following aspects

1. web. Configure the spring dispatcher servlet with XML, for example: MVC dispatcher 2 mvc-dispatcher-servlet. XML file configuration 3 spring applicationContext. XML file configuration (related to database, integrated with mybatis sqlsessionfact, scanning all mybatis mapper files, etc.) 4. Write controller class 5 Write page code

Let's have a rough image first. The whole drawing is as follows:

1. web. Configure the spring dispatcher servlet with XML, for example, MVC dispatcher

Program code program code

2. On the web Configure MVC dispatcher servlet. XML in the same directory XML file, the front part of this file name must be with you on the web The servlet name of the dispatcher servlet configured in XML corresponds to the servlet name The contents are as follows:

Program code

3. Configure the spring configuration file ApplicationContext. In the source directory config directory xml

Program code

I don't know why, once I use mappercannerconfigurer to scan all mapper interfaces, the database configuration datasource can't read the database Properties file. Error report: cannot load jdbc driver class' ${JDBC. Driverclassname} ', some people on the Internet say that spring 3.1 1 can be solved by sqlsessionfunctionbean injection, but I use spring 3.1 There is still a problem, so we have to configure the database connection information directly in the XML file.

4. Write controller layer

Program code

5. Page file:

Operation results:

And, of course, mybatis's configure The XML configuration file is similar to the one mentioned above. The only difference is that there is no need to configure the following: < mapper resource = "COM / yihaomen / mapper / user. XML" / >, all of which are imported by < property name = "mapperlocations" value = "classpath *: com / yihaomen / mapper / *. XML" / > when configuring sqlsessionfactory.

Database download:

Download spring MVC database test file

Mybatis in action part 7: realizing mybatis paging (source download)

In the previous article, we talked about the integration of mybatis and spring MVC, and made a list display to show all the article lists, but paging is not used. Paging is definitely required in actual projects. And it is physical paging, not memory paging. For physical paging schemes, different databases have different implementation methods. For MySQL, it is implemented by limit offset and PageSize. Oracle is implemented through rownum. If you are familiar with the operation of relevant databases, it is also a good extension. This paper takes MySQL as an example Take a look at the rendering first (the source code is available for download at the end of the article):

The simplest way to implement the physical paging of mybatis is to write directly in the SQL statement of your mapper, similar to the following:

Program code

Please note that the parametertype here is the parameter class you passed in, or map, which contains offset, PageSize, and other parameters you need. In this way, paging can certainly be realized. This is a simple way. But a more general way is to use the mybatis plug-in Reference to a lot of information on the Internet, mybatis plugin. Write your own plug-in

Program code

This plug-in has two auxiliary classes: pageinfo and reflecthelper. You can download the source code reference. After writing the plug-in, of course, you need to configure it in the configuration file of mybatis Configure this plug-in in XML

Program code

Please note that the plug-in defines a rule, that is, the ID of the SQL statement in the mapper must contain listpage to be intercepted. Otherwise, paging will not be processed

Now that the plug-in is written, you can write a method in the controller layer of spring MVC to test this page:

Program code

Then run the program and enter the paging page, and you can see the results:

To download the relevant jar packages, please download the jar in the example here http://www.yihaomen.com/article/java/318.htm (at the end of the article, download the source code. There is a jar package in it. Copy it to the Lib directory required in the above source code.)

In addition, you have to insert more records in the artilce table of the database mentioned above, and the paging effect will be better.

Mybatis in action part 8: mybatis dynamic SQL statement

The dynamic SQL statement of mybatis is based on ognl expression. It is convenient to implement some logic in SQL statements Generally speaking, the dynamic SQL statements of mybatis mainly fall into the following categories:

1. If statement (simple conditional judgment) 2 Choose (when, otherwise), which is equivalent to switch in Java language, is very similar to choose in JSTL 3. Trim (prefix, suffix, etc. are added to the content contained) 4 Where (it is mainly used to simplify the judgment of where conditions in SQL statements. It can intelligently process and or without worrying about redundant syntax errors) 5 Set (mainly used for updating) 6 Foreach (especially useful when implementing mybatis in statement queries)

These processing methods are described below

1. Mybaits if statement processing

Program code

The meaning of this statement is very simple. If you provide the title parameter, you must meet the title = #{Title}. Similarly, if you provide content and owner, they also need to meet the corresponding conditions, and then return all blogs that meet these conditions. This is a very useful function. In the past, when we used other types of frameworks or directly used JDBC, If we want to achieve the same selection effect, we need to spell SQL statements, which is extremely troublesome. Compared with the above dynamic SQL, it is much simpler

2.2. Choose (when), which is similar to choose in JSTL

Program code

The when element means that when the conditions in when are met, the content will be output. The effect is similar to the switch effect in Java. According to the order of conditions, when the conditions in when are met, choose will jump out, that is, only one of all when and otherwise conditions will be output. When all my conditions are not met, the content in otherwise will be output. So the meaning of the above sentence is very simple, when title= When null, and titlte = #{title} will be output, and the condition will not be judged. When title is empty and content= When null, and content = #{content} is output. When all conditions are not met, the content in otherwise is output.

3. Trim (prefix, suffix, etc. are added to the contents)

Program code

The main function of the trim element is to add some prefixes or suffixes to its contents. The corresponding attributes are prefix and suffix; You can overwrite some contents at the beginning of the content, that is, ignore it, or overwrite some contents at the end. The corresponding attributes are prefixoverrides and suffixoverrides; Because trim has such a function, we can also easily use trim to replace the function of where element

4. Where (is mainly used to simplify the judgment of where conditions in SQL statements, and can intelligently handle and or conditions

Program code

The function of the where element is to output a where where where is written to the where element. Another advantage is that you don't need to consider what the conditional output in the where element looks like. Mybatis will intelligently help you deal with it. If all the conditions are not met, mybatis will find out all the records. If the output starts with and, mybatis will ignore the first and, Of course, if it starts with or, mybatis will ignore it; In addition, you don't need to consider spaces in the where element. Mybatis will intelligently add them for you. As in the above example, if title = null and content= Null, the entire output statement will be select * from t_ Blog where content = #{content}, not select * from t_ Blog where and content = #{content}, because mybatis will intelligently ignore the first and or.

5. Set (mainly used for updating)

Program code

The set element is mainly used in update operations. Its main function is similar to that of the where element. It mainly outputs a set before the included statement. Then, if the included statement ends with a comma, the comma will be ignored. If the content contained in the set is empty, an error will occur. With the set element, we can dynamically update the modified fields

6. Foreach (especially useful when implementing mybatis in statement query)

Foreach is mainly used to build in conditions. It can iterate a set in SQL statements. The attributes of foreach elements mainly include item, index, collection, open, separator and close. Item indicates the alias of each element in the collection during iteration, index specifies a name, which is used to indicate the location of each iteration in the iteration process, open indicates what the statement starts with, separator indicates what symbol is used as the separator between each iteration, and close indicates what it ends with, When using foreach, the most critical and error prone attribute is the collection attribute, which must be specified, but the value of the attribute is different in different cases. There are three main cases: if the input is a single parameter and the parameter type is a list, The collection attribute value is list. If the input parameter is a single parameter and the parameter type is an array, the collection attribute value is array. If the input parameters are multiple, we need to encapsulate them into a map. Of course, a single parameter can also be encapsulated into a map. In fact, if you pass in parameters, In mybatis, it will also be encapsulated into a map. The key of the map is the parameter name, so at this time, the value of the collection attribute is the key of the incoming list or array object in its encapsulated map

1.1. Type of single parameter list

Program code

The value of the above collection is list, and the corresponding mapper is like this

Program code

Test code

2. Parameters of array type

Program code

Corresponding mapper

Program code

3. Map type parameters

Program code

Mapper should be such an interface:

Program code

Through the above methods, you can complete the general dynamic SQL statement of mybatis The most commonly used are if where foreach, which must be mastered

Mybatis in action part 9: use of mybatis code generation tool

Mybatis application requires a large number of configuration files. For hundreds of database tables, it is a terrible workload to configure them completely manually Therefore, the official mybatis also launched a jar package of mybatis code generation tool Today, I spent some time to preliminarily configure a usable version according to the doc document reference of mybatis generator. I also provide the source code for download. The mybatis code generation tool mainly has the following functions:

1. Generate POJO corresponding to database structure 2 If there is a primary key, it can match the primary key 3 If there is no primary key, you can use other fields to match 4 Dynamic select, update and delete methods 5 Automatically generate interfaces (that is, the previous Dao layer) 6 Automatically generate SQL mapper, add, delete, modify and query various statement configurations, including dynamic where statement configuration 7 Generate an example for reference

The detailed process is described below

1. Create a test project and configure mybatis code to generate jar package. Download address: http://code.google.com/p/mybatis/downloads/list?can=3&q=Product%3DGenerator MySQL driver download: http://dev.MysqL.com/downloads/connector/j/ I will also include these jar packages in the source code. You can download the source code at the end of the article for reference.

Build a dynamic web project with eclipse.

Unzip the downloaded mybatis-generator-core-1.3 2-bundle. Zip file, including two directories: one is the document directory docs, which mainly introduces how to use the code generation tool, and the other is the Lib directory, which mainly contains jar packages. Here we need mybatis-generator-core-1.3 2. Jar, this jar package Copy it to the webcontent / Web - inf / lib directory of the web project we just created Also put the MySQL driver jar package in this directory Because MySQL is used for testing

2. Create a test table in the database

Create a category table for testing in the mybatis database (if there is no mybatis database, you should create it based on the previous series of articles. You already have the mybatis database)

Program code

3. Configure the configuration file of mybatis code generation tool

In the created web project, create the corresponding package, such as: com yihaomen. Inter is used to store mybatis interface objects com. yihaomen. Mapper is used to store the mapping and SQL statements corresponding to SQL mapper com. yihaomen. Model is used to store the model corresponding to the database. Before using the mybatis code generation tool, these directories must be created. As a good application, the creation of these directories is also regular.

According to the mybatis code generation tool document, a configuration file is required, which is named mbgconfiguration XML is placed in the SRC directory The configuration file is as follows:

Program code

Use a main method to test whether mybatis can be used to generate the model, SQL mapper and other contents corresponding to the newly created 'category' table Create a com yihaomen. Test package, and create a test class genmain under this package:

Program code

So far, the eclipse project drawing should be as follows:

4. Run the main method of the test to generate mybatis related code

Run the main method in the genmain class and refresh the project. You will find that the corresponding files have been generated in their package directory, which fully conforms to the mybatis rules. The effect diagram is as follows:

5. Precautions

If you want to generate something like example, you need to remove it from < Table > < / Table >

Program code

This part of the configuration is used to generate an example. Generally speaking, it is not useful for the project

In addition, the generated SQL mapper is only used to add, delete, modify and query single tables. If you have multiple table join operations, you can configure them manually. If you call stored procedures, you also need to configure them manually At this time, the workload has been much less.

It's ok if you want to handle it on the command line

Program code

For example:

java -jar mybatis-generator-core-1.3. 2.jar -mbgConfiguration. xm -overwrite

In this case, the absolute path should be used In addition, mbgconfiguration The configuration of targetproject in the XML configuration file must also be an absolute path.

Use of mybatis sqlsessiondaosupport

The previous series of mybatis articles have basically talked about the operation of mybatis, but they are all based on the mapper implicit operation. In mybatis 3, the mapper interface seems to act as the Dao layer in ibatis 2. But in fact, if there is work that the mapper interface can't do, or you need more complex extensions, you need your own Dao layer In fact, mybatis 3 also supports Dao layer design, similar to ibatis 2 Let's introduce it

First create a com yihaomen. Dao's package Then create the interface userdao and the userdaoimpl that implements the interface

Program code

Program code

The executed SQL statement adopts the method of namespace + SQL statement ID, followed by parameters

Note that "sqlsessiondaosupport" is inherited. Sqlsessiontemplate can be obtained by using the method getsqlsession (), so that various SQL statements can be executed, similar to hibernate template, at least with the same idea

If you want to use autowire for integration with spring 3 MVC, add the annotation "@ repository" on the daoimpl class. In addition, you need to add < context: component scan base package = "com. Yihaomen. Dao" / > in the spring configuration file, so that autowire can be used for automatic injection where it needs to be called.

Of course, you can also create a service package according to the idea of the general program, and use the service to call the Dao layer. I didn't do it here, because it's relatively simple. When using a similar method and paying attention to automatic injection, you should also configure < context: component scan base package = "com. Yihaomen. Service" / > and so on.

Test in the controller layer, directly call Dao layer methods, and add methods to the controller:

Program code

In this way, the same result can be obtained, and the general program design method is satisfied The code structure is as follows:

The above is the relevant knowledge from the introduction to mastery (Classic) of mybatis practical tutorial introduced in this paper. I hope it will be helpful to you.

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>