PostgreSQL + Hibernate + Spring 自动创建数据库

6

我正在使用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访问User表时,会出现错误:表'User'不存在。

我如何使Hibernate自动创建数据库?


你尝试过使用 hibernate.hbm2ddl.auto=create 吗? - sAm
嘿,你解决了吗?怎么解决的? - Ryuzaki L
7个回答

28

9

尝试这种方式

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

这对我来说是一项工作。

来自Hibernate用户指南的自动生成模式部分:

javax.persistence.schema-generation.database.action

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

  • none - 不执行任何操作。

  • create - 生成数据库创建。

  • drop - 生成数据库删除。

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

如果spring.jpa.hibernate.ddl-auto=update ==> update,则可以根据您的情况进行更改。


7
属性hibernate.hbm2ddl.auto可以帮助您实现此功能。当创建SessionFactory时,它会自动验证或将模式DDL导出到数据库中。使用create-drop时,当SessionFactory被显式关闭时,数据库模式将被删除。
Hibernate可以接受上述属性的以下选项: validate: 验证模式,不对数据库进行更改。 update: 更新模式。 create: 创建模式,销毁以前的数据。 create-drop: 在会话结束时删除模式。

3

Spring Boot

Postgres不支持createDatabaseIfNotExist=true,因此您可以尝试类似的方法,这对我有效,请参见截图

@SpringBootApplication
public class SpringSecurityJwtApplication{

    public static void main(String[] args) {
        Logger logger = LoggerFactory.getLogger(SpringSecurityJwtApplication.class);
        Connection connection = null;
        Statement statement = null;
        try {
            logger.debug("Creating database if not exist...");
            connection = DriverManager.getConnection("jdbc:postgresql://localhost:5432/", "postgres", "postgres");
            statement = connection.createStatement();
            statement.executeQuery("SELECT count(*) FROM pg_database WHERE datname = 'database_name'");
            ResultSet resultSet = statement.getResultSet();
            resultSet.next();
            int count = resultSet.getInt(1);

            if (count <= 0) {
                statement.executeUpdate("CREATE DATABASE database_name");
                logger.debug("Database created.");
            } else {
                logger.debug("Database already exist.");
            }
        } catch (SQLException e) {
            logger.error(e.toString());
        } finally {
            try {
                if (statement != null) {
                    statement.close();
                    logger.debug("Closed Statement.");
                }
                if (connection != null) {
                    logger.debug("Closed Connection.");
                    connection.close();
                }
            } catch (SQLException e) {
                logger.error(e.toString());
            }
        }
        SpringApplication.run(SpringSecurityJwtApplication.class, args);
    }
}

1
问题涉及 Hibernate 方言。您正在使用旧版的方言。您应该使用像这样的新版方言。
spring.jpa.database-platform=org.hibernate.dialect.PostgreSQL95Dialect

0

只需更改

从:

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

目的地:

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

因为PostgreSQL有默认的“用户”


-3

你可以使用带有"CREATE SCHEMA IF NOT EXISTS x;"的schema.sql脚本。

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

它应该可以工作


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接