0

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.

AnthonyC
  • 277
  • 7
  • 16

1 Answers1

0

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>
coladict
  • 4,799
  • 1
  • 16
  • 27
  • Because i dont want to list all my entity in this file – AnthonyC Jan 08 '18 at 09:39
  • You don't have to list them. I'll edit the answer with the persistence.xml I use as an example. – coladict Jan 08 '18 at 09:42
  • @AnthonyC Keep in mind that Hibernate only finds Entity-annotated classes loaded by the same ClassLoader. Meaning, if you keep the `persistence.xml` in one jar, and the classes in another, then you need to either list them, or move the xml file into the same jar. – coladict Jan 08 '18 at 09:51