Schema export with hibernate annotations

前端 未结 4 1666
萌比男神i
萌比男神i 2021-02-13 12:35

I\'m using hibernate annotations and i want to export my database schema.

Similar to the schemaexporttask with hbm xml files.

4条回答
  •  夕颜
    夕颜 (楼主)
    2021-02-13 12:54

    In case someone is interested how to do this with JPA+Spring from a unit test (you can generate the sql running the unit test from inside Eclipse like a breeze):

    ExportDatabaseSchema.java:

    
    @RunWith(SpringJUnit4ClassRunner.class)
    @ContextConfiguration
    @TransactionConfiguration(defaultRollback=true)
    public class ExportDatabaseSchema {
    
      @Resource(name="&entityManagerFactory")
      private LocalContainerEntityManagerFactoryBean entityManagerFactory;
    
      @Test
      public void exportDatabaseSchema(){
        PersistenceUnitInfo persistenceUnitInfo = entityManagerFactory.getPersistenceUnitInfo();
        Map jpaPropertyMap = entityManagerFactory.getJpaPropertyMap();
    
        Configuration configuration = new Ejb3Configuration().configure( persistenceUnitInfo, jpaPropertyMap ).getHibernateConfiguration();
    
        SchemaExport schema = new SchemaExport(configuration);
        schema.setOutputFile("resources/sql/schema.sql");
        schema.create(false, false);
      }
    }
    

    You need an ExportDatabaseSchema-context.xml:

    
     
    
    

    The applicationContext-jpa.xml contains the annotation configured entityManagerFactory bean. The trick is to inject it with & like this: "&entityManagerFactory", to dereference the spring generated proxy.

提交回复
热议问题