mybatis 关联查询
时间: 2023-09-21 19:04:28 浏览: 116
mybatis 关联查询完整代码
4星 · 用户满意度95%
MyBatis is a popular Java-based persistence framework that provides support for object-relational mapping (ORM) and simplifies database access. It allows you to perform various types of queries, including association or join queries, to retrieve related data from multiple tables.
In MyBatis, you can achieve association or join queries using the "resultMap" feature. Here's an example of how you can perform a simple association query:
1. Define the result map:
```xml
<resultMap id="PersonResultMap" type="Person">
<id property="id" column="person_id" />
<result property="name" column="person_name" />
<association property="address" javaType="Address">
<id property="id" column="address_id" />
<result property="street" column="street" />
<result property="city" column="city" />
</association>
</resultMap>
```
2. Write the SQL query with JOIN:
```xml
<select id="getPersonWithAddress" resultMap="PersonResultMap">
SELECT p.id AS person_id, p.name AS person_name,
a.id AS address_id, a.street, a.city
FROM person p
JOIN address a ON p.address_id = a.id
WHERE p.id = #{personId}
</select>
```
3. Use the defined resultMap in your mapper interface:
```java
@Select("getPersonWithAddress")
@ResultMap("PersonResultMap")
Person getPersonWithAddress(int personId);
```
In this example, the query retrieves a person and their associated address by performing a join between the "person" and "address" tables. The result is mapped to the `Person` object using the defined resultMap.
You can customize the association mapping based on your specific database schema and entity classes. MyBatis provides flexibility in handling various types of associations, including one-to-one, one-to-many, and many-to-many relationships.
阅读全文