我正在使用hibernate开发一个系统。在系统中,我有多个类,如下所示:
@Entity
@Table(name = "metric")
public class Metric {
@Id @GeneratedValue
@Column(name = "metric_id")
private int id;
@Column(name = "name")
private String name;
@Column(name = "created_at")
private Date created_at;
@Column(name = "updated_at")
private Date updated_at;
@Column(name = "deleted_at")
private Date deleted_at;
public Metric() {
}
public Metric(int id, String name, Date created_at, Date updated_at, Date deleted_at) {
this.id = id;
this.name = name;
this.created_at = created_at;
this.updated_at = updated_at;
this.deleted_at = deleted_at;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Date getCreated_at() {
return created_at;
}
public void setCreated_at(Date created_at) {
this.created_at = created_at;
}
public Date getUpdated_at() {
return updated_at;
}
public void setUpdated_at(Date updated_at) {
this.updated_at = updated_at;
}
public Date getDeleted_at() {
return deleted_at;
}
public void setDeleted_at(Date deleted_at) {
this.deleted_at = deleted_at;
}
}
所有这些类都有一个自定义命名的id列,就像上面一样。但是,在数据库中" metric_id"字段突然被命名为#34; id"。这适用于所有表格。
我错过了什么吗?
答案 0 :(得分:0)
试试这个
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name="metric_id", unique = true, nullable = false)
private int metric_id;
此外,您必须在 hibernate.cfg.xml 中具有相应的映射:
<session-factory>
...
<mapping class="yourPath.YourJavaClass" />
</session-factory>
阅读它以获得 SessionFactory 对象:
import org.hibernate.SessionFactory;
import org.hibernate.cfg.AnnotationConfiguration;
public class HibernateUtil {
private static SessionFactory sessionFactory = buildSessionFactory();
private static SessionFactory buildSessionFactory() {
try {
return new AnnotationConfiguration().configure().buildSessionFactory();
} catch (Throwable ex) {
System.err.println("Initial SessionFactory creation failed." + ex);
throw new ExceptionInInitializerError(ex);
}
}
public static SessionFactory getSessionFactory() {
return sessionFactory;
}
public static void shutdown() {
sessionFactory.close();
}
}