I want to know whether a username is already in use, and if that's not the case, whether an emailadress is already in use. I don't want to begin and commit a new transaction for each entitymanager find method because I think using just one transaction for multiple operations is more efficient then using several. Can I replace commit() with flush() in my method?
public void createUser(User_ newUser){
UserDao userDao = new UserDao();
Alert alert;
EntityTransaction transaction = entityManager.getTransaction();
try{
transaction.begin();
userDao.find("userName",newUser.getUserName());
transaction.commit();
alert = new Alert(Alert.AlertType.ERROR,"Username already in use", ButtonType.OK);
alert.showAndWait();
if (alert.getResult() == ButtonType.OK)alert.close();
}
catch(NoResultException e){
try{
transaction.begin();
userDao.find("emailAdress",newUser.getEmailAdress());
transaction.commit();
alert = new Alert(Alert.AlertType.ERROR,"E-mail adress already in use", ButtonType.OK);
alert.showAndWait();
if (alert.getResult() == ButtonType.OK) alert.close();
}
catch(NoResultException x){
transaction.begin();
userDao.save(newUser);
transaction.commit();
}
}
catch(RuntimeException e){
transaction.rollback();
}
finally{entityManager.close();}
}
thank you.