如何使用JPA插件获取Play Framework 2中的org.hibernate.cfg.Configuration

时间:2014-09-16 14:48:51

标签: hibernate playframework-2.0

我可以像这样得到JPA Config:

Configuration jpaConf = Configuration.root().getConfig("jpa");

但是如何获得org.hibernate.cfg.Configuration,我需要像本课题一样(基于Play Framework 1)进行Schema Export:Using SchemaExport in Play Framework

My Play Framework 2.x application.conf有:

# Database configuration
# ~~~~~
db.default.driver=org.postgresql.Driver
db.default.url="jdbc:postgresql://localhost:5432/dpma"
db.default.user=bp
db.default.jndiName=DefaultDS
jpa.default=defaultPersistenceUnit

我的persistence.xml看起来像这样:

<?xml version="1.0" encoding="UTF-8"?>
<persistence version="2.0" xmlns="http://java.sun.com/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd">
  <persistence-unit name="defaultPersistenceUnit" transaction-type="RESOURCE_LOCAL">
    <non-jta-data-source>DefaultDS</non-jta-data-source>
    <properties>
            <property name="hibernate.dialect" value="org.hibernate.dialect.PostgreSQL9Dialect"/>
            <property name="hibernate.hbm2ddl.auto" value="update"/>
            <property name="hibernate.show_sql" value="true"/>
            <property name="hibernate.format_sql" value="true"/>
            <property name="hibernate.use_sql_comments" value="true"/>
            <!--<property name="hibernate.default_schema" value="&quot;legalEntitiesTest&quot;"/>-->
            <property name="hibernate.globally_quoted_identifiers" value="false"/>
        </properties>
  </persistence-unit>
</persistence>

**对于那些不熟悉Play Framework的人:** https://playframework.com/documentation/2.2.4/JavaJPA

1 个答案:

答案 0 :(得分:2)

您可以使用hibernate配置文件自己创建hibernate配置对象:

Configuration c = new Configuration();
c.configure("path to hibernate config").getProperty("hibernate property");

如果你不使用hibernate cfg文件,你可以用这种方式将JPA实体添加到配置中(它会使你所有的JPA类属于一个包):

final Configuration configuration = new Configuration();
final Reflections reflections = new Reflections(EntityClass.class.getPackage().getName());
final Set<Class<?>> classes = reflections.getTypesAnnotatedWith(Entity.class);
for (final Class<?> clazz : classes) {
    configuration.addAnnotatedClass(clazz);
}

在执行架构导出之前,请记住设置方言:

configuration.setProperty("hibernate.dialect", "org.hibernate.dialect.PostgreSQL9Dialect");