Spring Boot Learning (ix) using MyBatis annotation configuration in spring boot

Source: Internet
Author: User
Tags assert rollback

The previous blog in the Spring Boot integration MyBatis, using the annotated configuration, I believe many people still prefer this elegant way, today we look at spring boot using mybatis annotation configuration detailed;

An example of modifying the previous project;

method of transmitting parameters

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

using @param

In the previous consolidation example, we have used this simplest way of communicating the parameters as follows:

@Insert ("Insert into USER (NAME, age) VALUES (#{name}, #{age})")

int Insert (@Param ("name") String name, @Param ("age") of Integer Age);

This is a good way to understand that the name defined in the @Param corresponds to the #{name},age in SQL #{age}.

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:

map<string, object> map = 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);


The #{name}, #{age} In this statement corresponds to the name and age property in the user object.

Change and delete

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

Public interface Usermapper {



@Select ("SELECT * from user WHERE name = #{name}")

user Findbyname (@Param ("name") St ring name);



@Insert ("INSERT into user (name, age) VALUES (#{name}, #{age})")

int Insert (@Param (' name ') String name, @Param ("age") Integer age);



@Update ("Update user SET Age=#{age} WHERE name=#{name}")

void Update (user user);



@Delete ("Delete from user WHERE ID =#{id}")

void Delete (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

class Applicationtests {



@Autowired

private usermapper usermapper;



@Test

@Rollback public

void Testusermapper () throws Exception {

//insert a piece of data and select out to verify

Usermapper.insert ("AAA");

User u = usermapper.findbyname ("AAA");

Assert.assertequals (U.getage (). Intvalue ());

Update a data and select to verify

u.setage (+);

Usermapper.update (u);

U = usermapper.findbyname ("AAA");

Assert.assertequals (U.getage (). Intvalue ());

Delete this data and select Verify

usermapper.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 and other operations, then for the results of the query is often no longer a simple entity object, often need to return a different from the database entity wrapper class, then for such cases, You can bind by @results and @result annotations, as follows:

@Results ({

@Result (property = "Name", column = "name"),

@Result (property = ' age ', column = ' age ')

})

@Select ("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 ());

}

}


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

We look at screenshots:


Database screenshot:


We have finished Yo! You can try it!

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.