一个orm类中存在两个ManyToOne外键,那么使用basemapper进行保存的时候在springboot项目中如何实现,请用java代码注解实现
时间: 2024-02-27 10:54:33 浏览: 116
同样可以使用MyBatis Plus框架提供的BaseMapper接口进行保存。在ORM类中,需要使用注解@JoinColumn来定义外键关联关系。具体实现如下:
```java
@Data
@AllArgsConstructor
@NoArgsConstructor
@Builder
@Table(name = "order")
public class Order {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
private String orderNo;
@ManyToOne
@JoinColumn(name = "user_id")
private User user;
@ManyToOne
@JoinColumn(name = "product_id")
private Product product;
}
@Data
@AllArgsConstructor
@NoArgsConstructor
@Builder
@Table(name = "user")
public class User {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
private String name;
@OneToMany(mappedBy = "user", cascade = CascadeType.ALL)
private List<Order> orders = new ArrayList<>();
}
@Data
@AllArgsConstructor
@NoArgsConstructor
@Builder
@Table(name = "product")
public class Product {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
private String name;
@OneToMany(mappedBy = "product", cascade = CascadeType.ALL)
private List<Order> orders = new ArrayList<>();
}
```
在使用BaseMapper进行保存时,可以直接调用其save方法即可,例如:
```java
@Service
public class OrderService {
@Autowired
private OrderMapper orderMapper;
public void save(Order order) {
orderMapper.save(order);
}
}
```
在保存Order对象时,其关联的User和Product对象会自动保存。需要注意的是,由于使用了CascadeType.ALL级联保存,因此在保存Order对象时,其关联的User和Product对象的外键关联关系也会被保存。
阅读全文