一、MyBatisPlus介绍
MyBatisPlus是一个基于MyBatis的增强工具,提供了许多实用的功能,如分页、自定义SQL、代码生成等。MyBatisPlus还提供了一些自动化的功能,如自动填充、逻辑删除等,方便开发人员使用。
二、表之间的关联查询
在数据库开发中,表之间经常存在关联关系,例如一个用户有多个订单,这时就需要进行关联查询。MyBatisPlus提供了多种方式实现表之间的关联查询。
1、使用@TableName注解
在实体类中使用@TableName注解指定表名和主键字段,MyBatisPlus可以自动进行关联查询。例如有两个实体类User和Order,Order表中有一个userId字段与User表中的id字段对应。
User实体类:
“`
@TableName(“user”)
public class User {
@TableId(type = IdType.AUTO)
private Long id;
private String name;
private Integer age;
//getter和setter省略
}
“`
Order实体类:
“`
@TableName(“order”)
public class Order {
@TableId(type = IdType.AUTO)
private Long id;
private Long userId;
private String orderNo;
//getter和setter省略
}
“`
使用MyBatisPlus的BaseMapper进行关联查询:
“`
public interface UserMapper extends BaseMapper {
@Select(“select * from user where id = #{id}”)
User findById(Long id);
@Select(“select * from user where name = #{name}”)
List findByName(String name);
}
“`
“`
public interface OrderMapper extends BaseMapper {
@Select(“select * from `order` where user_id = #{userId}”)
List findByUserId(Long userId);
}
“`
以上代码中的@Select注解可以使用MyBatisPlus提供的Wrapper类进行构建,实现更加灵活的查询方式。
2、使用@TableName和@TableField注解
在实体类中使用@TableName注解指定表名和主键字段,使用@TableField注解指定关联字段与对应的实体类字段名。例如有两个实体类User和Order,Order表中有一个userId字段与User表中的id字段对应。
User实体类:
“`
@TableName(“user”)
public class User {
@TableId(type = IdType.AUTO)
private Long id;
private String name;
private Integer age;
@TableField(exist = false)
private List orders;
//getter和setter省略
}
“`
Order实体类:
“`
@TableName(“order”)
public class Order {
@TableId(type = IdType.AUTO)
private Long id;
private Long userId;
private String orderNo;
//getter和setter省略
}
“`
使用MyBatisPlus的BaseMapper进行关联查询:
“`
public interface UserMapper extends BaseMapper {
@Select(“select * from user where id = #{id}”)
User findById(Long id);
@Select(“select * from user where name = #{name}”)
List findByName(String name);
@Select(“select * from user where id = #{id}”)
@Results(id = “userOrderMap”, value = {
@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.findByUserId”
))
})
User findWithOrdersById(Long id);
}
“`
“`
public interface OrderMapper extends BaseMapper {
@Select(“select * from `order` where user_id = #{userId}”)
List findByUserId(Long userId);
}
“`
以上代码中的@Results、@Result、@Many注解可以使用MyBatisPlus提供的Wrapper类进行构建,实现更加灵活的查询方式。
三、总结
MyBatisPlus提供了多种实现表之间关联查询的方式,使用起来都非常方便。在实际开发中,开发人员可以根据业务需求灵活选择不同的方式来进行关联查询。
原创文章,作者:小蓝,如若转载,请注明出处:https://www.506064.com/n/303171.html