目录
🎂前言:
🎂 Mybatis也支持使用注解的方式实现一对一和一对多的关联查询。下面是注解实现的示例代码:
一对一关联查询:
🎂用户实体类(User):
🎂用户详情实体类(UserDetail):
🎂Mapper接口:
🎂一对多关联查询:
🎂订单实体类(Order):
🎂订单详情实体类(OrderDetail):
🎂Mapper接口:
🎂一对一和一对多的数据格式 :
🎂前言:
🎂 感觉要写一些通俗易懂的,
🎂上一篇直接使用mybatis 实现字段映射, 这篇使用注解来实现, 主打就是一个全面
🎂下面是映射版本地址:
[Mybatis的一对一和一对多]_是汤圆丫的博客-CSDN博客
🎂 Mybatis也支持使用注解的方式实现一对一和一对多的关联查询。下面是注解实现的示例代码:
一对一关联查询:
🎂用户实体类(User):
public class User {private int id;private String username;private String password;private String email;private UserDetail detail; // 一对一关联// getter和setter方法
}
🎂用户详情实体类(UserDetail):
public class UserDetail {private int id;private int userId;private String realName;private int age;private String address;// getter和setter方法
}
🎂Mapper接口:
public interface UserMapper {// 查询用户及其详情信息@Select("SELECT u.*, d.* FROM user u LEFT JOIN user_detail d ON u.id = d.user_id WHERE u.id = #{id}")@Results({@Result(property = "id", column = "id"),@Result(property = "username", column = "username"),@Result(property = "password", column = "password"),@Result(property = "email", column = "email"),@Result(property = "detail", column = "id", one = @One(select = "getUserDetail"))})User getUserWithDetail(int id);// 查询用户详情信息@Select("SELECT * FROM user_detail WHERE user_id = #{userId}")UserDetail getUserDetail(int userId);
}
在上面的代码中,我们使用了@Results注解来定义查询结果的映射关系,其中@Result注解用于定义每个属性的映射关系,@One注解用于定义一对一关联关系。在getUserWithDetail方法中,我们使用了@One注解来指定getUserDetail方法来查询用户详情信息,并将查询结果封装到User类的detail属性中。
🎂一对多关联查询:
🎂订单实体类(Order):
public class Order {private int id;private String orderNo;private Date createTime;private List<OrderDetail> details; // 一对多关联// getter和setter方法
}
🎂订单详情实体类(OrderDetail):
public class OrderDetail {private int id;private int orderId;private String productName;private double price;private int quantity;// getter和setter方法
}
🎂Mapper接口:
public interface OrderMapper {// 查询订单及其详情信息@Select("SELECT o.*, d.* FROM order o LEFT JOIN order_detail d ON o.id = d.order_id WHERE o.id = #{id}")@Results({@Result(property = "id", column = "id"),@Result(property = "orderNo", column = "order_no"),@Result(property = "createTime", column = "create_time"),@Result(property = "details", column = "id", many = @Many(select = "getOrderDetails"))})Order getOrderWithDetails(int id);// 查询订单详情信息@Select("SELECT * FROM order_detail WHERE order_id = #{orderId}")List<OrderDetail> getOrderDetails(int orderId);
}
在上面的代码中,我们使用了@Results注解来定义查询结果的映射关系,其中@Result注解用于定义每个属性的映射关系,@Many注解用于定义一对多关联关系。在getOrderWithDetails方法中,我们使用了@Many注解来指定getOrderDetails方法来查询订单详情信息,并将查询结果封装到Order类的details属性中。
🎂一对一和一对多的数据格式 :
这个格式数据要求,一般就看和前端如何去定义的, 你可以一个接口返回一条数据, 然后在提供一个接口 通过入参 再去查询 对应的list 列表数据
{"id": 1,"username": "test","password": "123456","email": "test@example.com","detail": {"id": 1,"userId": 1,"realName": "张三","age": 20,"address": "北京市"} }
{"id": 1,"orderNo": "202201010001","createTime": "2022-01-01","details": [{"id": 1,"orderId": 1,"productName": "商品1","price": 100.0,"quantity": 2},{"id": 2,"orderId": 1,"productName": "商品2","price": 200.0,"quantity": 1}] }