I'm new to Hibernate and trying to figure things out. I've done a lot of searching, but haven't been able to find any adequate answers to help me. So any assistance would be great.
Getting: Exception in thread "main" org.hibernate.SessionException: Session is closed!
When trying the createAccount() method, it uses an isValidated() method which checks to see if an email already exists in the DB... it begins a transaction, queries the DB, and commits. If it passes validation, the createAccount() method will begin its own transaction, update the db, and commit its changes. I run into the problem where the create account method cannot begin its own transaction, and I get the exception that the session is closed.
I'm assuming I'm just using the factories/sessions incorrectly and I just need to be pointed towards the right structure of setting up my db transactions.
Code below:
Code:
private static final Session session;
static
{
session = HibernateUtil.getSessionFactory().getCurrentSession();
}
protected static void endTransaction()
{
session.getTransaction().commit();
}
protected static void beginTransaction()
{
session.beginTransaction();
}
protected static Query createQuery(String str)
{
return session.createQuery(str);
}
protected static void save(Object o)
{
session.save(o);
}
Create Account
Code:
public Account createAccount(String firstName, String lastName, String email, String alias, String password) throws EmailNotAvailableException
{
Account toCreate = new Account();
toCreate.setFirstName(firstName);
toCreate.setLastName(lastName);
toCreate.setEmail(email);
toCreate.setAlias(alias);
boolean isValidated = this.validate(toCreate);
if(isValidated)
{
// Set up salt and encrypted password
PasswordEncryption util = new PasswordEncryption();
String salt = util.generateSalt();
String encryptedPassword = util.encrypt(password, salt);
toCreate.setSalt(salt);
toCreate.setPassword(encryptedPassword);
// Add account to database
beginTransaction();
save(toCreate);
endTransaction();
}
return toCreate;
}
Validate
Code:
private boolean validate(Account account) throws EmailNotAvailableException
{
boolean toReturn = true;
if(this.getAccountByEmail(account.getEmail()) != null)
{
toReturn = false;
throw new EmailNotAvailableException(new Throwable());
}
return toReturn;
}
GetAccountByEmail
Code:
public Account getAccountByEmail(String email)
{
Account toReturn = null;
beginTransaction();
Query response = createQuery("from Account account where account.email='" + email + "'");
List<Account> results = (List<Account>)response.list();
if(!results.isEmpty())
{
toReturn = results.get(0);
}
endTransaction();
return toReturn;
}