I have a User
Entity
class which maps a User
table in a MySQL DB. This was auto-generated using the Hibernate Tools in Eclipse.
Then, I wrote a generic DAO interface:
package dal.genericdao;
public interface GenericDAO <EntityClass, IDClass> {
EntityClass create(EntityClass entity);
void delete(IDClass id);
EntityClass findById(IDClass id);
EntityClass update(EntityClass entity);
}
which is implemented in a GenericDAOImpl
class which uses EntityManager
for CRUD operations. Here is a snippet of it
package dal.genericdao;
import javax.persistence.PersistenceContext;
public class GenericDAOImpl<EntityClass, IDClass> implements GenericDAO<EntityClass, IDClass> {
@PersistenceContext private EntityManager entityManager;
// ---- In the original post I omitted this piece of code for shortness. It only retrieves the runtime EntityClass ----
private Class<EntityClass> entityClass;
@SuppressWarnings("unchecked")
public GenericDAOImpl() {
entityClass = (Class<EntityClass>) ((ParameterizedType) getClass().getGenericSuperclass())
.getActualTypeArguments()[0];
}
// --------------
@Override
public EntityClass create(EntityClass entity)
{
entityManager.getTransaction().begin();
entityManager.persist(entity);
entityManager.flush();
entityManager.getTransaction().commit();
return entity;
}
@Override
public void delete(IDClass id)
{
...
}
@Override
public EntityClass findById(IDClass id)
{
...
}
@Override
public EntityClass update(EntityClass entity)
{
...
}
}
So the UserDAO
is this
import dal.genericdao.GenericDAOImpl;
import dal.User;
import javax.enterprise.inject.Default;
@Default
public class UserDAO extends GenericDAOImpl<User, String> {
}
If I run some tests on the UserDAO
class everything works as expected.
The problem shows off when I try to persist (by mean of the UserDAO.create()
method) an Entity
which already exists in the DB. In fact, the entityManager.persist(entity)
method doesn't warn me whether I'm persisting an existent entity (which should, theoretically, provoke a primary key constraint violation) or not.
Moreover, in the entityManager.persist(entity)
method I cannot access the Entity
identifier value because it is "hidden" with the generic IDClass
class (so I cannot run GenericDAOImpl.findById(IDClass)
to verify the presence of the Entity
prior to the persist operation).
What do you think about this problem? How would you solve this?
Thank you