Hibernate JPA @PersistenceUnit Example

@PersistenceUnit

The @PersistenceUnit annotation is used to specify the EntityManagerFactory that needs to be injected as a dependency.

PersistenceUnit Expresses a dependency on an EntityManagerFactory and its associated persistence unit.

Injecting the default EntityManagerFactory

@PersistenceUnit
private EntityManagerFactory emf;
Or, in case you have multiple Persistence Units (e.g. multiple persistence.xml configuration files), you can inject a specific EntityManagerFactory by Unit name:

Injecting a specific EntityManagerFactory

@PersistenceUnit(
    unitName = "CRM"
)
private EntityManagerFactory entityManagerFactory;
The META-INF/persistence.xml file looks as follows:

META-INF/persistence.xml configuration file

<persistence xmlns="http://xmlns.jcp.org/xml/ns/persistence"
             xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
             xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/persistence
             http://xmlns.jcp.org/xml/ns/persistence/persistence_2_1.xsd"
             version="2.1">

    <persistence-unit name="CRM">
        <description>
            Persistence unit for Hibernate User Guide
        </description>

        <provider>org.hibernate.jpa.HibernatePersistenceProvider</provider>

        <class>org.hibernate.documentation.userguide.Document</class>

        <properties>
            <property name="javax.persistence.jdbc.driver"
                      value="org.h2.Driver" />

            <property name="javax.persistence.jdbc.url"
                      value="jdbc:h2:mem:db1;DB_CLOSE_DELAY=-1;MVCC=TRUE" />

            <property name="javax.persistence.jdbc.user"
                      value="sa" />

            <property name="javax.persistence.jdbc.password"
                      value="" />

            <property name="hibernate.show_sql"
                      value="true" />

            <property name="hibernate.hbm2ddl.auto"
                      value="update" />
        </properties>

    </persistence-unit>

</persistence>

Comments

Popular posts from this blog

Today Walkin 14th-Sept

Hibernate Search - Elasticsearch with JSON manipulation

Spring Elasticsearch Operations