如何使用注释配置从实体生成数据库模式?

时间:2016-09-23 19:47:22

标签: java spring hibernate spring-mvc spring-data-jpa

我有一堆java POJO类。我之前使用XML配置生成了模式,但现在我正在使用注释,但它不起作用。

    @Bean
    public LocalContainerEntityManagerFactoryBean entityManagerFactory(DataSource dataSource, Environment env) {
        LocalContainerEntityManagerFactoryBean entityManagerFactoryBean = new LocalContainerEntityManagerFactoryBean();
        entityManagerFactoryBean.setDataSource(dataSource);
        entityManagerFactoryBean.setJpaVendorAdapter(new HibernateJpaVendorAdapter());
        entityManagerFactoryBean.setPackagesToScan("com.library.entities");
        entityManagerFactoryBean.setJpaProperties(hibernateProperties());

        return entityManagerFactoryBean;
    }

    @Bean
    public DataSource dataSource() {
        DriverManagerDataSource dataSource = new DriverManagerDataSource();
        dataSource.setDriverClassName("com.mysql.jdbc.Driver");
        dataSource.setUrl("jdbc:mysql://localhost/library");
        dataSource.setUsername("root");
        dataSource.setPassword("root");


        return dataSource;
    }

    final Properties hibernateProperties() {
        final Properties hibernateProperties = new Properties();

        hibernateProperties.setProperty("spring.jpa.database", "MYSQL");
        hibernateProperties.setProperty("spring.jpa.show-sql", "true");
        hibernateProperties.setProperty("spring.jpa.hibernate.ddl", "create");

        return hibernateProperties;
    }

我的属性在entityManagerFactory中设置。记录器信息可能会有所帮助:

LocalContainerEntityManagerFactoryBean:462 - Closing JPA EntityManagerFactory for persistence unit 'default'

我没有hibernate.properties文件。注释配置中是否需要此文件?

INFO  Environment:239 - HHH000206: hibernate.properties not found

1 个答案:

答案 0 :(得分:4)

您的属性密钥错误。 当你在spring.jpa.*文件中定义配置时,像application.properties这样的键用于Spring Boot。

查看AvailableSettings界面以查看可用和有效的密钥。

因此密钥必须是:

hibernateProperties.setProperty("hibernate.show_sql", "true");
hibernateProperties.setProperty("hibernate.hbm2ddl.auto", "create");

OR

hibernateProperties.setProperty(AvailableSettings.SHOW_SQL, "true");
hibernateProperties.setProperty(AvailableSettings.HBM2DDL_AUTO, "create");