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

e3bfsja2  于 2022-11-14  发布在  PostgreSQL
关注(0)|答案(7)|浏览(224)

我正在使用PostgreSQL和Spring4,希望我的应用程序在运行时自动创建数据库。
我的实体类是:

@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自动创建数据库?

5gfr0r5j

5gfr0r5j1#

只要找零就行了
出发地:

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

致:

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

因为PostgreSQL有默认的“USER”

bqujaahr

bqujaahr2#

您可以使用"CREATE SCHEMA IF NOT EXISTS x;""CREATE SCHEMA IF NOT EXISTS x;"

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

它应该能行得通

xlpyo6sf

xlpyo6sf3#

与MySQL不同,Postgres不支持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?

50few1ms

50few1ms4#

试试这条路

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操作。有效选项由操作枚举的外部JpaName值定义:

  • none-不执行任何操作。
  • create-将生成数据库创建。
  • drop-将生成数据库删除。
  • drop-and-create-在创建数据库之后将生成数据库删除。

在那里spring.jpa.hibernate.ddl-auto=update==>update,您可以根据您的场景进行更改。

iszxjhcz

iszxjhcz5#

属性hibernate.hbm2ddl.auto将为您完成此任务。在创建SessionFactory时,它会自动验证模式DDL或将其导出到数据库。使用CREATE-DROP,当显式关闭SessionFactory时,数据库模式将被删除。
Hibernate可以接受上述属性的这些选项。
validate:验证模式,不更改数据库。
update:更新架构。
create:创建模式,销毁以前的数据。
create-drop:在会话结束时删除该架构。

myzjeezk

myzjeezk6#

Spring Boot

Postgres不支持createDatabaseIfNotExist=true,所以您可以尝试类似的方法,它对我也有效,请参阅Screenshot

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

sxissh067#

问题出在 hibernate 方言上。您正在使用旧的。你应该用像这样的新的。

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

相关问题