In Hibernate, you can customize table and column names using JPA annotations such as @Table
and @Column
. These annotations allow you to define how your entity classes map to the database tables and columns. Here’s how you can do it:
Customize the Table Name
To specify a custom table name, use the @Table
annotation on the class level. You define the table name by setting the name
attribute of the @Table
annotation.
import jakarta.persistence.Entity;
import jakarta.persistence.Table;
@Entity
@Table(name = "custom_table_name")
public class MyEntity {
// Other fields and methods
}
In this example, the associated database table for the MyEntity
class will be named custom_table_name
.
Customize the Column Names
To customize column names, use the @Column
annotation on the field or property. You can specify the name of the column by setting the name
attribute of the annotation.
import jakarta.persistence.Entity;
import jakarta.persistence.Id;
import jakarta.persistence.Column;
@Entity
public class MyEntity {
@Id
private Long id;
@Column(name = "custom_column_name")
private String myField;
// Getters and Setters
}
Here, the myField
field will map to the column custom_column_name
in the database.
Complete Example
Below is a complete example demonstrating both:
import jakarta.persistence.Entity;
import jakarta.persistence.Id;
import jakarta.persistence.Table;
import jakarta.persistence.Column;
@Entity
@Table(name = "custom_table_name")
public class MyEntity {
@Id
private Long id;
@Column(name = "custom_column_name")
private String customField;
@Column(name = "date_of_creation", nullable = false, unique = true)
private String creationDate;
// Getters and Setters
}
- The
@Table
annotation maps the class to a custom table name (custom_table_name
). - The
@Column
annotation maps the fields to custom column names (custom_column_name
anddate_of_creation
). - Optional attributes like
nullable
,unique
,length
, etc., allow further customization.
Notes
- Default Naming: If you omit the
@Table
or@Column
annotations, Hibernate will use default naming strategies (usually camelCase names are converted to snake_case for the database). - Schema or Catalog: You can also specify a schema or catalog in the
@Table
annotation:@Table(name = "custom_table_name", schema = "my_schema")
- Column Options: The
@Column
annotation includes additional options like:nullable
: Whether the column allows nulls.unique
: Whether the column should have a unique constraint.length
: The length of the column (useful forVARCHAR
columns).precision
andscale
: ForDECIMAL
andNUMERIC
columns.
This level of customization gives you precise control over how your Java entities are mapped to database tables and columns.