Mybatis solution when the entity attribute is inconsistent with the database field

Source: Internet
Author: User

When using MyBatis, MyBatis the properties of the corresponding entity class based on the field of the database, and injects the attributes through the set method.
We can test the set method of the entity class and test it as follows:

The results of the implementation are as follows:

Description: MyBatis is injected using the Set method based on the same property and field name

What if the attribute name of the entity class is not the same as the field name of the database?

We change the attribute name of the entity class as follows:

Executed again, the results are as follows:

It can be found that there is no injection through the set method, and that the value of the username of the user object is null, which means that mybatis is indeed injected by the same field name and property name.
What if we don't want to use the same field name as the database as the Entity property name? method One: By modifying the SQL statement

To modify the SQL statement in the mapping file:

Test results:

Note: You can find that the MyBatis is based on the queried field name to find the entity class relative properties to inject. Method Two: Add an association map

Include the associated mappings in the mapping file as follows:

Note:

Note:

Modify the previous SQL statement

The test results are as follows:

Both methods resolve the problem of inconsistent entity attributes and database fields, but generally use the second one to resolve the problem by adding an association map.

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.