Hans Schwimmer Hans Schwimmer - 2 months ago 17
Java Question

How to generate db schema from entities using annotation configuration?

I have bunch of java POJO classes. I previously generated schema with XML configuration but now I am using annotated and it doesn't work.

@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;
}


My properties are set up in entityManagerFactory. The logger info that can be helpful:

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


I don't have hibernate.properties file. Is this file necessary in Annotated configuration?

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

Answer

Your keys for properties are wrong. keys like spring.jpa.* are for Spring Boot when you are defining configs in application.properties file.

Take a look at the AvailableSettings interface to see available and valid keys.

So the keys must be:

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

OR

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