我创建了 MySQL DB 架构,并且正在使用 Hibernate 逆向工程文件来创建带注释的域对象 (.java)。尽管文件已正确生成,但它在某种程度上缺少 ID 字段的“生成器”注释。
下面是我的 hibernate.reveng.xml:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE
hibernate-reverse-engineering PUBLIC
"-//Hibernate/Hibernate Reverse
Engineering DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-reverse-engineering-3.0.dtd"
<hibernate-reverse-engineering>
<table-filter match-name="products" match-catalog="test"></table-filter>
<table catalog="test" name="products">
<primary-key>
<generator class="native"></generator>
<key-column name="product_id"property="product_id" />
</primary-key>
</table>
</hibernate-reverse-engineering>
以及生成的类文件(Products.java):
// default package
// Generated Jan 21, 2011 8:27:16 PM by Hibernate Tools 3.3.0.GA
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
/**
* Products generated by hbm2java
*/
@Entity
@Table(name = "products", catalog = "test")
public class Products implements java.io.Serializable {
private String productId;
private String productName;
public Products() {
}
public Products(String productId) {
this.productId = productId;
}
public Products(String productId, String productName) {
this.productId = productId;
this.productName = productName;
}
@Id
@Column(name = "product_id", unique = true, nullable = false, length = 50)
public String getProductId() {
return this.productId;
}
public void setProductId(String productId) {
this.productId = productId;
}
@Column(name = "product_name", length = 200)
public String getProductName() {
return this.productName;
}
public void setProductName(String productName) {
this.productName = productName;
}
}
我的 hibernate.reveng.xml 文件中是否缺少某些内容,或者 hibernate 没有为“生成器”生成注释?
您需要检查“ejb3”或在配置中添加:
<hbm2java jdk5="true" ejb3="true" />
<key-column name="product_id" property="product_id" />
这里有问题。这部分是正确的:
key-column name="product_id"
,它映射到数据库列product_id
,但这部分是错误的:property="product_id"
,这是Java属性,称为productId
,而不是product_id
。这是正确的值:
<key-column name="product_id" property="productId" />
是的:据我所知,自动生成仅适用于数字类型。
添加后这对我有用
hibernate.reveng.xml
<table catalog="test" name="products">
<primary-key>
<generator class="identity"/>
<key-column name="product_id" property="productId"/>
</primary-key>
</table>
那么生成的类将会是这样的
@Id
@GeneratedValue(strategy=IDENTITY)
@Column(name="id", unique=true, nullable=false)
public Long getId() {
return this.id;
}