我正在使用 Hibernate/JPA 并有一个名为 Order 的 @Entity 对象,它使用 Hibernate 的动态表生成指向 MySQL 数据库,即在运行时为实体生成表。当 Hibernate 创建表时,它会为除 Order 实体之外的所有实体创建表。如果我将 Order 实体重命名为其他名称,例如StoreOrder,store_order表创建没问题。
此外,如果我这样做但随后注释 StoreOrder 对象以指定它应该创建的表使用 @Table (name="order") 称为“order”,则不再创建该表。
我知道 order 是一个保留字,但这是它不能创建表的原因吗?考虑到 Hibernate docs 这似乎很奇怪使用名为 Order 的实体示例。
这看起来不像是 MySQL 问题,因为我可以直接在数据库上手动创建一个名为 order 的表。
这是相关的 Order 实体对象定义...
@Entity
@Inheritance(strategy=InheritanceType.TABLE_PER_CLASS)
public class Order extends PersistentEntity {
... rest of POJO def...
}
...以及相应的 Persistence.xml
<?xml version="1.0" encoding="UTF-8"?>
<persistence xmlns="http://java.sun.com/xml/ns/persistence" version="1.0">
<persistence-unit name="store" transaction-type="RESOURCE_LOCAL">
<provider>org.hibernate.ejb.HibernatePersistence</provider>
<mapping-file>conf/jpa/persistence-query.xml</mapping-file>
<!-- Entities -->
...other entities...
<class>ie.wtp.store.model.Order</class>
<class>ie.wtp.store.model.OrderItem</class>
<!-- Hibernate properties -->
<properties>
<property name="hibernate.connection.url" value="jdbc:mysql://localhost:3306/store"/>
<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.dialect" value="org.hibernate.dialect.MySQL5InnoDBDialect"/>
<property name="hibernate.query.factory_class"
value="org.hibernate.hql.classic.ClassicQueryTranslatorFactory"/>
<property name="hibernate.query.substitutions" value="true 1, false 0"/>
<property name="cache.provider_class" value="org.hibernate.cache.NoCacheProvider"/>
<property name="hibernate.max_fetch_depth" value="3"/>
<property name="hibernate.archive.autodetection" value="class"/>
<property name="hibernate.show_sql" value="true"/>
<property name="hibernate.format_sql" value="true"/>
<property name="hibernate.hbm2ddl.auto" value="update"/>
</properties>
</persistence-unit>
</persistence>
如果我将其重命名为 StoreOrder,为什么不创建此 Order 实体但会创建它,有什么想法吗?
干杯,
J:)
最佳答案
ORDER
字是保留关键字,您必须对其进行转义。
在 JPA 1.0 中,没有标准化的方法,Hibernate 特定的解决方案是使用反引号:
@Entity
@Table(name="`Order`")
@Inheritance(strategy=InheritanceType.TABLE_PER_CLASS)
public class Order extends PersistentEntity {
... rest of POJO def...
}
JPA 2.0 对此进行了标准化,语法如下所示:
@Entity
@Table(name="\"Order\"")
@Inheritance(strategy=InheritanceType.TABLE_PER_CLASS)
public class Order extends PersistentEntity {
... rest of POJO def...
}
引用文献
- Hibernate Core 文档
- JPA 2.0 规范
- 2.13 数据库对象的命名
关于java - JPA/Hibernate 无法创建名为 Order 的实体,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3599803/