我想从数据库中删除商家表中的行和地址表中的行。商户的表中有address_id。我已经为 Merchant 和 Address 创建了 DAO。如何仅使用实体管理器来做到这一点?我省略了导入、getter 和 setter。似乎只删除了Merchant表中的行,而保留了地址表中的行。任何帮助将不胜感激,谢谢。
每当我删除商家实体时,它都会保留地址id,并且不会删除Address表中相应的地址。我不明白为什么。
@Entity
public 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();
}
}
@Entity
public 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();
}
慕桂英4014372
相关分类