休眠:基于实体类自动创建/更新数据库表

2022-08-31 10:00:53

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

}

和我的坚持.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()

数据库伊卡洛斯存在,但目前没有表。我希望Hibernate根据实体类自动创建和/或更新表。我将如何实现这一点?


答案 1

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

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

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

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

也许你应该显式设置javax.persistence.Table注释?

希望这有帮助。


答案 2

您可以尝试在持久性中更改此行.xml

<property name="hbm2ddl.auto" value="create"/>

自:

<property name="hibernate.hbm2ddl.auto" value="update"/>

这应该维护架构,以便在每次运行应用时跟踪对模型所做的任何更改。

JavaRanch获得这个


推荐