MyBatis 实现两表关联查询:详细步骤和示例
MyBatis 实现两表关联查询的步骤如下:
-
编写 Mapper.xml 文件,定义两个表的查询语句。
-
在 Mapper.xml 文件中,使用
<resultMap>标签定义结果集映射。在结果集映射中,使用<association>或<collection>标签定义两个表之间的关联关系。 -
在 Mapper 接口中定义查询方法,并使用
@Results注解指定结果集映射。 -
在 Service 层调用 Mapper 接口中的查询方法。
-
在 Controller 层中将查询结果返回给前端页面。
下面是一个示例:
- 定义 Mapper.xml 文件
<!-- 查询用户信息 -->
<select id="getUserInfo" resultType="User">
SELECT * FROM user WHERE id = #{id}
</select>
<!-- 查询用户的订单信息 -->
<select id="getUserOrders" resultMap="UserOrderMap">
SELECT * FROM orders WHERE user_id = #{userId}
</select>
<!-- 定义结果集映射 -->
<resultMap id="UserOrderMap" type="User">
<id property="id" column="user_id"/>
<result property="name" column="user_name"/>
<collection property="orders" ofType="Order">
<id property="id" column="order_id"/>
<result property="name" column="order_name"/>
<result property="price" column="order_price"/>
</collection>
</resultMap>
- 定义 Mapper 接口
public interface UserMapper {
// 查询用户信息
@Select("SELECT * FROM user WHERE id = #{id}")
@Results({
@Result(property = "id", column = "id"),
@Result(property = "name", column = "name"),
@Result(property = "orders", column = "id", javaType = List.class,
many = @Many(select = "getUserOrders"))
})
User getUserInfo(int id);
// 查询用户订单信息
@Select("SELECT * FROM orders WHERE user_id = #{userId}")
List<Order> getUserOrders(int userId);
}
- 在 Service 层调用 Mapper 接口
@Service
public class UserServiceImpl implements UserService {
@Autowired
private UserMapper userMapper;
@Override
public User getUserInfo(int id) {
return userMapper.getUserInfo(id);
}
}
- 在 Controller 层中将查询结果返回给前端页面
@Controller
public class UserController {
@Autowired
private UserService userService;
@GetMapping("/user/{id}")
public String getUserInfo(@PathVariable("id") int id, Model model) {
User user = userService.getUserInfo(id);
model.addAttribute("user", user);
return "user";
}
}
在前端页面中可以使用 thymeleaf 模板引擎来显示查询结果,示例代码如下:
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<title>User Info</title>
</head>
<body>
<h1>User Info</h1>
<p>ID: <span th:text="${user.id}"/></p>
<p>Name: <span th:text="${user.name}"/></p>
<h2>Orders</h2>
<table>
<thead>
<tr>
<th>ID</th>
<th>Name</th>
<th>Price</th>
</tr>
</thead>
<tbody>
<tr th:each="order : ${user.orders}">
<td th:text="${order.id}"/>
<td th:text="${order.name}"/>
<td th:text="${order.price}"/>
</tr>
</tbody>
</table>
</body>
</html>
以上就是 MyBatis 实现两表关联查询的完整流程。
原文地址: https://www.cveoy.top/t/topic/n6rK 著作权归作者所有。请勿转载和采集!