我有一个java代码,我正在更新人员实体。我正在使用应用程序管理实体管理器。我在登录页面中有一个条件,如果用户提供了正确的用户名/密码,他的上次登录时间将会更新。
但更新没有发生,我得到一个例外,该实体已被分离。请参阅下面的代码: -
GenericDaoImpl.java
public class GenericDaoImpl<T> implements GenericDao<T> {
private static final String PERSISTENCE_UNIT_NAME = "expenseCalculator";
private static EntityManagerFactory factory;
protected static EntityManager em;
private EntityTransaction etr;
protected Class<T> domainClass;
/** The domain object name. */
protected String domainObjectName = null;
public synchronized static EntityManagerFactory getfactory(){
if (null == factory) {
factory = Persistence.createEntityManagerFactory(PERSISTENCE_UNIT_NAME);
}
return factory;
}
@SuppressWarnings("unchecked")
public GenericDaoImpl() {
em = getfactory().createEntityManager();
domainClass = (Class<T>) ((ParameterizedType) getClass().getGenericSuperclass()).getActualTypeArguments()[0];
Entity entityAnn = (Entity) domainClass.getAnnotation(Entity.class);
if (entityAnn != null && !entityAnn.name().equals("")) {
domainObjectName = entityAnn.name();
} else {
domainObjectName = domainClass.getSimpleName();
}
}
public T create(T t) {
etr = em.getTransaction();
etr.begin();
em.persist(t);
etr.commit();
return t;
}
}
StaffServiceImpl.java
public Staff authenticateStaff(LoginBean loginBean) {
staff = staffDao.findUnique(loginBean.getUserName());
if (null != staff) {
if (staff.getIsBlocked() == 'N' && staff != null && staff.getUserName().equals(loginBean.getUserName())
&& staff.getPassword().equals(loginBean.getPassword())) {
staff.setLastLogin(new Date());
//This is giving an exception..
new StaffDaoImpl().create(staff);
return staff;
} else if (staff.getIsBlocked() == 'N' && staff != null
&& staff.getUserName().equals(loginBean.getUserName())) {
updateUnsuccessfulAttemptsAndBlockedStatus(staff);
}
}
return null;
}
StaffDaoImpl.java: -
@Repository
@Component
public class StaffDaoImpl extends GenericDaoImpl<Staff> implements StaffDao {
public Staff findUnique(String userName) {
TypedQuery<Staff> query = em.createNamedQuery(domainObjectName + ".findByUserName", domainClass);
query.setParameter("username", userName);
Staff staff = null;
try {
staff = query.getSingleResult();
} catch (NoResultException e) {
staff = null;
}
return staff;
}
在Class StaffServiceImpl.java中,您将看到我已经使Staff实体管理y调用&#34; staffDao.findUnique(loginBean.getUserName());&#34;但它仍然让我异常,实体工作人员是分离的。任何帮助都非常感谢。
答案 0 :(得分:0)
我得到了答案,实际上&#34;&#34; staffDao.findUnique(loginBean.getUserName())&#34;没有管理员工实体。所以我必须使用merge,以便管理Staff实体,并且对它的任何更改都会持久保存到DB。