mybatis plus 关联查询
Mybatis-plus-join是一个对Mybatis-plus进行功能升级的工具,它提供了更高效的开发方式,使用方法与Mybatis-plus一样,学习成本低。它增加了多表连接查询功能,摆脱了传统的xml模式多表连接的限制。
要使用Mybatis-plus-join,你可以按照以下步骤进行操作:
- 下载Mybatis-plus-join工具。
- 将Mybatis-plus-join打包成jar包,并将其引入到项目中。
- 在项目的pom.xml文件中配置Mybatis-plus-join的依赖。
- 准备使用Mybatis-plus-join的核心类MPJLambdaWrapper和MPJQueryWrapper。
- 使用MPJLambdaWrapper进行多表连接查询,可以使用示例中的3表查询和分页查询作为参考。
- 使用MPJQueryWrapper进行简单的3表查询和分页查询,但不建议过多使用该方式。
如果你想了解更多关于Mybatis-plus-join的使用方法,请参考Gitee上的文档。
mybatis plus 级联查询
Mybatis plus 是基于 Mybatis 的增强工具,其中包含了许多方便的功能。其中包括级联查询,又称之为关联查询。级联查询适用于多表查询的场景。例如,假设我们有两个表,一个是用户表,一个是订单表。如果我们想要查询某个用户所拥有的订单,我们就需要使用到级联查询。此时,我们通过 Mybatis plus 提供的 @TableField
注解来设置关系映射,例如:
@TableField(exist = false)
private List<Order> orders;
然后我们通过 @Select
注解编写查询 SQL 语句,例如:
@Select("SELECT * FROM user WHERE id = #{userId}")
@Results({
@Result(column = "id", property = "id"),
@Result(column = "name", property = "name"),
@Result(column = "age", property = "age"),
@Result(column = "id", property = "orders", many = @Many(select = "com.example.mapper.OrderMapper.findOrdersByUserId"))
})
User findUserByIdWithOrders(String userId);
通过在 @Result
中设置 many = @Many(select = "com.example.mapper.OrderMapper.findOrdersByUserId")
来实现关联查询,其中 findOrdersByUserId
是 OrderMapper
中的方法。这样,当我们查询某个用户时,就可以将其订单一并查询出来。
总之,Mybatis plus 提供了非常方便的级联查询功能,使我们能够更加方便地进行多表查询。
mybatis plus 实现关联查询
MyBatis-Plus-Join可以帮助我们轻松实现关联查询,具体步骤如下:
1.定义实体类之间的关系,例如:
public class User {
private Long id;
private String name;
private Integer age;
// 省略getter和setter方法
}
public class Order {
private Long id;
private Long userId;
private BigDecimal amount;
// 省略getter和setter方法
}
2.使用注解或XML配置关联查询,例如:
@TableName("user")
public class User {
@TableId
private Long id;
private String name;
private Integer age;
@TableField(exist = false)
private List<Order> orders;
// 省略getter和setter方法
}
@TableName("order")
public class Order {
@TableId
private Long id;
private Long userId;
private BigDecimal amount;
// 省略getter和setter方法
}
<!-- userMapper.xml -->
<select id="getUserWithOrders" resultMap="userMap">
SELECT u.*, o.id AS order_id, o.amount
FROM user u
LEFT JOIN order o ON u.id = o.user_id
WHERE u.id = #{id}
</select>
<resultMap id="userMap" type="com.example.User">
<id column="id" property="id"/>
<result column="name" property="name"/>
<result column="age" property="age"/>
<collection property="orders" ofType="com.example.Order">
<id column="order_id" property="id"/>
<result column="amount" property="amount"/>
</collection>
</resultMap>
3.调用关联查询方法,例如:
User user = userMapper.getUserWithOrders(1L);
List<Order> orders = user.getOrders();
相关推荐
















