Java Hibernate:根据实体类自动创建/更新数据库表

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/306806/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 12:55:51  来源:igfitidea点击:

Hibernate: Automatically creating/updating the db tables based on entity classes

javamysqlhibernatejpagroovy

提问by Jason Miesionczek

I have the following entity class (in Groovy):

我有以下实体类(在 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

}

and my persistence.xml:

和我的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>

and the script:

和脚本:

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()

the database Icarusexists, but currently has no tables. I would like Hibernate to automatically create and/or update the tables based on the entity classes. How would I accomplish this?

数据库Icarus存在,但目前没有表。我希望 Hibernate 能够根据实体类自动创建和/或更新表。我将如何做到这一点?

采纳答案by toolkit

I don't know if leaving hibernateoff the front makes a difference.

我不知道离开hibernate前面是否会有所不同。

The referencesuggests it should be hibernate.hbm2ddl.auto

参考表明,它应该是hibernate.hbm2ddl.auto

A value of createwill create your tables at sessionFactory creation, and leave them intact.

create将在 sessionFactory 创建时创建您的表,并保持它们不变。

A value of create-dropwill create your tables, and then drop them when you close the sessionFactory.

create-drop将创建您的表,然后在您关闭 sessionFactory 时删除它们。

Perhaps you should set the javax.persistence.Tableannotation explicitly?

也许您应该javax.persistence.Table明确设置注释?

Hope this helps.

希望这可以帮助。

回答by billjamesdev

You might try changing this line in your persistence.xml from

您可以尝试在您的 persistence.xml 中更改这一行

<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

JavaRanch得到这个

回答by Harbir

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>

回答by user2530633

Hibernate hbm2ddl.auto:

休眠 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

创建 SessionFactory 时自动验证或导出模式 DDL 到数据库。使用 create-drop,当 SessionFactory 显式关闭时,数据库模式将被删除。例如验证| 更新 | 创建 | 创建删除

Please check the linkfor more details.

请查看链接了解更多详情。

回答by thorinkor

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 @Tableannotation!

有一个非常重要的细节,它可能会阻止您的休眠生成表(假设您已经设置了hibernate.hbm2ddl.auto)。您还需要@Table注释!

@Entity
@Table(name = "test_entity")
    public class TestEntity {
}

It has already helped in my case at least 3 times - still cannot remember it ;)

在我的情况下它已经帮助了至少 3 次 - 仍然不记得它;)

PS. Read the hibernate docs - in most cases You will probably not want to set hibernate.hbm2ddl.autoto create-drop, because it deletes Your tables after stopping the app.

附注。阅读休眠文档 - 在大多数情况下,您可能不想设置hibernate.hbm2ddl.autocreate-drop,因为它会在停止应用程序后删除您的表。

回答by Yusuf Aksun

In applicationContext.xml file:

在 applicationContext.xml 文件中:

<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>

回答by DevDio

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

使用 Wildfly 的内存 H2 数据库

回答by AbsoluteDev

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.

为了支持@thorinkor 的答案,我将扩展我的答案,不仅对实体使用 @Table (name = "table_name") 注释,而且实体类的每个子变量都应该用 @Column(name = "col_name") 注释。这导致在旅途中对表格进行无缝更新。

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.

对于那些正在寻找基于 Java 类的休眠配置的人,该规则也适用于基于 Java 的配置(NewHibernateUtil)。希望它可以帮助别人。