SpringBoot实体类配置、Jpa查询、lombok注解整合笔记⼀、表结构与配置
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import lombok.ToString;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.OneToMany;
import javax.persistence.Table;
import java.util.ArrayList;
import java.util.List;
@Setter
@Getter
@ToString
@NoArgsConstructor
@Entity
@Table(name = "DEMO_ONE")
public class DemoOne {
@Id
@GenericGenerator(name = "idGenerator", strategy = "org.hibernate.id.UUIDGenerator")
@GeneratedValue(generator = "idGenerator")
@Column(name = "ID", length = 50)
private String id;
@Column(name = "NAME", length = 50)
private String name;
@ToString.Exclude
@OneToMany(mappedBy = "demoOne")
private List<DemoMany> demoManyList = new ArrayList<>();
}
import lombok.Getter;
import lombok.NoArgsConstructor;
springboot结构
import lombok.Setter;
import lombok.ToString;
import javax.persistence.*;
@Setter
@Getter
@ToString
@NoArgsConstructor
@Entity
@Table(name = "DEMO_MANY")
public class DemoMany {
@Id
@GenericGenerator(name = "idGenerator", strategy = "org.hibernate.id.UUIDGenerator")
@GeneratedValue(generator = "idGenerator")
@Column(name = "ID", length = 50)
private String id;
@Column(name = "NAME", length = 50)
private String name;
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "DEMO_ONE_ID")
private DemoOne demoOne;
}
DEMO_ONE
ID NAME
1one1
2one2
DEMO_MANY
ID NAME DEMO_ONE_ID
1many21
2many21
3many32
4many42
1、多对⼀需要配置懒加载,使⽤@ToString需要在关联的⼀⽅加 @ToString.Exclude
如果不加懒加载,当你使⽤jpa⾃带findAll或者jpa查询规则findByName查询DEMO_MANY表会执⾏3条⼀句:
语句A:select e.id,e.name … from many e
语句B:select e.id,e.name… from one e where e.id=1
语句C:select e.id,e.name… from one e where e.id=2
如果加了懒加载机制,只会执⾏⼀条语句,当使⽤DemoMany .getDemoOne()时,才会去执⾏语句B或者语句C,以此类推…!
如果使⽤了lombok的@ToString注解,关联会死循环导致内存溢出,需要在关联任意的⼀⽅加 @ToString.Exclude,建议在⼀对多的⼀⽅加,因为toString会去懒加载,查询数据库!
2、CascadeType详解
CascadeType.PERSIST:级联保存
多对⼀时,⼀般先是出数据库存在的one,赋值many.set(one),保存save(many) 完成关联保存,当如果数据库中不存在one,这时候需要在 @OneToMany 配置 cascade = CascadeType.PERSIST 属性,这时候就要先创建新的one,One one = new One(),赋值many.set(one),保存save(many) 完成关联保存,此时就会同时保存 one 和 many;如果不加 cascade =
CascadeType.PERSIST 属性就会报异常 save the transient instance before flushing!
⼀对多时保存的时候要注意是,不管是从数据库查询出来额many还是new出来的many,都需要many.set(one),否则关联关系将不会创建出来!
CascadeType.REMOVE:级联删除
如果你要删除⼀个实体,但是它有外键⽆法删除,配置该属性会删除与之关联的所有外键对应的数据!
CascadeType.MERGE:级联更新(合并)
未实践
CascadeType.DETACH:级联脱管/游离
如果你要删除⼀个实体,但是它有外键⽆法删除,配置该属性会撤销所有相关的外键关联!
CascadeType.REFRESH:级联刷新
未实践

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。