hibernateguiceguice-persist

Hibernate and Guice without persistence.xml


I am trying to find a way to use Guice 4.1 and Hibernate 5.2

I checked the documentation and seems like we need to use a persistence.xml file. I am wondering if we can use Guice and Hibernate without this persistence.xml? is there a way to do what persistence.xml do but programmatically?

Thanks.


Solution

  • Theoretically you could implement your own javax.persistence.spi.PersistenceUnitInfo into a MyPunit and do something like

    import java.util.ServiceLoader;
    import javax.persistence.spi.PersistenceProvider;
    
    ...
    
    PersistenceProvider pp = ServiceLoader.load(PersistenceProvider.class).iterator().next();
    MyPunit conf = new MyPunit();
    Map properties = new HashMap();
    EntityManagerFactory emf = pp.createContainerEntityManagerFactory(conf, properties);
    

    However there should be no need for this. You're supposed to create your own persistence.xml for the application. Why would you want to avoid it?

    Here is the minimal persistence.xml you need without listing all the classes (with example dialect):

    <?xml version="1.0" encoding="UTF-8"?>
    <persistence version="2.1" 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">
      <persistence-unit name="package.root.to.scan" transaction-type="RESOURCE_LOCAL">
        <provider>org.hibernate.jpa.HibernatePersistenceProvider</provider>
        <non-jta-data-source>java:comp/env/jdbc/ourdb</non-jta-data-source>
        <exclude-unlisted-classes>false</exclude-unlisted-classes>
        <properties>
          <property name="hibernate.dialect" value="org.hibernate.dialect.PostgreSQL95Dialect"/>
        </properties>
      </persistence-unit>
    </persistence>