控制器页面有以下代码
BigDecimal id=new BigDecimal(request.getParameter("empId"));
employee.setEmpno(id);
flag = factory.removeEmployee(employee);
TransactionFactory
上课
public final class EntityTransactionFactory implements TransactionFactory{
@PersistenceContext
private EntityManagerFactory Factory;
private EntityManager Manager;
@Resource
private UserTransaction Transaction;
private static final TransactionFactory transaction = new EntityTransactionFactory();
private EntityTransactionFactory() {
}
public static TransactionFactory getInstance() {
return transaction;
}
/**
* @return the Factory
*/
@Override
public EntityManagerFactory getFactory() {
Factory= Persistence.createEntityManagerFactory("SampleBeanPU");
return Factory;
}
/**
* @return the Manager
*/
@Override
public EntityManager getManager() {
Manager=getFactory().createEntityManager();
return Manager;
}
/**
* @return the Transaction
*/
@Override
public UserTransaction getTransaction() {
try {
Transaction = (UserTransaction) new InitialContext().lookup("java:comp/UserTransaction");
} catch (NamingException e) {
Transaction=null;
}
return Transaction;
}
}
emp
变量名Emp
类型。
TransactionFactory factory=EntityTransactionFactory.getInstance();
factory.getTransaction().begin();
factory.getManager().joinTransaction();
Emp ref= factory.getManager().getReference(Emp.class, emp.getEmpno());
System.out.println(ref.getEname());
factory.getManager().remove(factory.getManager().merge(ref));
System.out.println(factory.getTransaction().getStatus());
factory.getTransaction().commit();
System.out.println(factory.getTransaction().getStatus());
//factory.getManager().flush();
factory.getManager().close();
factory.getFactory().close();
但是,获得以下异常,这是指向上面的代码。
java.lang.IllegalArgumentException: Entity must be managed to call remove: com.entity.Emp[ empno=1234 ], try merging the detached and try the remove again.
答案 0 :(得分:0)
根据@JBNizet的建议
我只是通过放入私有构造函数并通过此类的getter方法检索实例来创建EntityManagerFactory
的实例。
为了删除我使用以下代码的实体
Emp ref = factory.getManager().find(Emp.class, emp.getEmpno());
factory.getManager().remove(ref);
而且,它有效。!!