MyBatis annotation configuration in Spring boot with detailed (1)

Source: Internet
Author: User

Prior to the integration of MyBatis in spring boot, the use of the annotated configuration, I believe many people still prefer this elegant way, but also received a lot of readers friends feedback and problems, mainly focused on the use of annotations for various scenarios, the following examples of several common cases illustrate usage.

Before you do the following example, prepare a project that integrates MyBatis, see Spring Boot Integration MyBatis, or use the Consolidated sample: Chapter3-2-7.

Method of transmitting parameters

The insert operation implemented in the previous article is implemented by several different methods of communication.

@Insert ("Insert into USER (NAME, age) VALUES (#{name}, #{age})") int Insert (@Param ("name") String name, @Param ("Age"  Integer age); This is a good way to understand that the name defined in the @Param corresponds to the #{name},age in SQL that corresponds to #{age} in SQL
Using map
The following code, through the Map object, is used as a container for passing parameters: @Insert (Insert into USER (NAME, age) VALUES (#{name,jdbctype=varchar}, #{age,jdbctype=integer})int insertbymap (map<string, object> Map);

For the parameters required in the INSERT statement, we only need to fill in the map with the same name, as shown in the following code:

New Hashmap<>(); Map.put ("name""CCC"); Map.put ("Age"); Usermapper.insertbymap (map);
Working with objects

In addition to the map object, we can use the normal Java object directly as the parameter of the query, for example, we can use the user object directly:

@Insert ("Insert into USER (NAME, age) VALUES (#{name}, #{age})")int Insertbyuser (user user);

In such a statement #{name} , the #{age} and attributes in the user object correspond to each other name age .

Change and delete

MyBatis provides different annotations for different database operations to configure, as demonstrated in the previous example @Insert , following a basic set of additions and deletions for the user table as an example:

 Public Interfaceusermapper {@Select ("SELECT * from user WHERE name = #{name}") User findbyname (@Param ("name") String name); @Insert ("INSERT into user (name, age) VALUES (#{name}, #{age})")intInsert (@Param ("name") String name, @Param (" Age") (Integer age); @Update ("UPDATE user SET Age=#{age} WHERE Name=#{name}")voidUpdate (user user), @Delete ("DELETE from user WHERE ID =#{id}")voidDelete (Long id);}

After the completion of a set of additions and deletions, we can try the following unit tests to verify the correctness of the above operation:

@RunWith (Springjunit4classrunner.class) @SpringApplicationConfiguration (Classes= Application.class) @Transactional Public classapplicationtests {@AutowiredPrivateusermapper usermapper; @Test @rollback Public voidTestusermapper () throws Exception {//Insert a piece of data and select it to verifyUsermapper.insert ("AAA", -); User u= Usermapper.findbyname ("AAA"); Assert.assertequals ( -, U.getage (). Intvalue ());//update a piece of data and select to verifyU.setage ( -); usermapper.update (U); u= Usermapper.findbyname ("AAA"); Assert.assertequals ( -, U.getage (). Intvalue ());//Delete this data, and select VerifyUsermapper.delete (U.getid ()); U= Usermapper.findbyname ("AAA"); Assert.assertequals (NULL, u);}}
Returns the binding of the result

For the increase, delete, change the operation of the relatively small change. And for the "check" operation, we often need to do multi-table association, summary calculation, etc., then for the results of the query is often no longer a simple entity object, often need to return a different than the database entity wrapper class, then for such cases, you can use @Results and @Result annotations to bind, Specific as follows:

  @Results ({@Result Property  =  " name   ", column =  name   "  ), @Result (Property  =  " age   ", column = "  age   "   select name, age from user  "  ) List  <User> findAll (); 

In the preceding code, the property attribute in the @Result corresponds to the member name in the user object, and column corresponds to the field name of the Select. The id attribute is intentionally not detected in this configuration, only the name and age objects in the user counterpart are mapped, so that the ID identified is null by the following unit test, and the other property is not null:

@Test @rollback  Public void Testusermapper () throws Exception {List<User> userlist = usermapper.findall ();  for (User user:userlist) {assert.assertequals (null, User.getid ()); Assert.assertnotequals (null, User.getname ());}}
Postscript

This article focuses on several of the most commonly used methods, and the use of additional annotations can be found in the documentation: http://www.mybatis.org/mybatis-3/zh/java-api.html

This sample full code: CHAPTER3-2-8

MyBatis annotation configuration in Spring boot with detailed (1)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.