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

The ways, advantages and disadvantages of mapping xml and annotations in Mybatis

2025-01-18 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

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

This article mainly introduces "the ways, advantages and disadvantages of mapping xml and annotations in Mybatis". In daily operation, I believe that many people have doubts about the ways, advantages and disadvantages of mapping between xml and annotations in Mybatis. The editor consulted all kinds of materials and sorted out simple and easy-to-use methods of operation. I hope it will be helpful to answer the doubts of "the way and the advantages and disadvantages of mapping xml and annotations in Mybatis". Next, please follow the editor to study!

MyBatis provides both XML configuration and annotation configuration. Today, let's talk about how these two ways are realized.

The real power of MyBatis lies in its statement mapping, which is its magic. Because of its extraordinary power, the mapper's XML file is relatively simple. If you compare it with JDBC code with the same functionality, you will immediately find that you have saved nearly 95% of the code. MyBatis is committed to reducing usage costs and allowing users to focus more on SQL code.

From the official website.

Mybatis maps nine top-level elements:

Mapper: the root node of the mapping file, with only one attribute namespace (namespace), for the following purposes:

Used to distinguish between different mapper, globally unique.

Bind DAO interface, that is, interface-oriented programming. When you bind an interface, you do not need to write the implementation class of this interface. You will find the corresponding mapper configuration through the fully qualified name of the interface to execute the SQL statement. Therefore, the naming of namespace must write the fully qualified name of the interface.

Cache: configures the cache for a given namespace.

Cache-ref: references the cache configuration from other namespaces.

ResultMap: used to describe the correspondence between database result sets and objects.

Sql: SQL blocks that can be reused or referenced by other statements. Usually store some common SQL.

Insert: map insert statement.

Update: update the mapping statement.

Delete: delete the mapping statement.

Select: mapping query statement.

Xml mode

Nine top-level mapping elements correspond to tags:

Select detailed explanation

As you can see, there are still many options behind. Here is an explanation of each item on the official website.

Select use case

Select * from m_user where id = # {id}

The id must be unique in the Mapper and can be used to reference the statement. The id must correspond to only the methods in the XxxMapper.java. It must be one-to-one.

Return type: User type, resultType: the query statement returns the fully qualified name or alias of the result type. Aliases are used in the same way as parameterType.

Parameters: shaping that represents the type and fully qualified name or alias of the parameters passed in by the query statement. Basic and complex data types are supported.

# {Parameter name}: tells MyBatis that the generated PreparedStatement parameter is identified as'? 'relative to the JDBC.

The alias and parameter mapping types are as follows:

Returns the use of aliases in the type, note:

If it is our entity class, then resultType cannot use aliases, only resultMap can use aliases.

Select * from m_user where id = # {id}

But if you use the above mapping table, you can also use aliases directly.

There are two pieces of data in the database

UserMapper.xml

Select count (1) from m_user

UserMapper.java

Import com.tian.mybatis.entity.User; public interface UserMapper {int countUser ();}

Test class:

Public class MybatisApplication {public static final String URL = "jdbc:mysql://localhost.com:3306/mblog?useUnicode=true"; public static final String USER = "root"; public static final String PASSWORD = "123456"; public static void main (String [] args) {String resource = "mybatis-config.xml"; InputStream inputStream = null; SqlSession sqlSession = null; try {inputStream = Resources.getResourceAsStream (resource) / / Factory mode SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder () .build (inputStream); / / get sql operation session sqlSession = sqlSessionFactory.openSession (); / / construct the object (special here, the way the object is constructed will be specially shared later) UserMapper userMapper = sqlSession.getMapper (UserMapper.class) / / query statistics System.out.println (userMapper.countUser ());} catch (Exception e) {e.printStackTrace ();} finally {try {inputStream.close ();} catch (IOException e) {e.printStackTrace () } sqlSession.close ();}

Output: 2

What if the field name in the database table does not match the field name in our entity?

In actual development, this kind of common is inevitable. We can use the following way to solve the problem.

Entity class User

Public class User {private Integer id; private String userName; private Integer age; / / set get toString method will not be posted here.

Contents of UserMapper.xml file:

Select * from m_user where id = # {id}

Type: corresponds to our entity class, full path name.

Id: can be understood as an alias.

Id: unique identification, this id value is used for references to the resultMap attribute of the select element.

Column: corresponds to the field name in our database table.

Property: corresponds to the attribute of our entity class, such as the attribute userName in User, which corresponds to name in the database table m_user.

Result: identifies some simple attributes, where the column attribute represents the field name of the database and property represents that the queried field name is mapped to an attribute of the entity class.

Continue to test using our previous test class:

UserMapper userMapper = sqlSession.getMapper (UserMapper.class); System.out.println (userMapper.selectUserById (1))

Output: User {id=1, userName='tian', age=22}

Note: the get set and toString () methods of entity classes are omitted here. I hope that if you are using them, it is easy to use shortcut keys.

ResultType and resultMap are mentioned above, so what's the difference between them?

What's the difference between resultType and resultMap?

ResultType: directly represents return types, including basic and complex data types.

ResultMap: a reference to an external resultMap definition, which, through the id of the corresponding external resultMap, indicates which resultMap the result is mapped to. It is generally used in cases where field names and attribute names are inconsistent, or complex federated queries are required to freely control the mapping results.

The connection between the two

When querying, each field is placed in a Map, and when the query element returns an attribute of resultType, the key-value pair is assigned to the specified attribute. In fact, the return type of each query mapping in MyBatis is resultMap, but when we use resultType, we will automatically assign the corresponding value to the specified object property. When using resultMap, because map is not a good representation of the domain, we will further convert it to the corresponding entity object. ResultMap mainly works on complex federated queries.

Automatic mapping level of resultMap: the default level is PARTIAL, and you can also change the value in settings.

Note: resultType and resultMap are essentially the same, both are Map data structures, but they cannot exist at the same time.

Addition, deletion and modification case

Insert

As you can see from this, there is no return value type for us to specify about adding insert. The int type is returned by default.

INSERT INTO m_user (`name`, age) VALUES (# {userName}, # {age})

Corresponding to the methods in Mapper

Int insert (User user)

Another update is similar to delete, so there is no need to demonstrate it one by one.

Annotation mode

Nine top-level mapping element corresponding annotations:

The other annotations are used in conjunction with nine annotations.

Select comments

Delete the local UserMapper.xml, then change the mybatis-config.xml and comment out the UserMapper.xml in it. Add

UserMapper.java add comment

Public interface UserMapper {@ Select ("select * from m_user where id = # {id}") User selectUserById (Integer id);}

Test again

User user = sqlSession.selectOne ("com.tian.mybatis.mapper.UserMapper.selectUserById", 1); System.out.println (user)

Output:

User {id=1, userName='null', age=22}

From the output, we can see that userName is null, which is also caused by inconsistency with the field name in the database table sink, so how to deal with it?

To do this, add another note:

Public interface UserMapper {@ Select ("select * from m_user where id = # {id}") @ Results (@ Result (column = "name", property = "userName")) User selectUserById (Integer id);}

Output:

User {id=1, userName='tian', age=22}

This is the way to deal with the difference between the entity attribute name and the database table field name when using annotations.

Insert, update, and delete can also be done with annotations.

@ Insert, @ Update, and @ Delete are matched with corresponding SQL statements.

Can annotations and xml coexist?

Update m_user `name` = # {userName}, gender = # {gender}, age = # {age}, where id=# {id}

At the same time, add comments to the methods in UserMapper.java.

@ Update ("update m_user set `name` = # {userName}, gender = # {gender}, age = # {age} where id=# {id}") int updateAuthorIfNecessary (User user)

The return is abnormal when you have a neutron star again:

Nested exception is java.lang.IllegalArgumentException: Mapped Statements collection already contains value for com.tian.mybatis.mapper.UserMapper.updateAuthorIfNecessary. Please check file [D:\ workspace\ my_code\ mybatis\ target\ classes\ mapper\ UserMapper.xml] and com/tian/mybatis/mapper/UserMapper.java (best guess)

Roughly, it already exists, that is, you can't use xml and annotations at the same time. Choose one of the two.

Xml can be used in combination with annotations, but make sure that there are no xml and annotations in the same method.

Suggestion

Annotations can be used for simple sql processing and xml for complex sql. But the actual work depends on whether this is standardized in the project you are waiting for.

There are only three types of projects:

1. All must use xml mode.

two。 All must be annotated.

3. You can use both xml and annotations.

Advanced mapping

Association

Maps to one of the complex "data type" attributes of JavaBean and handles only one-to-one associations.

Attribute node of association:

Property: the entity object attribute name of the mapping database column.

JavaType: the full java class name and qualified name. The type of attribute mapped by propert.

Child element

Id: it is generally a mapping primary key, which can improve performance.

Result:

Column: the field name of the mapped database.

Property: the entity object attribute corresponding to the mapped data column.

Collection

Maps to a complex "data type" property of JavaBean, which is a list of collections that handle one-to-many relationships.

OfType: the full Java class name and qualified name. The type of attribute mapped by propert.

The rest is basically the same as association.

Both association and collection have delayed loading capabilities.

Delayed loading: first query from a single table, and then check the associated tables when needed, which greatly improves the performance of the database, because relatively speaking, single-table queries are faster than multi-table queries.

Relationship between xml and annotations

Above we have talked about the implementation of two ways, let's compare the relationship between the two ways:

Xml mode

There must be a XxxMapper.xml corresponding to it, the method name corresponds to the id in the xml, and both the method input parameters and the method output parameters must correspond, which is prone to problems. Some of our developers can use code generators to generate code, but some of them have to be handwritten, and some companies also require them to be handwritten, so we need to pay attention to it here.

Annotation mode

You don't need XxxMapper.xml files, you just need to annotate the methods in the corresponding XxxMapper.java, but there are holes here. After all, we put sql in our Java code.

Advantages and disadvantages

Xml mode: added xml files, troublesome modification, uncertain conditions (ifelse judgment), error-prone, special escape characters such as greater than less.

Annotation method: complex sql is not easy to use, it is not convenient to collect sql, it is not convenient to manage, and the modification needs to be recompiled

At this point, the study of "the ways, advantages and disadvantages of mapping xml and annotations in Mybatis" is over. I hope to be able to solve your doubts. The collocation of theory and practice can better help you learn, go and try it! If you want to continue to learn more related knowledge, please continue to follow the website, the editor will continue to work hard to bring you more practical articles!

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

Development

Wechat

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

12
Report