JPA has provided us with a rich API interface, the following for its various APIs encapsulated into an abstract class, our business logic interface implementation as long as the inheritance of this abstract class, you can use simple code to achieve a variety of operations.
Add action: protected void Persist (Object object) throws Persistenceexception {
Persistenceexception ex = null;
Entitymanager em = Getentitymanager ();
Em.gettransaction (). Begin ();
try {
Persist (em, object);
Em.gettransaction (). commit ();
} catch (Persistenceexception e) {
ex = e;
try {
Em.gettransaction (). rollback ();
} catch (Exception innerexception) {
}
} catch (Exception e) {
ex = new Persistenceexception (e);
try {
Em.gettransaction (). rollback ();
} catch (Exception innerexception) {
}
} finally {
Em.close ();
}
if (ex! = null) {
Throw ex;
}
}
Update operation: protected <T> t Merge (T object) throws Persistenceexception {
T ro = null;
Persistenceexception ex = null;
Entitymanager em = Getentitymanager ();
Em.gettransaction (). Begin ();
try {
Ro = Merge (em, object);
Em.gettransaction (). commit ();
} catch (Persistenceexception e) {
ex = e;
try {
Em.gettransaction (). rollback ();
} catch (Exception innerexception) {
}
} catch (Exception e) {
ex = new Persistenceexception (e);
try {
Em.gettransaction (). rollback ();
} catch (Exception innerexception) {
}
} finally {
try {
Em.close ();
} catch (Exception e) {
}
}
if (ex! = null) {
Throw ex;
}
return ro;
}
Delete operation
Protected void Remove (Object object) throws Persistenceexception {
persistenceexception ex = null;
entitymanager em = Getentitymanager ();
em.gettransaction (). Begin ();
try {
em.remove (Em.merge (object));
Em.gettransaction (). commit ();
} catch (Persistenceexception e) {
ex = e;
try {
Em.gettransaction (). rollback ();
} catch (Exception innerexception) {
}
} catch (Exception e) {
ex = new Persistenceexception (e);
try {
Em.gettransaction (). rollback ();
} catch (Exception innerexception) {
}
} finally {
try {
Em.close ();
} catch (Exception innerexception) {
}
}
if (ex! = null) {
Throw ex;
}
}
Number of queries, list
@SuppressWarnings ("Unchecked")
protected int GetCount (Class clazz) {
Entitymanager em = null;
try {
EM = Getentitymanager ();
return em! = null? GetCount (EM, clazz): 0;
} finally {
if (em! = null) {
Em.close ();
}
}
}
@SuppressWarnings ("Unchecked")
Protected <T> list<t> findentitylist (Class clazz) {
Entitymanager em = Getentitymanager ();
try {
Return (list<t>) Em.createquery (
"From" + clazz.getsimplename () + "O"). Getresultlist ();
} finally {
Em.close ();
}
}