Program Tip

Hibernate hbm2ddl.auto 구성의 가능한 값은 무엇이며 무엇을합니까?

programtip 2020. 9. 27. 13:45
반응형

Hibernate hbm2ddl.auto 구성의 가능한 값은 무엇이며 무엇을합니까?


업데이트, 내보내기 및 hibernate.hbm2ddl.auto
업데이트를 사용할 때와 사용하지 않을 때를 알아야 하는 값에 대해 더 많이 알고 싶습니다 . 그리고 대안은 무엇입니까?

다음은 DB를 통해 발생할 수있는 변경 사항입니다.

  • 새 테이블
  • 이전 테이블의 새 열
  • 열이 삭제되었습니다.
  • 열의 데이터 유형이 변경됨
  • 열의 유형이 속성을 변경했습니다.
  • 테이블 삭제
  • 열의 값이 변경됨

각각의 경우에 최상의 솔루션은 무엇입니까?


로부터 커뮤니티 문서 :

hibernate.hbm2ddl.auto SessionFactory가 생성 될 때 스키마 DDL을 자동으로 검증하거나 데이터베이스로 내 보냅니다. create-drop을 사용하면 SessionFactory가 명시 적으로 닫히면 데이터베이스 스키마가 삭제됩니다.

예 : 유효성 검사 | 업데이트 | 만들기 | 드롭 생성

따라서 가능한 옵션 목록은 다음과 같습니다.

  • validate : 스키마 유효성을 검사하고 데이터베이스를 변경하지 않습니다.
  • update : 스키마를 업데이트합니다.
  • create : 스키마를 생성하고 이전 데이터를 삭제합니다.
  • create-drop : 일반적으로 애플리케이션이 중지 될 때 SessionFactory가 명시 적으로 닫히면 스키마를 삭제합니다.

이러한 옵션은 개발자 도구이며 프로덕션 수준의 데이터베이스를 용이하게하기위한 것이 아닙니다. 다음 질문을 살펴 보시기 바랍니다. 최대 절전 모드 : hbm2ddl.auto = 프로덕션 업데이트?


완전히 비활성화하는 문서화되지 않은 "없음"값도 있습니다.


구성 속성이 호출됩니다. hibernate.hbm2ddl.auto

개발 환경에서는 hibernate.hbm2ddl.auto=create-drop배포 할 때마다 깨끗한 데이터베이스를 삭제하고 생성하도록 설정 하여 데이터베이스가 알려진 상태에 있도록합니다.

이론적 hibernate.hbm2ddl.auto=update으로는 모델 변경 사항으로 데이터베이스를 업데이트하도록 설정할 수 있지만 프로덕션 데이터베이스에서는이를 신뢰하지 않습니다. 문서의 이전 버전은 이것이 적어도 실험적이라고 말했습니다. 나는 현재 상태를 모른다.

따라서 프로덕션 데이터베이스의 경우 설정하지 마십시오 hibernate.hbm2ddl.auto. 기본값은 데이터베이스를 변경하지 않는 것입니다. 대신 한 버전에서 다음 버전으로 변경 사항을 적용하는 SQL DDL 업데이트 스크립트를 수동으로 생성합니다.


나는 당신의 db를 업데이트하기 위해 liquibase사용할 것 입니다. hibernate의 스키마 업데이트 기능은 개발자가 새로운 기능을 개발하는 동안에 만 실제로 괜찮습니다. 프로덕션 상황에서는 db 업그레이드를 더 신중하게 처리해야합니다.


꽤 오래된 게시물이지만 주제에 대한 조사를 했으므로 공유를 생각했습니다.

hibernate.hbm2ddl.auto

문서에 따라 4 개의 유효한 값을 가질 수 있습니다.

만들기 | 업데이트 | 확인 | 드롭 생성

다음은 이러한 값으로 표시되는 동작에 대한 설명입니다.

  • create :-스키마를 생성하면 이전에 스키마에있는 데이터 (있는 경우)가 손실됩니다.
  • update :-주어진 값으로 스키마를 업데이트합니다.
  • 유효성 검사 :-스키마 유효성을 검사합니다. DB는 변경되지 않습니다.
  • create-drop :-이전에 존재했던 데이터를 삭제하여 스키마를 생성합니다 (있는 경우). 또한 SessionFactory가 닫힐 때 데이터베이스 스키마를 삭제합니다.

다음은 주목할만한 중요한 사항입니다.

  • 의 경우 갱신 , 경우 스키마는 스키마가 생성 된 DB에 존재하지 않습니다.
  • 의 경우 유효성 검사 스키마가 DB에 존재하지 않는 경우, 그것은 만들어지지 않습니다. 대신 오류가 발생합니다.Table not found:<table name>
  • create-drop의 경우 세션을 닫을 때 스키마가 삭제되지 않습니다. SessionFactory를 닫을 때만 삭제됩니다.
  • 이 속성에 값을 제공하거나 (위에서 설명한 4 개의 값 대신 abc) 그냥 비워두면. 다음과 같은 동작을 보여줍니다.

    -DB에 스키마가없는 경우 :-스키마 생성

    -DB에 스키마가있는 경우 :- 스키마를 업데이트 합니다.


먼저 hbm2ddl구성 속성에 사용할 수있는 값 은 다음과 같습니다.

  • none-작업이 수행되지 않습니다. 스키마가 생성되지 않습니다.
  • create-only -데이터베이스 스키마가 생성됩니다.
  • drop -데이터베이스 스키마는 나중에 삭제되고 생성됩니다.
  • create -데이터베이스 스키마는 나중에 삭제되고 생성됩니다.
  • create-drop-데이터베이스 스키마는 나중에 삭제되고 생성됩니다. 을 닫으면 SessionFactory데이터베이스 스키마가 삭제됩니다.
  • validate -데이터베이스 스키마는 엔티티 매핑을 사용하여 유효성이 검사됩니다.
  • update -기존 데이터베이스 스키마와 엔티티 매핑을 비교하여 데이터베이스 스키마를 업데이트합니다.

나는 전용 블로그 게시물을 가장 일반적인 대한 최대 절전 모드 DDL 생성 전략 :

  1. The hibernate.hbm2ddl.auto="update" is convenient but less flexible if you plan on adding functions or executing some custom scripts.
  2. The most flexible approach is to use Flyway.

However, even if you use Flyway, you can still generate the initial migration script using hbm2ddl. In this article, you can see how you can combine the JPA Entity Model with jOOQ Table Model.


hibernate.hbm2ddl.auto automatically validates and exports DDL to the schema when the sessionFactory is created.

By default, it does not perform any creation or modification automatically on DB. If the user sets one of the below values then it is doing DDL schema changes automatically.

  • create - doing creating a schema

    <entry key="hibernate.hbm2ddl.auto" value="create">
    
  • update - updating existing schema

    <entry key="hibernate.hbm2ddl.auto" value="update">
    
  • validate - validate existing schema

    <entry key="hibernate.hbm2ddl.auto" value="validate">
    
  • create-drop - create and drop the schema automatically when a session is starts and ends

    <entry key="hibernate.hbm2ddl.auto" value="create-drop">
    

If you don't want to use Strings in your app and are looking for predefined constants have a look at org.hibernate.cfg.AvailableSettings class included in the Hibernate JAR, where you'll find a constant for all possible settings. In your case for example:

/**
 * Auto export/update schema using hbm2ddl tool. Valid values are <tt>update</tt>,
 * <tt>create</tt>, <tt>create-drop</tt> and <tt>validate</tt>.
 */
String HBM2DDL_AUTO = "hibernate.hbm2ddl.auto";

I Think you should have to concentrate on the

SchemaExport Class 

this Class Makes Your Configuration Dynamic So it allows you to choose whatever suites you best...

Checkout [SchemaExport]


  • validate: validates the schema, no change happens to the database.
  • update: updates the schema with current execute query.
  • create: creates new schema every time, and destroys previous data.
  • create-drop: drops the schema when the application is stopped or SessionFactory is closed explicitly.

validate: It validates the schema and makes no changes to the DB.
Assume you have added a new column in the mapping file and perform the insert operation, it will throw an Exception "missing the XYZ column" because the existing schema is different than the object you are going to insert. If you alter the table by adding that new column manually then perform the Insert operation then it will definitely insert all columns along with the new column to the Table. Means it doesn't make any changes/alters the existing schema/table.

update: it alters the existing table in the database when you perform operation. You can add or remove columns with this option of hbm2ddl. But if you are going to add a new column that is 'NOT NULL' then it will ignore adding that particular column to the DB. Because the Table must be empty if you want to add a 'NOT NULL' column to the existing table.


Since 5.0, you can now find those values in a dedicated Enum: org.hibernate.boot.SchemaAutoTooling (enhanced with value NONE since 5.2).

Or even better, since 5.1, you can also use the org.hibernate.tool.schema.Action Enum which combines JPA 2 and "legacy" Hibernate DDL actions.

But, you cannot yet configure a DataSource programmatically with this. It would be nicer to use this combined with org.hibernate.cfg.AvailableSettings#HBM2DDL_AUTO but the current code expect a String value (excerpt taken from SessionFactoryBuilderImpl):

this.schemaAutoTooling = SchemaAutoTooling.interpret( (String) configurationSettings.get( AvailableSettings.HBM2DDL_AUTO ) );

… and internal enum values of both org.hibernate.boot.SchemaAutoToolingand org.hibernate.tool.schema.Action aren't exposed publicly.

Hereunder, a sample programmatic DataSource configuration (used in ones of my Spring Boot applications) which use a gambit thanks to .name().toLowerCase() but it only works with values without dash (not create-drop for instance):

@Bean(name = ENTITY_MANAGER_NAME)
public LocalContainerEntityManagerFactoryBean internalEntityManagerFactory(
        EntityManagerFactoryBuilder builder,
        @Qualifier(DATA_SOURCE_NAME) DataSource internalDataSource) {

    Map<String, Object> properties = new HashMap<>();
    properties.put(AvailableSettings.HBM2DDL_AUTO, SchemaAutoTooling.CREATE.name().toLowerCase());
    properties.put(AvailableSettings.DIALECT, H2Dialect.class.getName());

    return builder
            .dataSource(internalDataSource)
            .packages(JpaModelsScanEntry.class, Jsr310JpaConverters.class)
            .persistenceUnit(PERSISTENCE_UNIT_NAME)
            .properties(properties)
            .build();
}

In theory, you can set hibernate.hbm2ddl.auto=update to update your database with changes to your model, but I would not trust that on a production database. An earlier version of the documentation said that this was experimental, at least; I do not know the current status.

따라서 프로덕션 데이터베이스의 경우 hibernate.hbm2ddl.auto를 설정하지 마십시오. 기본값은 데이터베이스를 변경하지 않는 것입니다. 대신 한 버전에서 다음 버전으로 변경 사항을 적용하는 SQL DDL 업데이트 스크립트를 수동으로 생성합니다.

참고 URL : https://stackoverflow.com/questions/438146/what-are-the-possible-values-of-the-hibernate-hbm2ddl-auto-configuration-and-wha

반응형