Hibernate:根据实体类自动创建/更新数据库表 [英] Hibernate: Automatically creating/updating the db tables based on entity classes
问题描述
我有以下实体类(在 Groovy 中):
I have the following entity class (in 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:
and my 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 能够根据实体类自动创建和/或更新表.我将如何做到这一点?
the database Icarus exists, 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?
推荐答案
我不知道将 hibernate
放在前面是否会有所不同.
I don't know if leaving hibernate
off the front makes a difference.
参考 建议它应该是 hibernate.hbm2ddl.auto
create
的值将在 sessionFactory 创建时创建您的表,并保持它们不变.
A value of create
will create your tables at sessionFactory creation, and leave them intact.
create-drop
的值将创建您的表,然后在您关闭 sessionFactory 时删除它们.
A value of create-drop
will create your tables, and then drop them when you close the sessionFactory.
也许您应该设置 javax.persistence.Table
显式注解?
Perhaps you should set the javax.persistence.Table
annotation explicitly?
希望这会有所帮助.
这篇关于Hibernate:根据实体类自动创建/更新数据库表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!