我想從數(shù)據(jù)庫中刪除商家表中的行和地址表中的行。商戶的表中有address_id。我已經(jīng)為 Merchant 和 Address 創(chuàng)建了 DAO。如何僅使用實體管理器來做到這一點?我省略了導(dǎo)入、getter 和 setter。似乎只刪除了Merchant表中的行,而保留了地址表中的行。任何幫助將不勝感激,謝謝。每當我刪除商家實體時,它都會保留地址id,并且不會刪除Address表中相應(yīng)的地址。我不明白為什么。@Entitypublic class Merchant { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private int id; private String name; @OneToOne private Address address; public Merchant() { }}public class MerchantDAO { protected static EntityManagerFactory emf = Persistence.createEntityManagerFactory("hamzaspersistenceunit"); public void persist(Merchant merchant) { EntityManager em = emf.createEntityManager(); em.getTransaction().begin(); em.persist(merchant); em.getTransaction().commit(); em.close(); } public void removeMerchant(Merchant merchant) { EntityManager em = emf.createEntityManager(); em.getTransaction().begin(); em.remove(em.contains(merchant) ? merchant : em.merge(merchant)); em.getTransaction().commit(); em.close(); }}@Entitypublic class Address { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private int id; private String name; private String streetAddress; private String city; private String state; private String zipCode; public Address(String name, String streetAddress, String city, String state, String zipCode) { super(); this.name = name; this.streetAddress = streetAddress; this.city = city; this.state = state; this.zipCode = zipCode; }}public class AddressDAO { protected static EntityManagerFactory emf = Persistence.createEntityManagerFactory("hamzaspersistenceunit"); public AddressDAO() { } public void persist(Address address) { EntityManager em = emf.createEntityManager(); em.getTransaction().begin(); em.persist(address); em.getTransaction().commit(); em.close(); }
1 回答

慕桂英4014372
TA貢獻1871條經(jīng)驗 獲得超13個贊
嘗試使用 注釋實體address
中的字段。默認情況下,此選項設(shè)置為,因此刪除操作不會級聯(lián)到實體。Merchant
@OneToOne(orphanRemoval = true)
false
Address
更新:此問題的正確解決方案是使用@OneToOne(cascade = CascadeType.REMOVE)
添加回答
舉報
0/150
提交
取消