Hibernate不会在数据库中创建我的表

时间:2014-04-21 00:04:22

标签: java spring hibernate postgresql maven

在我的Spring / Maven项目的当前状态中,我有两个实体类,应该在我的postgresql数据库中创建。 Hibernate配置类是这样的:

@Configuration
@EnableTransactionManagement
@PropertySource({ "classpath:database.properties" })
@ComponentScan({ "spring.webapp.persistence" })
public class HibernateConfig {

   @Autowired
   private Environment env;

   @Bean
   public LocalSessionFactoryBean sessionFactory() {
      LocalSessionFactoryBean sessionFactory = new LocalSessionFactoryBean();
      sessionFactory.setDataSource(restDataSource());
      sessionFactory.setPackagesToScan(new String[] { "spring.webapp.persistence.model" });
      sessionFactory.setHibernateProperties(hibernateProperties());

      return sessionFactory;
   }

   @Bean
   public DataSource restDataSource() {
      BasicDataSource dataSource = new BasicDataSource();
      dataSource.setDriverClassName(env.getProperty("jdbc.driverClassname"));
      dataSource.setUrl(env.getProperty("jdbc.url"));
      dataSource.setUsername(env.getProperty("jdbc.user"));
      dataSource.setPassword(env.getProperty("jdbc.pass"));

      return dataSource;
   }

   @Bean
   @Autowired
   public HibernateTransactionManager transactionManager(SessionFactory sessionFactory) {
      HibernateTransactionManager txManager = new HibernateTransactionManager();
      txManager.setSessionFactory(sessionFactory);

      return txManager;
   }

   @Bean
   public PersistenceExceptionTranslationPostProcessor exceptionTranslation() {
      return new PersistenceExceptionTranslationPostProcessor();
   }

   Properties hibernateProperties() {
      return new Properties() {
         /**
         * 
         */
        private static final long serialVersionUID = 1L;

        {
            setProperty("hibernate.hbm2ddl.auto", env.getProperty("hibernate.hbm2ddl.auto"));
            setProperty("hibernate.dialect", env.getProperty("hibernate.dialect"));
            setProperty("hibernate.globally_quoted_identifiers", "true");
         }
      };
   }
}

我的文件database.properties是:

jdbc.driverClassname=org.postgresql.Driver
jdbc.url=jdbc:postgresql://localhost:5432/maven_test?charSet=LATIN1
jdbc.user=klebermo
jdbc.pass=123
hibernate.dialect=org.hibernate.dialect.PostgreSQLDialect
hibernate.show_sql=true
hibernate.hbm2ddl.auto=create-drop

我通过pom.xml添加postgresql jdbc驱动程序,其中包含:

<dependency>
  <groupId>postgresql</groupId>
  <artifactId>postgresql</artifactId>
  <version>9.1-901.jdbc3</version>
  <scope>compile</scope>
</dependency>

任何人都可以看到此设置有什么问题?因为在运行应用程序时,数据库中没有创建任何表。

2 个答案:

答案 0 :(得分:0)

hibernate.hbm2ddl.auto = update 而不是create-drop update用于创建新表,也用于更新旧表(如果有更改)

<dependency>
            <groupId>postgresql</groupId>
            <artifactId>postgresql</artifactId>
            <version>9.1-901-1.jdbc4</version>
        </dependency>

答案 1 :(得分:0)

好的,我现在发现了问题。发生我在注释@ComponentScan中有错误的路径。我修复了,现在表格是正常创建的。无论如何,谢谢你的建议。