jpa级联保存
程序员文章站
2022-04-20 21:12:31
...
@Data
@Entity
@Table(name = "BB_CLOTHES")
public class Clothes implements Serializable{
private static final long serialVersionUID = -3018808522887346432L;
@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
private Long id;
@Column(length = 32)
private String name;
@Column(length = 32)
private Integer size;
@Column(length = 64)
private Float price;
@ManyToOne(fetch=FetchType.EAGER,optional=true,cascade=CascadeType.PERSIST)
@JoinColumn(name = "wardrobe_id")
private Wardrobe wardrobe;
}
级联类型说明
public enum CascadeType {
ALL, // 级联全部操作
PERSIST, // 级联保存操作
MERGE, // 级联合并操作: 有主键就更新,没有就新增
REMOVE, // 级联删除操作
REFRESH,
DETACH
}
@Data
@Entity
@Table(name="BB_WARDROBE")
@GenericGenerator(name = "jpa-uuid", strategy = "uuid")
public class Wardrobe {
@Id
@GeneratedValue(generator = "jpa-uuid")
@Column(length = 64)
private String id;
@Column(length = 128)
private String name;
@Column
private Date createTime;
}
@RestController
@RequestMapping("/crud")
@Slf4j
public class CrudController {
@GetMapping("/save")
Object save(Clothes clothes) {
log.info("【clothes】={}", clothes);
// 保存对象
clothesDao.save(clothes);
return clothes;
}
@GetMapping("/delete")
Object delete(Long id) {
boolean flag = false;
Optional<Clothes> beDeleteObject = clothesDao.findById(id);
if(beDeleteObject.isPresent()) {
clothesDao.delete(beDeleteObject.get());
flag=true;
}
return flag;
}
}
测试保存
http://localhost:9080/crud/save?name=白衬衫&wardrobe.name=5号衣橱
打印日志
2020-09-16 10:34:22.392 INFO o.z.j.g.controller.CrudController - 【clothes】=Clothes(id=null, name=白衬衫, size=null, price=null, wardrobe=Wardrobe(id=null, name=6号衣橱, createTime=null))
Hibernate: insert into bb_wardrobe (create_time, name, id) values (?, ?, ?)
Hibernate: insert into bb_clothes (name, price, size, wardrobe_id) values (?, ?, ?, ?)
数据库两张表分别插入了新的记录
返回数据为:
{
"id": 24,
"name": "白衬衫",
"size": null,
"price": null,
"wardrobe": {
"id": "4028ed817494bcd5017494c3513b0006",
"name": "6号衣橱",
"createTime": null
}
}
测试删除
http://localhost:9080/crud/delete?id=24
只删除了bb_clothes的一条记录,因为级联的时候指定了 CascadeType.PERSIST
上一篇: 栈的java实现和栈的应用举例
下一篇: MySQL中的变量