【问题标题】:PostgreSQL + Hibernate + Spring auto create databasePostgreSQL + Hibernate + Spring 自动创建数据库
【发布时间】:2016-11-12 23:20:01
【问题描述】:

我正在使用 PostgreSQL 和 Spring 4,并希望我的应用在运行时自动创建数据库。

我的实体类是:

@Entity
@Table(name = "user", schema = "public")
public class User extends BaseEntity {

    private Integer id;
    private String name;
    private Integer contractId;

    public User() {
    }

    public User(Integer id) {
        super(id);
    }

    @Id
    @Column(name = "usr_id", nullable = false)
    @GeneratedValue(strategy= GenerationType.IDENTITY)
    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    @Basic
    @Column(name = "usr_name", nullable = true, length = -1)
    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    @Basic
    @Column(name = "usr_contract_id", nullable = true)
    public Integer getContractId() {
        return contractId;
    }

    public void setContractId(Integer contractId) {
        this.contractId = contractId;
    }

}

HibernateConfig.java

@Configuration
@EnableTransactionManagement(proxyTargetClass = true)
@PropertySources({
    @PropertySource(value = "classpath:application.properties")})
@ConfigurationProperties(prefix = "spring.datasource")
public class HibernateConfig {

    @Autowired
    private Environment environment;

    @Autowired
    private DataSource dataSource;

    @Autowired
    private MultiTenantConnectionProvider multiTenantConnectionProvider;

    @Autowired
    private CurrentTenantIdentifierResolver currentTenantIdentifierResolver;

    public HibernateConfig() {}

    @Bean
    public LocalSessionFactoryBean sessionFactory() throws Exception {

        LocalSessionFactoryBean sessionFactory = new LocalSessionFactoryBean();
        sessionFactory.setDataSource(dataSource);
        sessionFactory.setHibernateProperties(hibernateProperties());

        sessionFactory.setPackagesToScan(new String[] {
            "com.xxx.xxx.model",
        });

        return sessionFactory;
    }

    private Properties hibernateProperties() {
        Properties properties = new Properties();
        properties.put(DIALECT, environment.getRequiredProperty(DIALECT));
        properties.put(SHOW_SQL, environment.getRequiredProperty(SHOW_SQL));
        properties.put(FORMAT_SQL, environment.getRequiredProperty(FORMAT_SQL));
        properties.put(HBM2DDL_AUTO, environment.getRequiredProperty(HBM2DDL_AUTO));

        return properties;
    }

    @Bean
    @Primary
    @Autowired
    public HibernateTransactionManager transactionManager(SessionFactory s) {
        HibernateTransactionManager txManager = new HibernateTransactionManager();
        txManager.setSessionFactory(s);
        return txManager;
    }

    @Bean
    @Autowired
    public HibernateTemplate hibernateTemplate(SessionFactory s) {
        HibernateTemplate hibernateTemplate = new HibernateTemplate(s);
        return hibernateTemplate;
    }
}

application.properties

# Database connection settings:
jdbc.driverClassName=org.postgresql.Driver
jdbc.url=jdbc:postgresql://localhost:5432/database
jdbc.username=postgres
jdbc.password=111111

hibernate.dialect=org.hibernate.dialect.PostgreSQLDialect
hibernate.show_sql=false
hibernate.format_sql=false
hibernate.hbm2ddl.auto=update

spring.datasource.initialSize=50
spring.datasource.maxActive=200
spring.datasource.maxIdle=200
spring.datasource.minIdle=50

但是当我运行SQL访问表用户时,会出现错误:表'用户'不存在。

如何让 Hibernate 自动创建数据库?

【问题讨论】:

  • 你厌倦了hibernate.hbm2ddl.auto=create吗?
  • 嘿,你解决了吗?以及如何?

标签: java spring hibernate postgresql


【解决方案1】:

hibernate.hbm2ddl.auto 属性将为您解决问题。创建 SessionFactory 时,它会自动验证模式 DDL 或将其导出到数据库。使用 create-drop,当 SessionFactory 显式关闭时,数据库模式将被删除。

Hibernate 可以接受上述属性的这些选项。

validate:验证架构,不更改数据库。

update:更新架构。

create:创建架构,销毁以前的数据。

create-drop:在会话结束时删除架构。

【讨论】:

    【解决方案2】:

    Postgres 不像 mysql 不支持Create Database If not exist

    因此更改 hibernate.hbm2ddl.auto=create 并更改 URL jdbc.url=jdbc:postgresql://localhost/database?createDatabaseIfNotExist=true 不适合你。

    但是您可以尝试模拟以下问题中的行为:

    Create Postgres database on the fly, if it doesn't exists using Hibernate

    Simulate CREATE DATABASE IF NOT EXISTS for PostgreSQL?

    【讨论】:

      【解决方案3】:

      试试这个方法

      spring.jpa.hibernate.ddl-auto=update
      spring.jpa.generate-ddl=true
      spring.jpa.database-platform=org.hibernate.dialect.PostgreSQL94Dialect
      
      spring.datasource.driverClassName=org.postgresql.Driver
      spring.datasource.url= jdbc:postgresql://localhost:5432/postgres
      spring.datasource.username=postgres
      spring.datasource.password=123
      
      spring.jpa.show-sql=true
      spring.session.store-type=none
      

      这对我有用。

      来自Automatic schema generation section of the Hibernate User Guide

      javax.persistence.schema-generation.database.action

      设置为在 SessionFactory 生命周期中自动执行 SchemaManagementTool 操作。有效选项由 Action 枚举的 externalJpaName 值定义:

      • none - 不会执行任何操作。

      • create - 将生成数据库创建。

      • drop - 将生成数据库删除。

      • drop-and-create - 将生成数据库删除,然后创建数据库。

      那里有spring.jpa.hibernate.ddl-auto=update ==> update,你可以根据你的场景改变。

      【讨论】:

        【解决方案4】:

        你可以有一个带有"CREATE SCHEMA IF NOT EXISTS x;"的schema.sql脚本

        spring.jpa.properties.hibernate.hbm2ddl.auto=update 
        

        它应该可以工作

        【讨论】:

          【解决方案5】:

          问题在于休眠方言。你用的是旧的。你应该像这样使用较新的。

          spring.jpa.database-platform=org.hibernate.dialect.PostgreSQL95Dialect
          

          【讨论】:

            【解决方案6】:

            改变一下

            来自:

            @Table(name = "user") || @Entity(name="user")
            

            到:

            @Table(name = "users") || @Entity(name="users")
            

            因为 PostgreSQL 有默认的“用户”

            【讨论】:

              猜你喜欢
              • 2021-10-21
              • 1970-01-01
              • 2014-01-30
              • 2018-08-10
              • 2016-10-21
              • 2019-07-18
              • 2016-08-15
              • 2016-05-26
              • 2018-12-30
              相关资源
              最近更新 更多