这是问题所在。当我尝试从数据库中删除Catalog对象时,Hibernate还会删除所有具有关联Type和Genre ID的Catalog对象。例如,如果我正在删除带有Type.id = 1和Genre.id = 1的目录,则Hibernate会删除每个具有此类ID的目录。任何想法如何解决它?我只需删除一个Catalog对象而不删除id = 1的Type和Genre对象。
@Entity
@Table(name = "catalog", catalog = "media_store_db")
public class Catalog implements Serializable {
@Id
@Column(name = "id")
@GeneratedValue(strategy = GenerationType.AUTO)
private Integer id;
@Column(name = "product_name", length = 100)
private String productName;
@ManyToOne(cascade = {CascadeType.ALL})
@JoinColumn(name = "genre_id", referencedColumnName = "genre_id")
private Genre genre;
@ManyToOne(cascade = {CascadeType.ALL})
@JoinColumn(name = "type_id", referencedColumnName = "type_id")
private Type type;
@Entity
@Table(name = "genres", catalog = "media_store_db")
public class Genre implements Serializable {
@Id
@Column(name = "genre_id")
@GeneratedValue(strategy = GenerationType.AUTO)
private Integer id;
@Column(name = "genre_name")
private String name;
@OneToMany(mappedBy = "genre", cascade = CascadeType.ALL)
Collection<Catalog> catalogs = new ArrayList<Catalog>();
@Entity
@Table(name = "types", catalog = "media_store_db")
public class Type implements Serializable {
@Id
@Column(name = "type_id")
@GeneratedValue(strategy = GenerationType.AUTO)
private Integer id;
@Column(name = "type_name")
private String name;
@OneToMany(mappedBy = "type", cascade = CascadeType.ALL)
Collection<Catalog> catalogs = new ArrayList<Catalog>();
我删除目录对象的方法
public void deleteCatalog(Integer catalogId) {
Session session = config.getSession();
Transaction tx = session.beginTransaction();
session.delete(session.get(Catalog.class, catalogId));
tx.commit();
session.close();
}
答案 0 :(得分:1)
这是因为Cascade.ALL。如果您删除父项,如果您使用Cascade.ALL也会删除所有相关的子项。
相反,ALL只从下面选择你需要的东西
CascadeType.PERSIST:如果调用persist()或管理实体,则将持久化(创建)操作级联到关联实体
CascadeType.MERGE:如果调用merge()或管理实体,则将合并操作级联到关联实体
CascadeType.REMOVE:如果调用delete(),则将删除操作级联到关联实体
CascadeType.REFRESH:如果调用refresh(),则将刷新操作级联到关联的实体
CascadeType.DETACH:如果调用detach(),则将分离操作级联到关联实体
CascadeType.ALL:以上所有