melli-182
melli-182

Reputation: 1234

Auto create/update Tables using Spring and Hibernate

i have an Spring + Hibernate based application where the most properties are setted using annotations.

My AppConfig class looks like:

//package declarations and imports 

@EnableWebMvc
@Configuration
@ComponentScan({ "com.package.subpackage.*" })
@Import({ SecurityConfig.class })
public class AppConfig {

    @Bean(name = "dataSource")
    public DriverManagerDataSource dataSource() {
        DriverManagerDataSource driverManagerDataSource = new DriverManagerDataSource();
        driverManagerDataSource.setDriverClassName("com.mysql.jdbc.Driver");
        driverManagerDataSource.setUrl("jdbc:mysql://localhost:3306/fur");
        Properties prop = new Properties();
        prop.setProperty("hibernate.hbm2ddl.auto", "create");
        driverManagerDataSource.setConnectionProperties(prop);
        driverManagerDataSource.setUsername("root");
        driverManagerDataSource.setPassword("");
        return driverManagerDataSource;
    }

    //other methods...

}

The problem I have is that the tables associated with my Java classes are not auto-created in my database.

I dont add examples of my class beacause I think its in the configuration the issue, but please let me know if is needed.

Upvotes: 3

Views: 3311

Answers (1)

Bohuslav Burghardt
Bohuslav Burghardt

Reputation: 34776

You are setting the properties containing hibernate.hmb2ddl.auto on the data source, which doesn't know anything about ORM layer such as Hibernate. You should pass these properties to LocalSessionFactoryBuilder bean or such.

You could use similar configuration to set-up Hibernate with the required properties:

@Configuration
public class DatabaseConfig {

    // Data source, transaction manager, ... bean definitions omitted

    @Bean
    public LocalSessionFactoryBuilder sessionFactoryBuilder() {
        LocalSessionFactoryBuilder sfb = new LocalSessionFactoryBuilder(dataSource());
        sfb.scanPackages("com.example.app.model");
        // Hibernate/JPA properties
        Properties properties = new Properties();
        properties.put("hibernate.dialect", "org.hibernate.dialect.MySQLDialect");
        properties.put("hibernate.hbm2ddl.auto", "create");
        sfb.addProperties(properties);
        return sfb;
    }

    @Bean
    public SessionFactory sessionFactory() {
        return sessionFactoryBuilder().buildSessionFactory();
    }

}

Upvotes: 2

Related Questions