Hibernate : 엔티티 클래스를 기반으로 db 테이블 자동 생성 / 업데이트
다음 엔터티 클래스 (Groovy)가 있습니다.
import javax.persistence.Entity
import javax.persistence.Id
import javax.persistence.GeneratedValue
import javax.persistence.GenerationType
@Entity
public class ServerNode {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
Long id
String firstName
String lastName
}
내 persistence.xml :
<?xml version="1.0" encoding="UTF-8"?>
<persistence xmlns="http://java.sun.com/xml/ns/persistence" version="1.0">
<persistence-unit name="NewPersistenceUnit">
<provider>org.hibernate.ejb.HibernatePersistence</provider>
<properties>
<property name="hibernate.connection.url" value="jdbc:mysql://localhost:3306/Icarus"/>
<property name="hibernate.connection.driver_class" value="com.mysql.jdbc.Driver"/>
<property name="hibernate.connection.username" value="root"/>
<property name="hibernate.connection.password" value=""/>
<property name="hibernate.archive.autodetection" value="class"/>
<property name="hibernate.show_sql" value="true"/>
<property name="hibernate.format_sql" value="true"/>
<property name="hbm2ddl.auto" value="create"/>
</properties>
<class>net.interaxia.icarus.data.models.ServerNode</class>
</persistence-unit>
</persistence>
및 스크립트 :
import javax.persistence.EntityManager
import javax.persistence.EntityManagerFactory
import javax.persistence.Persistence
import net.interaxia.icarus.data.models.ServerNode
def factory = Persistence.createEntityManagerFactory("NewPersistenceUnit")
def manager = factory.createEntityManager()
manager.getTransaction().begin()
manager.persist new ServerNode(firstName: "Test", lastName: "Server")
manager.getTransaction().commit()
Icarus 데이터베이스 가 있지만 현재 테이블이 없습니다. Hibernate가 엔티티 클래스를 기반으로 테이블을 자동으로 생성 및 / 또는 업데이트하기를 바랍니다. 어떻게해야합니까?
hibernate
앞을 떠나는 것이 효과가 있는지 모르겠습니다 .
참조는 그것이 있어야 제안hibernate.hbm2ddl.auto
값은 create
sessionFactory 생성시 테이블을 생성하고 그대로 둡니다.
값은 create-drop
테이블을 만든 다음 sessionFactory를 닫을 때 삭제합니다.
javax.persistence.Table
주석을 명시 적으로 설정해야 할까요?
도움이 되었기를 바랍니다.
You might try changing this line in your persistence.xml from
<property name="hbm2ddl.auto" value="create"/>
to:
<property name="hibernate.hbm2ddl.auto" value="update"/>
This is supposed to maintain the schema to follow any changes you make to the Model each time you run the app.
Got this from JavaRanch
Sometimes depending on how the configuration is set, the long form and the short form of the property tag can also make the difference.
e.g. if you have it like:
<property name="hibernate.hbm2ddl.auto" value="create"/>
try changing it to:
<property name="hibernate.hbm2ddl.auto">create</property>
In my case table was not created for the first time without last property listed below:
<properties>
<property name="hibernate.archive.autodetection" value="class"/>
<property name="hibernate.show_sql" value="true"/>
<property name="hibernate.format_sql" value="true"/>
<property name="hbm2ddl.auto" value="create-drop"/>
<!-- without below table was not created -->
<property name="javax.persistence.schema-generation.database.action" value="drop-and-create" />
</properties>
used Wildfly's in-memory H2 database
There is one very important detail, than can possibly stop your hibernate from generating tables (assuming You already have set the hibernate.hbm2ddl.auto
). You will also need the @Table
annotation!
@Entity
@Table(name = "test_entity")
public class TestEntity {
}
It has already helped in my case at least 3 times - still cannot remember it ;)
PS. Read the hibernate docs - in most cases You will probably not want to set hibernate.hbm2ddl.auto
to create-drop
, because it deletes Your tables after stopping the app.
In applicationContext.xml file:
<bean id="entityManagerFactoryBean" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="dataSource" ref="dataSource" />
<!-- This makes /META-INF/persistence.xml is no longer necessary -->
<property name="packagesToScan" value="com.howtodoinjava.demo.model" />
<!-- JpaVendorAdapter implementation for Hibernate EntityManager.
Exposes Hibernate's persistence provider and EntityManager extension interface -->
<property name="jpaVendorAdapter">
<bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter" />
</property>
<property name="jpaProperties">
<props>
<prop key="hibernate.hbm2ddl.auto">update</prop>
<prop key="hibernate.dialect">org.hibernate.dialect.MySQL5Dialect</prop>
</props>
</property>
</bean>
In support to @thorinkor's answer I would extend my answer to use not only @Table (name = "table_name") annotation for entity, but also every child variable of entity class should be annotated with @Column(name = "col_name"). This results into seamless updation to the table on the go.
For those who are looking for a Java class based hibernate config, the rule applies in java based configurations also(NewHibernateUtil). Hope it helps someone else.
Hibernate hbm2ddl.auto:
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. e.g. validate | update | create | create-drop
Please check the link for more details.
'IT story' 카테고리의 다른 글
ReSharper를 사용하여 기존 인터페이스에 메서드 추출 (0) | 2020.08.26 |
---|---|
XML 파일에서 날짜 / 시간에 사용할 올바른 형식은 무엇입니까? (0) | 2020.08.26 |
스크립트 또는 저장 프로 시저에서 일회용 함수를 만들 수 있습니까? (0) | 2020.08.26 |
기록에 영향을주지 않고 해시 탐색을 사용할 수 있습니까? (0) | 2020.08.26 |
.NET Core에서 쿼리 문자열 구문 분석 및 수정 (0) | 2020.08.26 |