|
5 | 5 | import org.hibernate.Session;
|
6 | 6 | import org.hibernate.SessionFactory;
|
7 | 7 | import org.hibernate.Transaction;
|
| 8 | +import org.slf4j.Logger; |
| 9 | +import org.slf4j.LoggerFactory; |
8 | 10 |
|
9 | 11 | import java.util.Collection;
|
| 12 | +import java.util.Properties; |
10 | 13 |
|
11 | 14 | public class DataAccessServiceImpl implements DataAccessService {
|
12 | 15 |
|
| 16 | + final private static Logger LOG = LoggerFactory.getLogger(DataAccessServiceImpl.class); |
| 17 | + |
13 | 18 | private final SessionFactory sessionFactory;
|
14 | 19 |
|
15 |
| - public DataAccessServiceImpl() { |
16 |
| - this.sessionFactory = HibernateUtil.getSessionFactory(); |
| 20 | + public DataAccessServiceImpl(Properties properties) { |
| 21 | + this.sessionFactory = HibernateUtil.getSessionFactory(properties); |
17 | 22 | }
|
18 | 23 |
|
19 | 24 | @Override
|
20 | 25 | public void saveUserData(UserData userData) {
|
21 | 26 | Transaction transaction = null;
|
22 |
| - try(Session session = this.sessionFactory.openSession()) { |
| 27 | + try (Session session = this.sessionFactory.openSession()) { |
23 | 28 | transaction = session.beginTransaction();
|
| 29 | + LOG.info("save user data, TX started"); |
24 | 30 | session.save(userData);
|
25 | 31 | transaction.commit();
|
| 32 | + LOG.info("save user data, TX committed"); |
26 | 33 | } catch (Exception e) {
|
| 34 | + LOG.error("Error: ", e); |
27 | 35 | if (transaction != null) {
|
| 36 | + LOG.info("user data rollback, TX rollback"); |
28 | 37 | transaction.rollback();
|
29 | 38 | }
|
30 | 39 | }
|
31 | 40 | }
|
32 | 41 |
|
33 | 42 | @Override
|
34 | 43 | public Collection<UserData> getUserData() {
|
35 |
| - try (Session session = HibernateUtil.getSessionFactory().openSession()) { |
| 44 | + try (Session session = this.sessionFactory.openSession()) { |
36 | 45 | return session.createQuery("from UserData", UserData.class).list();
|
37 | 46 | }
|
38 | 47 | }
|
39 | 48 |
|
| 49 | + @Override |
| 50 | + public void deleteUserData(long id) { |
| 51 | + Transaction transaction = null; |
| 52 | + try (Session session = this.sessionFactory.openSession()) { |
| 53 | + transaction = session.beginTransaction(); |
| 54 | + LOG.info("delete user data id={}, TX started", id); |
| 55 | + //Delete a transient object |
| 56 | + UserData userData = new UserData(id); |
| 57 | + session.delete(userData); |
| 58 | + transaction.commit(); |
| 59 | + LOG.info("delete user data id={}, TX committed", id); |
| 60 | + } catch (Exception e) { |
| 61 | + LOG.error("Error: ", e); |
| 62 | + if (transaction != null) { |
| 63 | + LOG.info("user data rollback, TX rollback"); |
| 64 | + transaction.rollback(); |
| 65 | + } |
| 66 | + } |
| 67 | + } |
| 68 | + |
| 69 | + @Override |
| 70 | + public void close() throws Exception { |
| 71 | + this.sessionFactory.close(); |
| 72 | + } |
| 73 | + |
40 | 74 | }
|
0 commit comments