| .. | .. |
|---|
| 3 | 3 | */ |
|---|
| 4 | 4 | package net.curisit.securis.ioc; |
|---|
| 5 | 5 | |
|---|
| 6 | +import jakarta.annotation.PostConstruct; |
|---|
| 6 | 7 | import jakarta.enterprise.context.ApplicationScoped; |
|---|
| 7 | 8 | import jakarta.persistence.EntityManager; |
|---|
| 8 | 9 | import jakarta.persistence.EntityManagerFactory; |
|---|
| .. | .. |
|---|
| 27 | 28 | @ApplicationScoped |
|---|
| 28 | 29 | public class EntityManagerProvider { |
|---|
| 29 | 30 | |
|---|
| 30 | | - @SuppressWarnings("unused") |
|---|
| 31 | 31 | private static final Logger log = LogManager.getLogger(EntityManagerProvider.class); |
|---|
| 32 | 32 | |
|---|
| 33 | 33 | /** |
|---|
| 34 | 34 | * entityManagerFactory<p> |
|---|
| 35 | 35 | * Application-wide EMF built from persistence.xml PU "localdb". |
|---|
| 36 | 36 | */ |
|---|
| 37 | | - private final EntityManagerFactory entityManagerFactory = Persistence.createEntityManagerFactory("localdb"); |
|---|
| 37 | + //private final EntityManagerFactory entityManagerFactory = Persistence.createEntityManagerFactory("localdb"); |
|---|
| 38 | + private EntityManagerFactory entityManagerFactory; |
|---|
| 38 | 39 | |
|---|
| 40 | + @PostConstruct |
|---|
| 41 | + public void init() { |
|---|
| 42 | + try { |
|---|
| 43 | + log.info("Initializing EntityManagerFactory with persistence unit 'localdb'"); |
|---|
| 44 | + entityManagerFactory = Persistence.createEntityManagerFactory("localdb"); |
|---|
| 45 | + log.info("EntityManagerFactory initialized correctly: {}", entityManagerFactory); |
|---|
| 46 | + } catch (Exception e) { |
|---|
| 47 | + log.error("Error creating EntityManagerFactory for persistence unit 'localdb'", e); |
|---|
| 48 | + entityManagerFactory = null; |
|---|
| 49 | + } |
|---|
| 50 | + } |
|---|
| 51 | + |
|---|
| 39 | 52 | /** |
|---|
| 40 | 53 | * getEntityManager<p> |
|---|
| 41 | 54 | * Create a new {@link EntityManager}. |
|---|
| .. | .. |
|---|
| 43 | 56 | * @return a new EntityManager; caller must close it |
|---|
| 44 | 57 | */ |
|---|
| 45 | 58 | public EntityManager getEntityManager() { |
|---|
| 46 | | - return entityManagerFactory.createEntityManager(); |
|---|
| 59 | + try { |
|---|
| 60 | + if (entityManagerFactory == null) { |
|---|
| 61 | + log.error("EntityManagerFactory is null"); |
|---|
| 62 | + return null; |
|---|
| 63 | + } |
|---|
| 64 | + EntityManager em = entityManagerFactory.createEntityManager(); |
|---|
| 65 | + log.info("Created EntityManager: {}", em); |
|---|
| 66 | + return em; |
|---|
| 67 | + } catch (Exception e) { |
|---|
| 68 | + log.error("Error creating EntityManager", e); |
|---|
| 69 | + return null; |
|---|
| 70 | + } |
|---|
| 47 | 71 | } |
|---|
| 48 | 72 | } |
|---|