How do I configure Hibernate with a JPA 2.0 file?
Hibernate docs show very clearly how to configure Hibernate with XML.
This is the snippet of code to do so:
new Configuration().configure("catdb.cfg.xml")
Now how do you configure Hibernate when instead of a hibernate configuration file, you have a JPA 2.0 config file ?
- How to do it for META-INF/persistence.xml ?
- What if my file is called META-INF/jpa.xml instead ?
This is for Hibernate 3.6 and JPA 2.0. My ultimate goal is to be able to export a schema DDL for the classes described in file persistence.xml, so I don't want to build a 开发者_StackOverflow社区SessionFactory.
Configuration cfg = /* ??? */
SchemaExport schemaExport = new SchemaExport(cfg);
schemaExport.setDelimiter(";");
schemaExport.setOutputFile("ddl.sql");
boolean script = true, export = false, justDrop = false, justCreate = false;
schemaExport.execute(script, export, justDrop, justCreate);
Assuming you would ordinarily look up your configuration using a persistence unit name, you can create an org.hibernate.ejb.Ejb3Configuration
and get it to return the wrapped org.hibernate.cfg.Configuration
:
package test;
import org.hibernate.cfg.Configuration;
import org.hibernate.ejb.Ejb3Configuration;
import org.hibernate.tool.hbm2ddl.SchemaExport;
public class SchemaExportTest {
public static void main(String[] args) {
Configuration cfg = new Ejb3Configuration().configure( "persistence-unit-name", null ).getHibernateConfiguration();
SchemaExport export = new SchemaExport(cfg);
export.execute(true, false, false, false);
}
}
If you use JPA 2.0 with Hibernate, the only file you need is the persistence.xml file located in the META-INF directory.
How to configure the persistence.xml file is an extensive subject and depends on the type of application you are building.
For instance, I am currently running an application with Hibernate 3.6.2 whose only configuration file is the persistence.xml and it only has the following lines
<persistence 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" version="2.0">
<persistence-unit name="xyz" transaction-type="RESOURCE_LOCAL"/>
</persistence>
That's all I need. At runtime, when I start the entity manager factory, I provide a few more properties , but what I intent to demonstrate, is how easy it can be to configure JPA with Hibernate.
精彩评论