Java hibernate函数编码
我有以下场景,Java hibernate函数编码,java,hibernate,Java,Hibernate,我有以下场景,authenticateUser()调用saveApplicationLog() 我想使整个操作原子化,但不想合并这两个函数,因为其他函数也使用saveApplicationLog()。做这件事的正确方法是什么?如果您使用in方法管理事务,那么您就不能完成整个原子操作。 您必须将事务管理代码移动到另一个方法,例如execute(),并从execute()调用authenticateUser()和saveApplicationLog()。您必须对这两个操作使用相同的会话。如果我将au
authenticateUser()
调用saveApplicationLog()
我想使整个操作原子化,但不想合并这两个函数,因为其他函数也使用
saveApplicationLog()
。做这件事的正确方法是什么?如果您使用in方法管理事务,那么您就不能完成整个原子操作。
您必须将事务管理代码移动到另一个方法,例如
execute()
,并从execute()
调用authenticateUser()
和saveApplicationLog()
。您必须对这两个操作使用相同的会话。如果我将authenticateUser()
会话传递给saveApplicationLog()
它会工作吗?是的,如果您的事务管理代码只在authenticateUser()中,那么它会工作吗
private boolean authenticateUser(String username, String password) {
Session session = GCCPersistenceMangerFactory.getSessionFactory().openSession();
Transaction tx = null;
Boolean found = false;
try{
tx = session.beginTransaction();
String query = "FROM PersistentUserMasterData where userName = '" + username+"',password = '"+password+"'";
Query q = session.createQuery(query);
List <PersistentUserMasterData> userInfo = new ArrayList<PersistentUserMasterData> (q.list());
if (userInfo != null ) {
for(PersistentUserMasterData user : userInfo) {
found = true;
}
}
tx.commit();
}catch (HibernateException e) {
if (tx!=null) tx.rollback();
e.printStackTrace();
}finally {
session.close();
}
if(found){
ApplicationLogsDTO logsDto = new ApplicationLogsDTO(
"Login was succesfull for LDAP user: "+ username,
"LDAP_LOGIN_SUCCESS", "LOGIN", username, Severity.INFO.ordinal());
saveApplicationLog(logsDto);//function 2
}
return found;
}
public void saveApplicationLog(ApplicationLogsDTO log){
PersistentApplicationLogs pLog = new PersistentApplicationLogs(
log.getDetailDescription(), log.getEvent(), log.getEventSource(),log.getUser(), log.getSeverity(),getThreadLocalRequest().getRemoteAddr());
Session session = GCCPersistenceMangerFactory.getSessionFactory().openSession();
Transaction tx = null;
try{
tx = session.beginTransaction();
session.save(pLog);
tx.commit();
}catch (HibernateException e) {
if (tx!=null) tx.rollback();
e.printStackTrace();
}finally {
session.close();
}
}