When using mybatis-plus
database operations, annotations are very convenient to implement one-to-many and many-to-many relationships.
For one-to-many relationships, we can use @OneToMany
annotations to achieve. Here is sample code:
@TableName("tb_order")
public class Order {
@TableId(type = IdType.AUTO)
private Long id;
private Long userId;
private String orderNo;
@OneToMany(fetch = FetchType.EAGER, cascade = CascadeType.ALL)
@JoinColumn(name = "order_id")
private List<OrderItem> orderItems;
// getter和setter方法
}
@TableName("tb_order_item")
public class OrderItem {
@TableId(type = IdType.AUTO)
private Long id;
private Long orderId;
private String skuCode;
private Integer quantity;
// getter和setter方法
}
For many-to-many relationships, we can use @ManyToMany
annotations to implement, the sample code is as follows:
@TableName("tb_user")
public class User {
@TableId(type = IdType.AUTO)
private Long id;
private String username;
private String password;
@ManyToMany(fetch = FetchType.EAGER, cascade = CascadeType.ALL)
@JoinTable(name = "tb_user_role", joinColumns = @JoinColumn(name = "user_id"), inverseJoinColumns = @JoinColumn(name = "role_id"))
private List<Role> roles;
// getter和setter方法
}
@TableName("tb_role")
public class Role {
@TableId(type = IdType.AUTO)
private Long id;
private String roleName;
@ManyToMany(fetch = FetchType.EAGER, cascade = CascadeType.ALL)
@JoinTable(name = "tb_user_role", joinColumns = @JoinColumn(name = "role_id"), inverseJoinColumns = @JoinColumn(name = "user_id"))
private List<User> users;
// getter和setter方法
}
By using the above annotations, we can easily implement one-to-many and many-to-many relationships.
The above example is a sample code for implementing one-to-many and many-to-many relationships for annotations of database operations in the mybatis-plus framework.
One-to-many query example:
Order order = orderMapper.selectById(1L);
List<OrderItem> orderItems = order.getOrderItems();
Example many-to-many query:
User user = userMapper.selectById(1L);
List<Role> roles = user.getRoles();