Joaquín Reñé
12 hours ago 132b79a57b0595430cfa245590e3b1a5d61891c5
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
/*
* Copyright @ 2013 CurisTEC, S.A.S. All Rights Reserved.
*/
package net.curisit.securis.ioc;
import jakarta.annotation.PostConstruct;
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.persistence.EntityManager;
import jakarta.persistence.EntityManagerFactory;
import jakarta.persistence.Persistence;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
/**
* EntityManagerProvider
* <p>
* Simple provider for JPA {@link EntityManager} instances using the
* persistence unit "localdb". Creates an {@link EntityManagerFactory}
* once per application and returns a fresh {@link EntityManager} per call.
*
* Note:
* - Callers are responsible for closing the obtained EntityManager.
* @author JRA
* Last reviewed by JRA on Oct 5, 2025.
*/
@ApplicationScoped
public class EntityManagerProvider {
   
    private static final Logger log = LogManager.getLogger(EntityManagerProvider.class);
    /** 
     * entityManagerFactory<p>
     * Application-wide EMF built from persistence.xml PU "localdb". 
     */
    //private final EntityManagerFactory entityManagerFactory = Persistence.createEntityManagerFactory("localdb");
    private EntityManagerFactory entityManagerFactory;
    @PostConstruct
    public void init() {
        try {
            log.info("Initializing EntityManagerFactory with persistence unit 'localdb'");
            entityManagerFactory = Persistence.createEntityManagerFactory("localdb");
            log.info("EntityManagerFactory initialized correctly: {}", entityManagerFactory);
        } catch (Exception e) {
            log.error("Error creating EntityManagerFactory for persistence unit 'localdb'", e);
            entityManagerFactory = null;
        }
    }
    
    /**
    * getEntityManager<p>
    * Create a new {@link EntityManager}.
    *
    * @return a new EntityManager; caller must close it
    */
    public EntityManager getEntityManager() {
        try {
            if (entityManagerFactory == null) {
                log.error("EntityManagerFactory is null");
                return null;
            }
            EntityManager em = entityManagerFactory.createEntityManager();
            log.info("Created EntityManager: {}", em);
            return em;
        } catch (Exception e) {
            log.error("Error creating EntityManager", e);
            return null;
        }
    }
}