一个orm类中存在一个ManyToOne和oneToOne的外键,那么使用basemapper进行保存的时候在springboot项目中如何实现,请用java代码注解实现
时间: 2024-02-27 21:54:20 浏览: 52
基于springboot,采用mybatis和mapper3插件,基于shiro的sso cookies单机实现+源代码+文档说
可以使用MyBatis Plus框架提供的BaseMapper接口进行保存。在ORM类中,需要使用注解@JoinColumn来定义外键关联关系。具体实现如下:
```java
@Data
@AllArgsConstructor
@NoArgsConstructor
@Builder
@Table(name = "child")
public class Child {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
private String name;
@ManyToOne
@JoinColumn(name = "parent_id")
private Parent parent;
}
@Data
@AllArgsConstructor
@NoArgsConstructor
@Builder
@Table(name = "parent")
public class Parent {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
private String name;
@OneToOne(mappedBy = "parent", cascade = CascadeType.ALL)
private Address address;
@OneToMany(mappedBy = "parent", cascade = CascadeType.ALL)
private List<Child> children = new ArrayList<>();
}
@Data
@AllArgsConstructor
@NoArgsConstructor
@Builder
@Table(name = "address")
public class Address {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
private String street;
private String city;
@OneToOne
@JoinColumn(name = "parent_id")
private Parent parent;
}
```
在使用BaseMapper进行保存时,可以直接调用其save方法即可,例如:
```java
@Service
public class ParentService {
@Autowired
private ParentMapper parentMapper;
public void save(Parent parent) {
parentMapper.save(parent);
}
}
```
在保存Parent对象时,其关联的Address和Child对象会自动保存。需要注意的是,由于使用了CascadeType.ALL级联保存,因此在保存Parent对象时,其关联的Address和Child对象的外键关联关系也会被保存。
阅读全文