Hello,
JPA allows CRUD code to be written only once; in other words, you can now avoid the huge amount of code duplication caused by the proliferation of DAOs. That's why I'm using the code below (
CRUDService.java) as a base class for services built on domain objects. The code has been working fine so far. I'm able to use it as follows, for example:
Code:
Job flightAtt = new Job();
...
SERVICE.create(flightAtt);
...
Runway r = (Runway) SERVICE.read(Runway.class, 2);
...
Employee e = (Employee) SERVICE.read(Employee.class, 4);
...
SERVICE.update(e);
...
SERVICE.delete(r);
SERVICE is a Singleton instance of CRUDService (or its subclasses). Still, when I compile the code I get the following warnings:
CRUDService.java:43: warning: [unchecked] unchecked conversionfound : java.lang.Class
required: java.lang.Class<T>
return em.find(type, id);
CRUDService.java:43: warning: [unchecked] unchecked method invocation: <T>find(java.lang.Class<T>,java.lang.Object) in javax.persistence.EntityManager is applied to (java.lang.Class,java.lang.Object)
return em.find(type, id);
As far as I can see, they are complaining that I'm not using generics in the
read() method. Even though they are just warnings, would someone please take a look at the code and criticize it? The code is very short and simple.
Code:
public class CRUDService {
protected static final Logger LOGGER = Logger.
getLogger(Logger.GLOBAL_LOGGER_NAME);
protected EntityManager em;
protected EntityTransaction tx;
private enum TransactionType { CREATE, UPDATE, DELETE };
protected CRUDService(String persistenceUnit) {
em = Persistence.createEntityManagerFactory(persistenceUnit).
createEntityManager();
tx = em.getTransaction();
}
public boolean create(Object obj) {
return execTransaction(obj, TransactionType.CREATE);
}
public Object read(Class type, Object id) {
return em.find(type, id);
}
public boolean update(Object obj) {
return execTransaction(obj, TransactionType.UPDATE);
}
public boolean delete(Object obj) {
return execTransaction(obj, TransactionType.DELETE);
}
private boolean execTransaction(Object obj, TransactionType txType) {
try {
tx.begin();
if (txType.equals(TransactionType.CREATE))
em.persist(obj);
else if (txType.equals(TransactionType.UPDATE))
em.merge(obj);
else if (txType.equals(TransactionType.DELETE))
em.remove(obj);
tx.commit();
} finally {
if (tx.isActive()) {
LOGGER.severe(txType + " FAILED: ROLLING BACK!");
tx.rollback();
return false;
} else {
LOGGER.info(txType + " SUCCESSFUL.");
return true;
}
}
}
}
Thanks so much,
Cristina