|
| 1 | +package mate.academy.dao.impl; |
| 2 | + |
| 3 | +import java.util.Optional; |
| 4 | +import mate.academy.dao.UserDao; |
| 5 | +import mate.academy.exception.DataProcessingException; |
| 6 | +import mate.academy.model.User; |
| 7 | +import mate.academy.util.HibernateUtil; |
| 8 | +import org.hibernate.HibernateException; |
| 9 | +import org.hibernate.Session; |
| 10 | +import org.hibernate.Transaction; |
| 11 | + |
| 12 | +public class UserDaoImpl implements UserDao { |
| 13 | + @Override |
| 14 | + public User add(User user) { |
| 15 | + Session session = null; |
| 16 | + Transaction transaction = null; |
| 17 | + try { |
| 18 | + session = HibernateUtil.getSessionFactory().openSession(); |
| 19 | + transaction = session.beginTransaction(); |
| 20 | + session.persist(user); |
| 21 | + transaction.commit(); |
| 22 | + return user; |
| 23 | + } catch (Exception e) { |
| 24 | + if (transaction != null) { |
| 25 | + transaction.rollback(); |
| 26 | + } |
| 27 | + throw new RuntimeException("can't save user to db" + user); |
| 28 | + } finally { |
| 29 | + if (session != null) { |
| 30 | + session.close(); |
| 31 | + } |
| 32 | + } |
| 33 | + } |
| 34 | + |
| 35 | + @Override |
| 36 | + public User get(Long id) { |
| 37 | + try (Session session = HibernateUtil.getSessionFactory().openSession()) { |
| 38 | + return session.get(User.class, id); |
| 39 | + } catch (Exception e) { |
| 40 | + throw new DataProcessingException("can't get user by id:" + id, e); |
| 41 | + } |
| 42 | + } |
| 43 | + |
| 44 | + @Override |
| 45 | + public Optional<User> findByEmail(String email) { |
| 46 | + try (Session session = HibernateUtil.getSessionFactory().openSession()) { |
| 47 | + return session.createQuery("FROM User u where u.email = :email", User.class) |
| 48 | + .setParameter("email", email) |
| 49 | + .uniqueResultOptional(); |
| 50 | + } catch (HibernateException e) { |
| 51 | + throw new DataProcessingException("can't find user by email " + email, e); |
| 52 | + } |
| 53 | + } |
| 54 | +} |
0 commit comments