我有一个商店课程。
@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);
}
和一个产品类
@Entity
@IdClass(ProductPK.class)
@Table(name = "Product")
public class Product {
@Id
@Column(name = "PR_Name", nullable = false, length = 45)
private String name;
@Id
@Column(name = "PR_SerialNumber", nullable = false, length = 45)
private String serialNumber;
....
@OneToMany(fetch = FetchType.EAGER, cascade = CascadeType.ALL, mappedBy="product")
private Set<StoreProductLink> stores = new HashSet<StoreProductLink>();
以及作为联接表的 StoreProductLink 类
@Entity
@IdClass(StoreProductLinkPK.class)
@Table(name = "StoreProductLink")
public class StoreProductLink {
@Id
private String storeName;
@Id
private String productName;
@Id
private String productSerialNumber;
@Column(name = "quantity")
private int quantity;
@Column(name = "lt")
private String lt;
@ManyToOne
@JoinColumn(name = "storeName", updatable = false, insertable = false, referencedColumnName = "ST_Name")
private Store store;
@ManyToOne
@JoinColumns(value = {
@JoinColumn(name = "productName", updatable = false, insertable = false, referencedColumnName = "PR_Name"),
@JoinColumn(name = "productSerialNumber", updatable = false, insertable = false, referencedColumnName = "PR_Serialnumber") })
private Product product;
.
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)
正在做
store.removeProduct(product);
此函数从 Set 命名产品中删除产品示例。和
t1 = entityManager.merge(t);
返回具有产品集但没有产品示例的商店。
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;
}