Hibernate 不会设置 id 列名

Posted

技术标签:

【中文标题】Hibernate 不会设置 id 列名【英文标题】:Hibernate won't set id column name 【发布时间】: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”。这适用于所有表格。

我错过了什么吗?

【问题讨论】:

签出this 【参考方案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”字段吗?

以上是关于Hibernate 不会设置 id 列名的主要内容,如果未能解决你的问题,请参考以下文章

运行第二天出现hibernate的错误,org.hibernate.TransactionException: JDBC commit failed at org.hiber

Hibernate学习- 初识

Spring JPA/Hibernate findby 列名返回空集合

休眠代码生成:org.hibernate.HibernateException:没有可用连接时必须设置“hibernate.dialect”

Hibernate 本机查询:无效的列名错误 SQL-17006

hibernate 级联删除