如何将Hibernate SchemaUpdate类与JPA persistence.xml一起使用?

时间:2010-04-15 12:41:57

标签: hibernate jpa persistence.xml

我有一个使用SchemaUpdate的主方法在控制台上显示要更改/创建的表,它在我的Hibernate项目中工作正常:

 public static void main(String[] args) throws IOException {
  //first we prepare the configuration
  Properties hibProps = new Properties();
  hibProps.load(Thread.currentThread().getContextClassLoader().getResourceAsStream("jbbconfigs.properties"));
  Configuration cfg = new AnnotationConfiguration();
  cfg.configure("/hibernate.cfg.xml").addProperties(hibProps);

  //We create the SchemaUpdate thanks to the configs
  SchemaUpdate schemaUpdate = new SchemaUpdate(cfg);


  //The update is executed in script mode only
  schemaUpdate.execute(true, false);
  ...  

我想在JPA项目中重用此代码,没有hibernate.cfg.xml文件(也没有.properties文件),而是一个persistence.xml文件(在META-INF目录中自动检测,由JPA spec)。

我尝试过这么简单的改编,

Configuration cfg = new AnnotationConfiguration();
cfg.configure();

但是因为那个例外而失败了。

Exception in thread "main" org.hibernate.HibernateException: /hibernate.cfg.xml not found

有人这样做过吗? 感谢。

3 个答案:

答案 0 :(得分:7)

Kariem走在正确的轨道上,但让我试着澄清一下。

假设你有一个没有Hibernate特定的vanilla JPA标准配置,除了类路径上的Hibernate jar。如果您在J2SE引导程序模式下运行,那么您已经有一些看起来像这样的代码,无论是Java还是Spring配置等:

Map<String, Object> props = getJPAProperties();
EntityManagerFactory emf = 
    Persistence.createEntityManagerFactory("persistence-unit-name", props);

要运行SchemaUpdate,只需使用此代码:

Map<String, Object> props = getJPAProperties();
Ejb3Configuration conf = 
    new Ejb3Configuration().configure("persistence-unit-name", props);
new SchemaUpdate(conf.getHibernateConfiguration()).execute(true, false);

我不确定这将如何在容器环境中运行,但在简单的J2SE或Spring类型的配置中,这就是它的全部内容。

答案 1 :(得分:3)

您应该使用Ejb3Configuration而不是普通配置。请参阅hibernate文档中bootstrapping section末尾的实体管理器文档。

(从上面复制,经过微调)

Ejb3Configuration cfg = new Ejb3Configuration();
EntityManagerFactory emf = 
  cfg.addProperties(properties)                  // add some properties
     .setInterceptor(myInterceptorImpl)          // set an interceptor
     .addAnnotatedClass(MyAnnotatedClass.class)  // add a class to be mapped
     .addClass(NonAnnotatedClass.class)          // add an hbm.xml file using the Hibernate convention
     .addResource("mypath/MyOtherCLass.hbm.xml") // add an hbm.xml file
     .addResource("mypath/orm.xml" )             // add an EJB3 deployment descriptor
     .configure("/mypath/hibernate.cfg.xml")     // add a regular hibernate.cfg.xml
     .buildEntityManagerFactory();               // create the entity manager factory

如您所见,您可以混合使用很多不同类型的配置。

如果仅用于架构更新部分,则只需在persistence.xml中设置一个属性:hibernate.hbm2ddl.auto

<persistence-unit name="app1">
   <provider>org.hibernate.ejb.HibernatePersistence</provider>
   <properties>
     …
     <property name="hibernate.hbm2ddl.auto" value="update"/>
   </properties>
</properties>

请参阅here以获取更多参考资料。

答案 2 :(得分:1)

非常感谢彼得,你的回复工作得很好。 以下是SchemaUpdater类的完整代码:

package reformyourcountry.dbupdate;

import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.hibernate.ejb.Ejb3Configuration;
import org.hibernate.tool.hbm2ddl.SchemaUpdate;

import reformyourcountry.misc.DateUtil;

/** Small utility to be run by a developer to identify the difference between
 * its entities and its DB schema. It produces an SQL to be copy/pasted and applied
 * on the DB manually. Each developers having its own DB, when a developer commits its
 * Java code with new entity attributes (needing new DB columns), he also commits
 * an updated SQL file with the SQL that other developers need to apply on their local DB.
 * Later, when deploying the next version of the application in production,
 * this SQL file with cumulated changes will be applied onto the production DB.  
 * 
 * Limitations: 
 * 1. the Hibernate schema update does not detect removed attributes. 
 * If you have to delete a column, you need to write the SQL manually;
 * 
 * 2. the Hibernate schema update does not detect changes on existing columns.
 * for example, if you add @Column(nullable=false), it will not generates an 
 * additional DB constraint.
 * 
 * @author Cédric Fieux & John Rizzo & Aymeric Levaux
 *
 */
public class SchemaUpdater  {

    @SuppressWarnings({ "deprecation", "unchecked" })
    public static void main(String[] arg) throws IOException {

        ////// 1. Prepare the configuration (connection parameters to the DB, ect.)
        // Empty map. We add no additional property, everything is already in the persistence.xml
        Map<String,Object> map=new HashMap<String,Object>();   
        // Get the config from the persistence.xml file, with the unit name as parameter.
        Ejb3Configuration conf =  new Ejb3Configuration().configure("ConnectionPostgres",map);
        SchemaUpdate schemaUpdate =new SchemaUpdate(conf.getHibernateConfiguration());

        /////// 2. Get the SQL
        // Before we run the update, we start capturing the console output (to add ";" later)
        PrintStream initOut = System.out;
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream(1024);
        PrintStream newOut = new PrintStream(outputStream);
        System.setOut(newOut);

        //The update is executed in script mode only
        schemaUpdate.execute(true, false);

        //We reset the original out
        System.setOut(initOut);

        ////// 3. Prints that SQL at the console with a good format (adding a ";" after each line).
        System.out.println("--*******************************************Begin of SQL********************************************");
        System.out.println("-- "+DateUtil.formatyyyyMMdd(new Date()));
        BufferedReader ouReader = new BufferedReader(new InputStreamReader(new ByteArrayInputStream(outputStream.toByteArray())));
        String str = ouReader.readLine();
        while(str != null){  // For each (sometimes multiline) SQL statement
            // now, str equals "".
            str = ouReader.readLine();  // 
            while (str != null && !str.trim().equals("")) { // for each line of the same statement
                System.out.println();  // previous line is finished.
                System.out.print(str.toLowerCase());
                str = ouReader.readLine();
            }
            // Statement is now finished
            System.out.println(";");
        }
        System.out.println("--*******************************************End of SQL********************************************");

        ////// 4. Print eventual exceptions.
        //If some exception occurred we display them
        if(!schemaUpdate.getExceptions().isEmpty()){
            System.out.println();
            System.out.println("SOME EXCEPTIONS OCCURED WHILE GENERATING THE UPDATE SCRIPT:");
            for (Exception e: (List<Exception>)schemaUpdate.getExceptions()) {
                System.out.println(e.getMessage());
            }
        }
    }

}