What is the method for adding multiple data in MyBatis?
In MyBatis, a one-to-many relationship can be achieved by using two different methods to insert data.
- To use nested queries:
Firstly, define two corresponding query statements in the mapping file, one to query data from the main table, and one to query data from the subordinate table. Then, in the query statement of the main table, use a nested query to incorporate the query statement of the subordinate table, establishing a relationship between the primary key of the main table and the foreign key of the subordinate table. Finally, call the query statement of the main table within the business logic. MyBatis will automatically execute the nested query and map the results to nested objects. - The sample code is shown below:
-
- Invoke a query statement within the business logic.
- Retrieve the data from the mainTable using the selectOne method with the parameter “getMainTableData” and the specified ID.
- MyBatis will automatically execute nested queries and map the results to nested objects.
- One alternative method is to use the association and collection tags in MyBatis. In the mapping file, the association tag defines the relationship between the main table and the secondary table, while the collection tag defines a collection for the secondary table. When querying the main table in the business logic, MyBatis will automatically execute the association query and map the results to associated objects.
- The sample code is as follows:
- Query statement for the main table:
Mapping for the main table:
Mapping for the sub table:
- Call the query statement in the business logic.
- Retrieve data from the main table using the specified ID and assign it to the MainTable object.
- MyBatis will automatically perform associated queries and map the results to associated objects.