我想从数据库中删除商家表中的行和地址表中的行。商户的表中有address_id。我已经为 Merchant 和 Address 创建了 DAO。如何仅使用实体管理器来做到这一点?我省略了导入、getter 和 setter。似乎只删除了Merchant表中的行,而保留了地址表中的行。任何帮助将不胜感激,谢谢。每当我删除商家实体时,它都会保留地址id,并且不会删除Address表中相应的地址。我不明白为什么。@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条经验 获得超13个赞
尝试使用 注释实体address
中的字段。默认情况下,此选项设置为,因此删除操作不会级联到实体。Merchant
@OneToOne(orphanRemoval = true)
false
Address
更新:此问题的正确解决方案是使用@OneToOne(cascade = CascadeType.REMOVE)
添加回答
举报
0/150
提交
取消