mybatis 一对多 collection
时间: 2023-11-07 09:17:25 浏览: 41
MyBatis is a popular Java-based persistence framework that provides support for mapping SQL queries to Java objects. When it comes to handling one-to-many relationships in MyBatis, you can use the "collection" element.
To map a one-to-many relationship using the "collection" element, you need to have two classes/entities involved - one representing the parent object and another representing the child objects. Let's assume we have two classes: "Parent" and "Child".
In the Parent class, you can define a collection property of type List or Set to represent the child objects. For example:
```java
public class Parent {
private int id;
private List<Child> children;
// Getters and setters
}
```
In the Child class, you can define the properties representing the child object's attributes:
```java
public class Child {
private int id;
private String name;
// Getters and setters
}
```
To map the one-to-many relationship between Parent and Child, you can use the MyBatis XML mapping file. Here's an example:
```xml
<resultMap id="parentResultMap" type="Parent">
<id property="id" column="parent_id" />
<collection property="children" ofType="Child">
<id property="id" column="child_id" />
<result property="name" column="child_name" />
</collection>
</resultMap>
<select id="getParentWithChildren" resultMap="parentResultMap">
SELECT p.id as parent_id, c.id as child_id, c.name as child_name
FROM parents p
JOIN children c ON p.id = c.parent_id
</select>
```
In this example, we define a resultMap called "parentResultMap" for the Parent class. Inside the resultMap, we use the collection element to map the children property to the Child class. The "ofType" attribute specifies the type of the child objects.
The select statement retrieves the parent and child information using a join between the parents and children tables.
With this setup, when you execute the "getParentWithChildren" query, MyBatis will automatically populate the Parent object with a List of Child objects based on the one-to-many relationship defined in the mapping.
This is just a basic example of handling one-to-many relationships using collections in MyBatis. You can customize it further based on your specific requirements.