代码之家  ›  专栏  ›  技术社区  ›  AnthonyC

休眠和Guice,无需持久性。xml

  •  0
  • AnthonyC  · 技术社区  · 7 年前

    我试图找到一种使用Guice 4.1和Hibernate 5.2的方法

    我查看了文档,似乎我们需要使用持久性。xml文件。我想知道我们是否可以在没有这种持久性的情况下使用Guice和Hibernate。xml?有没有办法做到什么坚持。xml做但编程?

    谢谢

    1 回复  |  直到 7 年前
        1
  •  0
  •   coladict    7 年前

    理论上你可以实现你自己的 javax.persistence.spi.PersistenceUnitInfo 变成一个 MyPunit 然后做一些类似的事情

    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);
    

    然而,应该没有必要这样做。你应该创建自己的持久性。应用程序的xml。你为什么要避免它?

    这是最小的持久性。所需的xml,无需列出所有类(使用示例方言):

    <?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>