PostgreSQL + Hibernate + Spring 自动创建数据库
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/38299685/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
PostgreSQL + Hibernate + Spring auto create database
提问by Tran Vinh Quang
I'm working with PostgreSQL and Spring 4 and want my app auto create database when it running.
我正在使用 PostgreSQL 和 Spring 4,并希望我的应用程序在运行时自动创建数据库。
My Entity Class is:
我的实体类是:
@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
But when I running SQL to access table User, this will appear error: Table 'User' does not exist.
但是当我运行 SQL 访问表 User 时,会出现错误:表 'User' 不存在。
How can I make Hibernate to auto create database?
如何让 Hibernate 自动创建数据库?
采纳答案by aksappy
The property hibernate.hbm2ddl.auto
will do the trick for you. It automatically validates or exports schema DDL to the database when the SessionFactory is created. With create-drop, the database schema will be dropped when the SessionFactory is closed explicitly.
该物业hibernate.hbm2ddl.auto
将为您解决问题。创建 SessionFactory 时,它会自动验证或将模式 DDL 导出到数据库。使用 create-drop,当 SessionFactory 显式关闭时,数据库模式将被删除。
Hibernate can accept these options for the above property.
Hibernate 可以接受上述属性的这些选项。
validate
: validate the schema, makes no changes to the database.
validate
: 验证架构,不对数据库做任何更改。
update
: update the schema.
update
: 更新架构。
create
: creates the schema, destroying previous data.
create
: 创建模式,破坏以前的数据。
create-drop
: drop the schema at the end of the session.
create-drop
: 在会话结束时删除架构。
回答by ankidaemon
Postgres unlike mysql does not support Create Database If not exist
.
与 mysql 不同,Postgres 不支持Create Database If not exist
.
Thus changing hibernate.hbm2ddl.auto=create
and changing URL jdbc.url=jdbc:postgresql://localhost/database?createDatabaseIfNotExist=true
won't work for you.
因此更改hibernate.hbm2ddl.auto=create
和更改 URLjdbc.url=jdbc:postgresql://localhost/database?createDatabaseIfNotExist=true
对您不起作用。
However you can try simulating the behavior as in below questions:
但是,您可以尝试模拟以下问题中的行为:
Create Postgres database on the fly, if it doesn't exists using Hibernate
如果使用 Hibernate 不存在,则动态创建 Postgres 数据库
回答by Thilina Sampath
Try this way
试试这个方法
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
This is work for me.
这对我来说是工作。
From the Automatic schema generationsection of the Hibernate User Guide:
javax.persistence.schema-generation.database.action
Setting to perform SchemaManagementTool actions automatically as part of the SessionFactory lifecycle. Valid options are defined by the externalJpaNamevalue of the Action enum:
none
- No action will be performed.
create
- Database creation will be generated.
drop
- Database dropping will be generated.
drop-and-create
- Database dropping will be generated followed by database creation.
javax.persistence.schema-generation.database.action
设置为作为 SessionFactory 生命周期的一部分自动执行 SchemaManagementTool 操作。有效选项由Action 枚举的externalJpaName值定义:
none
- 不会执行任何操作。
create
- 将生成数据库创建。
drop
- 将产生数据库删除。
drop-and-create
- 将生成数据库删除,然后创建数据库。
there spring.jpa.hibernate.ddl-auto=update
==> update
, you can change according to your scenario.
那里spring.jpa.hibernate.ddl-auto=update
==> update
,您可以根据您的情况进行更改。
回答by Ali Katkar
The problem is about hibernate dialect. You are using old one. You should use newer one like this.
问题是关于休眠方言。你正在使用旧的。你应该像这样使用较新的。
spring.jpa.database-platform=org.hibernate.dialect.PostgreSQL95Dialect
回答by MrOlloyor
Just change
只是改变
from:
从:
@Table(name = "user") || @Entity(name="user")
to:
到:
@Table(name = "users") || @Entity(name="users")
Because PostgreSQL has default "user"
因为 PostgreSQL 有默认的“用户”
回答by Meriam
you can have a schema.sql script with "CREATE SCHEMA IF NOT EXISTS x;"
with
你可以有一个schema.sql文件脚本"CREATE SCHEMA IF NOT EXISTS x;"
与
spring.jpa.properties.hibernate.hbm2ddl.auto=update
It should work
它应该工作