복붙노트

[SPRING] PostgreSQL + Hibernate + Spring 자동 생성 데이터베이스

SPRING

PostgreSQL + Hibernate + Spring 자동 생성 데이터베이스

나는 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로 하여금 자동으로 데이터베이스를 만들도록 할 수 있습니까?

해결법

  1. ==============================

    1.hibernate.hbm2ddl.auto 속성이 당신을 대신하여 속임수를 쓸 것입니다. SessionFactory가 생성 될 때 스키마 DDL을 데이터베이스에 자동으로 유효성을 검사하거나 내 보냅니다. create-drop을 사용하면 SessionFactory가 명시 적으로 닫힐 때 데이터베이스 스키마가 삭제됩니다.

    hibernate.hbm2ddl.auto 속성이 당신을 대신하여 속임수를 쓸 것입니다. SessionFactory가 생성 될 때 스키마 DDL을 데이터베이스에 자동으로 유효성을 검사하거나 내 보냅니다. create-drop을 사용하면 SessionFactory가 명시 적으로 닫힐 때 데이터베이스 스키마가 삭제됩니다.

    Hibernate는 위의 프로퍼티에 대해이 옵션들을 받아 들일 수있다.

    validate : 스키마 유효성을 검사하고 데이터베이스를 변경하지 않습니다.

    update : 스키마를 업데이트합니다.

    create : 스키마를 생성하여 이전 데이터를 삭제합니다.

    create-drop : 세션이 끝날 때 스키마를 삭제합니다.

  2. ==============================

    2.이 방법을 시도해보십시오.

    이 방법을 시도해보십시오.

    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
    

    이것은 나를 위해 일합니다.

    최대 절전 사용자 가이드의 자동 스키마 생성 섹션 :

    there spring.jpa.hibernate.ddl-auto = update ==> update, 시나리오에 따라 바꿀 수 있습니다.

  3. ==============================

    3.Postgres와 달리 mysql은 데이터베이스 생성을 지원하지 않는다.

    Postgres와 달리 mysql은 데이터베이스 생성을 지원하지 않는다.

    따라서 hibernate.hbm2ddl.auto = URL 생성 및 변경 jdbc.url = jdbc : postgresql : // localhost / database? createDatabaseIfNotExist = true 당신을 위해 작동하지 않습니다.

    그러나 다음 질문에서와 같이 동작을 시뮬레이션 해 볼 수 있습니다.

    최대 절전 모드를 사용하여 Postgres 데이터베이스가 존재하지 않는 경우 즉시 작성하십시오.

    PostgreSQL에 존재하지 않는다면 CREATE DATABASE를 시뮬레이션 하시겠습니까?

  4. ==============================

    4."CREATE SCHEMA IF NOT EXISTS x;"와 함께 schema.sql 스크립트를 가질 수 있습니다. 와

    "CREATE SCHEMA IF NOT EXISTS x;"와 함께 schema.sql 스크립트를 가질 수 있습니다. 와

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

    작동해야합니다.

  5. from https://stackoverflow.com/questions/38299685/postgresql-hibernate-spring-auto-create-database by cc-by-sa and MIT license