Java 休眠删除多对多关联
我正在上商店课Java 休眠删除多对多关联,java,mysql,hibernate,many-to-many,Java,Mysql,Hibernate,Many To Many,我正在上商店课 @Entity @Table(name = "Store") public class Store { @Id @Column(name = "ST_Name", nullable = false) private String name; ... @OneToMany(fetch = FetchType.EAGER, cascade = CascadeType.ALL, mappedBy="store") priva
@Entity
@Table(name = "Store")
public class Store {
@Id
@Column(name = "ST_Name", nullable = false)
private String name;
...
@OneToMany(fetch = FetchType.EAGER, cascade = CascadeType.ALL, mappedBy="store")
private Set<StoreProductLink> products = new HashSet<StoreProductLink>();
public void addProduct(Product pr, int quantity, String lt) {
StoreProductLink link = new StoreProductLink();
...
this.products.add(link);
pr.getStores().add(link);
}
public void removeProduct(Product pr) {
StoreProductLink link = new StoreProductLink();
....
this.products.remove(link);
pr.getStores().remove(link);
}
Store store = new Store();
Product product = new Product();
product.setName(example);
...
store.addProduct(product, 5, "com");
updateHibernateFunction(store); (this inserts in StoreProductLink table this --> storeName,example, exampleSerialNumber,5,com)
做
此函数用于从名为products的集合中删除产品示例。
和
返回具有产品集但不包含产品示例的存储
updateHibernateFunction(store);
但是,StoreProductLink表仍保留该记录
添加操作效果良好。删除操作不起作用:/
已添加
这是更新函数
public T update(T t)
{
EntityManager entityManager = DataLayer.getEntityManager();
T t1 = null;
EntityTransaction tx = null;
try
{
tx = entityManager.getTransaction();
tx.begin();
t1 = entityManager.merge(t);
tx.commit();
}catch(RuntimeException e)
{
if(tx != null && tx.isActive()) tx.rollback();
throw e;
}finally
{
entityManager.close();
}
return t1;
}
这不是级联的问题,因为级联意味着(在DELETE情况下):“删除我时删除目标” 尝试执行删除操作:
public class Product {
@OneToMany(fetch = FetchType.EAGER, cascade = CascadeType.ALL, mappedBy="product",
orphanRemoval=true)
private Set<StoreProductLink> stores = new HashSet<StoreProductLink>();
公共类产品{
@OneToMany(fetch=FetchType.EAGER,cascade=CascadeType.ALL,mappedBy=“product”,
(删除=真)
私有集存储=新HashSet();
阅读一下@Cascade
注释……我用Hibernate做了一些事情已经有几个月了,但我想你想要CascadeOnDelete我在@OneToMany注释的两个类中都有(Cascade=CascadeType.ALL)。我应该添加其他内容吗?不幸的是,问题仍然存在。我想知道…可能是因为关系的另一端(存储<代码>存储代码>)仍然存在连接吗?我无法理解为什么会发生这种情况。正在执行存储.addProduct(产品1);存储.removeProduct(产品2);更新HibernateFunction(存储);仅添加产品1。不删除产品2。
t1 = entityManager.merge(t);
updateHibernateFunction(store);
public T update(T t)
{
EntityManager entityManager = DataLayer.getEntityManager();
T t1 = null;
EntityTransaction tx = null;
try
{
tx = entityManager.getTransaction();
tx.begin();
t1 = entityManager.merge(t);
tx.commit();
}catch(RuntimeException e)
{
if(tx != null && tx.isActive()) tx.rollback();
throw e;
}finally
{
entityManager.close();
}
return t1;
}
public class Product {
@OneToMany(fetch = FetchType.EAGER, cascade = CascadeType.ALL, mappedBy="product",
orphanRemoval=true)
private Set<StoreProductLink> stores = new HashSet<StoreProductLink>();