Hibernate 级联操作
程序员文章站
2022-05-02 08:17:10
...
– Start
我们已经知道了表与表之间的关系,如果我们对一个表进行操作,同时自动对相关表进行同样的操作,这时我们可以配置表的级联操作,级联操作的类型定义在枚举类 CascadeType 中。
package shangbo.hibernate.demo029;
import javax.persistence.CascadeType;
import javax.persistence.Entity;
import javax.persistence.ForeignKey;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.SequenceGenerator;
@Entity
public class Address {
@Id
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "addressId-generator")
@SequenceGenerator(name = "addressId-generator", sequenceName = "ADDRESS_ID_SEQ")
private Integer addressId;
private String city;
private String street;
// 级联操作
@ManyToOne(cascade = CascadeType.ALL)
@JoinColumn(name = "customerId", foreignKey = @ForeignKey(name = "CUSTOMER_ID_FK"))
private Customer customer;
public Address() {
}
public Address(String city, String street, Customer customer) {
this.city = city;
this.street = street;
this.customer = customer;
}
public Integer getAddressId() {
return addressId;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public String getStreet() {
return street;
}
public void setStreet(String street) {
this.street = street;
}
public Customer getCustomer() {
return customer;
}
public void setCustomer(Customer customer) {
this.customer = customer;
}
}
package shangbo.hibernate.demo029;
public class App {
public static void main(String[] args) throws Exception {
try (DataService dataService = new DataService()) {
dataService.beginTransaction();
// 创建实体类对象,由于配置了级联操作,我们只需要 save address
Customer customer = new Customer("test");
Address address = new Address("Dalian", "Gaoxingqu", customer);
dataService.save(address);
dataService.commit();
}
}
}
– 更多参见:Hibernate 精萃
– 声 明:转载请注明出处
– Last Updated on 2019-07-07
– Written by ShangBo on 2019-07-07
– End
上一篇: div水平垂直居中的方法