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.