【问题标题】:Hibernate won't set id column nameHibernate 不会设置 id 列名
【发布时间】:2016-05-23 15:01:19
【问题描述】:

我正在开发一个带有休眠功能的系统。在系统中,我有多个类,如下所示:

@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”字段突然被命名为“id”。这适用于所有表格。

我错过了什么吗?

【问题讨论】:

标签: java database hibernate


【解决方案1】:

试试这个

@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();     
    } 
}

【讨论】:

  • 感谢您的建议。它不起作用。可能是因为您不能在 id 字段上使用 @Column 注释?
  • 是的,您可以使用它。你确定你的数据库表有“metric_id”字段吗?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多