Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Hibernate default schema and Table annotation

I am using Spring Boot 1.3.5 and Hibernate 5.1. Property that tells Hibernate what the schema to work with is called is

spring.jpa.properties.hibernate.default_schema

The value (schema name, lets say development), however, Somehow it does not get picked-up when creating tables with spring.jpa.hibernate.ddl-auto. Only way to get it work (at least what works for my case) is that each entity class has schema name defined with

 @Table(name = "some_table", schema = "development")

It would be great if tables could be created in the schema defined in spring boot application properties (possibility to be passed as ENV for different environments). If schema is not specified in @Table annotation the table is created in public schema.

Is there a way to set schema for tables without setting it in the Table annotation but with property file config only?

like image 271
CAPS LOCK Avatar asked Jun 30 '16 19:06

CAPS LOCK


2 Answers

After a year now app evolved and I am using Spring Boot 1.5.4 and Hibernate 5.1.5 with Postgres 9.6. Not sure if there were issues with previous versions but now it works fine.

yaml configuration file:

spring:
   datasource:
      driver-class-name: org.postgresql.Driver
      platform: postgresql
   jpa:
      properties:
         hibernate:
            dialect: org.hibernate.dialect.PostgreSQL94Dialect
            default_schema: SCHEMA_NAME

Although using 9.6, PostgreSQL94Dialect can be used for 9.4 and later as there is no specific PostgreSQL96Dialect for given Hibernate version.

With this there is no need to specify schema in @Table annotation.

Update October 2018

See Hibernate's repository for supported dialects and set git tag to your Hibernate version: https://github.com/hibernate/hibernate-orm/tree/master/hibernate-core/src/main/java/org/hibernate/dialect

like image 111
CAPS LOCK Avatar answered Oct 09 '22 01:10

CAPS LOCK


you can add this configuration if you use hibernate session factory;

@Value("${spring.jpa.properties.hibernate.default_schema}")
private String HIBERNATE_DEFAULT_SCHEMA;

@Bean
public LocalSessionFactoryBean sessionFactory() {
    LocalSessionFactoryBean sessionFactoryBean = new LocalSessionFactoryBean();
    sessionFactoryBean.setDataSource(dataSource);
    sessionFactoryBean.setMappingLocations(HIBERNATE_HBM_RESOURCES);

    Properties hibernateProperties = new Properties();
    hibernateProperties.put("hibernate.dialect", HIBERNATE_DIALECT);
    hibernateProperties.put("hibernate.show_sql", HIBERNATE_SHOW_SQL);
    hibernateProperties.put("hibernate.hbm2ddl.auto", HIBERNATE_HBM2DDL_AUTO);
    hibernateProperties.put("hibernate.default_schema", HIBERNATE_DEFAULT_SCHEMA);

    sessionFactoryBean.setHibernateProperties(hibernateProperties);

    return sessionFactoryBean;
}
like image 27
ali akbar azizkhani Avatar answered Oct 09 '22 00:10

ali akbar azizkhani