Mybatis implements one-to-one association mapping instance code
preface
In the objective world, objects rarely exist alone, such as the relationship between classes and students, the relationship between students and courses, and their instances can access each other, which is the correlation. Mybatis association mapping can greatly simplify the access of persistence layer data. The classification of association relations is as follows:
We first draw a simplified E-R diagram to represent the three relationships.
The above figure shows three relationships:
introduction
In actual project development, there is often a one-to-one relationship. For example, a person corresponds to an ID card information, which is a one-to-one relationship. Here is a simple example
example:
1. I will omit the process of creating a table, mainly a person table and an IDcard table. See step 2pojo class attributes for related attributes;
2. Create a person object and an IDcard object:
mybatis/pri/xiaoyang/otot/pojo/IDCard. java
mybatis/pri/xiaoyang/otot/pojo/Person. java
3. Next comes the XML Mapping File:
mybatis/pri/xiaoyang/otot/mapper/IDCardMapper. xml
mybatis/pri/xiaoyang/otot/mapper/PersonMapper. xml
Note: in person mapper XML defines a < select / > tag. The SQL statement of the tag queries the unique person information according to the primary key field of the person table. Because the person table is associated with the IDcard table, a mapping object with the resultmap value of personmap is returned. Personmap uses the < Association / > tag to map a one-to-one association relationship. The attribute select in the tag indicates that the selectidcardbyid defined in idcardmapper will be executed with the attribute value "card_id" of column as a parameter to query the corresponding IDcard data, and the queried data will be encapsulated in the "card" object of property attribute value.
summary
The above is the whole content of this article. I hope the content of this article has a certain reference value for your study or work. If you have any questions, you can leave a message. Thank you for your support for programming tips.