k1u
k1u

Reputation: 93

Hibernate won't set id column name

I am developing a system with hibernate. In the system i have multiple classes like the following one:

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

All of these classes have an custom named id column, just like above. However, in the database the "metric_id" field suddenly gets named "id". This applies to all tables.

Am i missing something?

Upvotes: 2

Views: 4303

Answers (1)

user6159261
user6159261

Reputation:

Try this

@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name="metric_id", unique = true, nullable = false)
private int metric_id; 

Also, you must have the respective mapping in hibernate.cfg.xml:

<session-factory>
    ...
    <mapping class="yourPath.YourJavaClass" />

</session-factory>

And read it to get SessionFactory object:

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

Upvotes: 2

Related Questions