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

Example Analysis of mybatis attribute

2025-02-23 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Database >

Share

Shulou(Shulou.com)05/31 Report--

This article shares with you the content of a sample analysis of mybatis attributes. The editor thinks it is very practical, so share it with you as a reference and follow the editor to have a look.

Preface

MyBatis is based on the idea that the database structure is uncontrollable, that is, we want the database to follow the third normal form or BCNF, but the actual situation is contrary to our wishes, so the result set mapping is the means that MyBatis provides us with the transformation between ideal and reality, and resultMap is the configuration label of result set mapping.

Before diving into the ResultMap tag, we need to understand the process from the SQL query result set to the JavaBean or POJO entity.

From SQL query results to domain model entities

Get the ResultSet object by JDBC query

Traverses the ResultSet object and temporarily stores each row of data in the HashMap instance, using the field name or field alias of the result set as the key and the field value as the value

Instantiate the domain model through reflection based on the type attribute of the ResultMap tag

Populate the key-value pairs in the HashMap into the domain model instance according to the type attribute of the ResultMap tag and tag information such as id, result, etc., and return

1. ResultMap

1. Attribute description

The id attribute, the identification of the resultMap tag.

The type property, the fully qualified class name of the return value, or a type alias.

AutoMapping attribute, value range true (default) | false, sets whether to enable the automatic mapping function, which automatically finds the property name with the lowercase name of the field and calls the setter method. When set to false, the mapping relationship needs to be clearly indicated in the resultMap before the corresponding setter method is called.

2. Basic function: to establish the mapping relationship between SQL query result fields and entity attributes

Example 1: constructing a domain model through setter

Public class EStudent {private long id; private String name; private int age; / / getter,setter method / * must provide a no-argument constructor * / public EStudent () {}} SELECT ID, Name, Age FROM TStudent

Child element description:

Id element, which is used to set the mapping between primary key fields and domain model attributes

The result element, which is used to set the mapping between normal fields and domain model attributes

Id, result statement attribute configuration details:

The attribute description property needs to map to the attribute name of the JavaBean. The column name or label alias of the column data table. JavaType a full class name, or a type alias. If you match a JavaBean, the MyBatis usually detects it itself. Then, if you are mapping to a HashMap, you need to specify what the javaType wants to achieve. List of types supported by the jdbcType data table. This property is useful only when insert,update or delete is allowed for columns that are empty. This is required for JDBC, but not for MyBatis. If you are directly targeting JDBC encoding and have columns that allow null, you need to specify this. TypeHandler uses this property to override type handlers. This value can be a full class name or a type alias.

Example 2: constructing a domain model through a constructor

SELECT ID, Name, Age FROM TStudent

Child element description:

The constructor element that specifies that the domain model is instantiated using the constructor of the specified parameter list. Note: the order of its child elements must correspond to the order of the parameter list

IdArg child element, marking the input parameter as the primary key

Arg child element, marking the input parameter as a normal field (it is also possible for the primary key to use this child element)

3. One-to-one relationship, one-to-many relationship query

Note: when querying one-to-one or one-to-many relationships with nested results, the attribute / field mapping relationship must be explicitly set through the id or result tag under resultMap, otherwise only the last record will be returned when querying multiple records. Association federation

Union elements are used to handle "one-to-one" relationships. You need to specify the attribute of the mapped Java entity class, and the javaType of the attribute (usually MyBatis will recognize it). The column name of the corresponding database table. If you want to override the value of the result, you need to specify typeHandler.

Different situations need to tell MyBatis how to load a federation. MyBatis can be loaded in two ways:

Select: a SQL statement that executes another mapping returns a Java entity type. More flexible

ResultsMap: uses a nested result mapping to process querying result sets through join, mapping to Java entity types.

For example, a class corresponds to a head teacher.

First of all, define the head teacher private TeacherEntity teacherEntity in the class.

Using select to achieve federation

Example: there are the attributes of the head teacher in the class entity class, and the class teacher entity is mapped when a class entity is obtained by association.

This allows you to directly reuse the query teacher defined in the TeacherMapper.xml file according to its ID select statement. And you don't need to modify the written SQL statement, just modify the resultMap directly.

Part of the ClassMapper.xml file:

SELECT * FROM CLASS_TBL CT WHERE CT.CLASS_ID = # {classID}

Part of the TeacherMapper.xml file:

SELECT * FROM TEACHER_TBL TT WHERE TT.TEACHER_ID = # {teacherID}

Using resultMap to achieve federation

The same function as above, query the class, and inquire about the head teacher at the same time. Need to add resultMap in association (defined in teacher's xml file), write new sql (query class table left join teacher table), do not need teacher select.

Modify part of the ClassMapper.xml file:

SELECT * FROM CLASS_TBL CT LEFT JOIN TEACHER_TBL TT ON CT.TEACHER_ID = TT.TEACHER_ID WHERE CT.CLASS_ID = # {classID}

The teacherResultMap can be found in the TeacherMapper.xml file section above.

Collection aggregation

Aggregate elements are used to handle an one-to-many relationship. You need to specify the attribute of the mapped Java entity class, the javaType of the attribute (usually ArrayList), the type of the object in the list ofType (Java entity class), and the column name of the corresponding database table

In different cases, you need to tell MyBatis how to load a collection. MyBatis can be loaded in two ways:

1. Select: a SQL statement that executes another mapping returns a Java entity type. More flexible

2. ResultsMap: uses a nested result mapping to process query result sets through join, mapping to Java entity types.

For example, there are multiple students in a class.

First define the student list property in the class: private List studentList

Using select to implement aggregation

Usage is similar to federation, except that it is one-to-many, so lists are usually mapped. So here you need to define javaType as ArrayList, the type ofType of the objects in the list, and the statement name of the select that must be set (note that the select statement condition of the query student here must be the foreign key classID).

Part of the ClassMapper.xml file:

SELECT * FROM CLASS_TBL CT WHERE CT.CLASS_ID = # {classID}

Part of the StudentMapper.xml file:

WHERE ST.CLASS_ID = # {classID}

Using resultMap to implement aggregation

To use resultMap, you need to rewrite a sql,left join student table.

SELECT * FROM CLASS_TBL CT LEFT JOIN STUDENT_TBL ST ON CT.CLASS_ID = ST.CLASS_ID LEFT JOIN TEACHER_TBL TT ON CT.TEACHER_ID = TT.TEACHER_ID WHERE CT.CLASS_ID = # {classID}

The teacherResultMap can be found in the TeacherMapper.xml file section above. StudentResultMap can be found in the StudentMapper.xml file section above.

4. Dynamic mapping relation

The setting of dynamic mapping relation information can be realized through discriminator child elements (discriminator). Specific examples are as follows:

Public class EStudent {private long id; private String name; private String juniorHighSchool; private String seniorHighSchool; private int during; / / time spent in this school / / getter,setter method / * must provide a no-argument constructor * / public EStudent () {}}

Situation: query the seniorHighSchool information of the student information. If the during field value of the study time is 4, 5, 6, then the juniorHighSchool field is used as the seniorHighSchool information.

SELECT ID, Name, JuniorHighSchool, SeniorHighSchool, during FROM TStudent / / if this sentence is not added, when juniorHighSchool is assigned to the seniorHighSchool attribute, the juniorHighSchool attribute will be null / / form 1: set dynamic mapping information through resultType / / form 2: set dynamic mapping information through resultMap

Note: the resultType attribute of the case element of the discriminator child element and the type attribute of the resultMap element do not refer directly to the returned domain model type, but specify that the mapping relationship can be obtained according to the judgment condition, which can be rewritten by the id child element and the result child element.

5. Common attributes of id element, result element, idArg element, arg element, discriminator element

JavaType attribute: the fully qualified name, or alias, of the Java class

JdbcType attribute: JDBC type, processed when the column may be empty if the JDBC type is CUD

TypeHandler attribute: specifies the fully qualified class name or type alias of the type handler

Column property: specifies the field name or field alias of the SQL query result. ResultSet.getString (columnName) to be used for JDBC

Thank you for reading! This is the end of this article on "sample Analysis of mybatis attributes". I hope the above content can be of some help to you, so that you can learn more knowledge. if you think the article is good, you can share it out for more people to see!

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

Database

Wechat

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

12
Report