1、 在springboot的entity类中声明变量时禁止使用如“desc”、“user”等关键词汇。
2、主键自增长的使用
@Id
@SequenceGenerator(name = "devicegroup_gid_seq", allocationSize = 1, initialValue = 1, sequenceName = "devicegroup_gid_seq")
@GeneratedValue(generator = "devicegroup_gid_seq", strategy = GenerationType.SEQUENCE)
@Column(name = "gid", unique = true, nullable = false)
public long getGid() {
return this.gid;
}
private void setGid(long gid) {
this.gid = gid;
}
3、多对一的使用:
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "uid")
public User getUser() {
return this.user;
}
public void setUser(User user) {
this.user = user;
}
4、一对多的使用:
@OneToMany(fetch = FetchType.EAGER, mappedBy = "deviceGroup")
public Set<Device> getDevices() {
return this.devices;
}
public void setDevices(Set<Device> devices) {
this.devices = devices;
}
mappedBy表示声明自己不是一对多的关系维护端,由对方来维护,是在一的一方进行声明的。mappedBy的值应该为一的一方的表名。
5、联级操作:
注意:联级操作必须和mappedBy一起使用到@OneToMany上才会起效。
PA允许您传播从父实体到子级的状态转换。为此,JPA javax.persistence.CascadeType定义了各种级联类型:
ALL
级联所有实体状态转换
PERSIST
级联实体持久化操作。
MERGE
级联实体合并操作。
REMOVE
级联实体删除操作。
REFRESH
级联实体刷新操作。
DETACH
级联实体分离操作。
此外,CascadeType.ALL将会传播任何Hibernate特定的操作,它由org.hibernate.annotations.CascadeType枚举定义:
以下示例将使用以下实体来解释上述一些级联操作:
@Entity
public class Person {
@Id
private Long id;
private String name;
@OneToMany(mappedBy = "owner", cascade = CascadeType.ALL)
private List<Phone> phones = new ArrayList<>();
}