Customize Table and Column Names with Hibernate Annotations
In this article
To customize table and column names with Hibernate annotations, use @Table(name = "your_table_name") on the entity class and @Column(name = "your_column_name") on the field or getter. These annotations override the default naming strategy, giving you explicit control over the database schema.
Why Customize Names?
Hibernate's default naming strategy converts CamelCase class and field names to snake_case (e.g., UserProfile becomes user_profile). While this works for many projects, you often need to customize names to:
- Match an existing legacy database schema that uses different conventions (e.g., all caps, prefixes like
tbl_, or abbreviations). - Comply with database-specific reserved words (e.g.,
user,order,groupare reserved in many SQL dialects). - Align with a team's naming standards that differ from Hibernate's defaults.
- Shorten long names to fit database identifier length limits (e.g., Oracle's 30-character limit).
Without custom annotations, you'd have to rename your Java fields or rely on a global naming strategy, which can be less flexible.
Basic Usage: @Table and @Column
The @Table annotation is placed on the entity class and accepts a name attribute. The @Column annotation is placed on the field or its getter (choose one consistently) and also accepts a name attribute.
@Entity
@Table(name = "user_accounts")
public class User {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "user_id")
private Long id;
@Column(name = "full_name")
private String name;
@Column(name = "email_address")
private String email;
// getters and setters
}
In this example, the entity maps to the user_accounts table, and the fields map to user_id, full_name, and email_address. This works regardless of the default naming strategy.
Using @Table with Additional Attributes
Beyond name, @Table supports other attributes that are useful in real projects:
schema: specifies the database schema (e.g.,@Table(name = "user_accounts", schema = "core")).catalog: specifies the catalog (e.g.,@Table(name = "user_accounts", catalog = "mydb")).uniqueConstraints: defines unique constraints on the table (e.g.,@UniqueConstraint(columnNames = {"email_address"})).indexes: defines indexes (e.g.,@Index(name = "idx_email", columnList = "email_address")).
These are especially helpful when you want Hibernate to generate the schema (using hbm2ddl.auto) and need constraints beyond the default.
Handling Relationships: Join Columns and Join Tables
Customization also applies to foreign keys and many-to-many join tables. For @ManyToOne and @OneToOne associations, use @JoinColumn(name = "fk_column"):
@ManyToOne
@JoinColumn(name = "address_id")
private Address address;
For many-to-many relationships, use @JoinTable to customize both the join table name and its columns:
@ManyToMany
@JoinTable(
name = "user_roles",
joinColumns = @JoinColumn(name = "user_id"),
inverseJoinColumns = @JoinColumn(name = "role_id")
)
private Set<Role> roles;
This gives you full control over the foreign key column names, which is critical when integrating with existing schemas or when you want to avoid ambiguous column names.
Common Pitfalls and Misconceptions
A frequent mistake is placing @Column on both the field and the getter, which can cause Hibernate to map the property twice, leading to errors. Pick one access strategy (field or getter) and stick with it consistently across the entity.
Another misconception is that @Column(name = "...") is required for every field. It's not; you only need it when you want to override the default. However, if you rely on a global naming strategy (like Spring Boot's SpringPhysicalNamingStrategy), be aware that explicit annotations take precedence over the strategy.
Also, note that the name attribute in @Column is case-sensitive in some databases (e.g., PostgreSQL folds unquoted identifiers to lowercase). If you need exact case, you may need to quote the name using backticks in the annotation (e.g., @Column(name = "\"UserID\"")), but this is database-specific and often unnecessary.
How to Choose Between Annotations and Naming Strategy
If you have a handful of exceptions to the default naming, annotations are the right choice. They are explicit, local, and easy to read. However, if you need to change the naming convention globally (e.g., all tables get a tbl_ prefix), consider implementing a custom PhysicalNamingStrategy or ImplicitNamingStrategy instead of annotating every entity.
For example, in a Spring Boot application, you can define a bean that implements PhysicalNamingStrategy to transform all table and column names. But this is a broader solution; annotations are better for one-off exceptions.
Testing Your Custom Names
To verify that your custom names are applied correctly, you can:
- Enable Hibernate's SQL logging (
spring.jpa.show-sql=truein Spring Boot, orhibernate.show_sql=truein Hibernate config) to see the generated DDL and queries. - Use
hibernate.hbm2ddl.auto=update(in development only) to let Hibernate alter the schema, and check the database directly. - Inspect the Hibernate metadata at runtime via
SessionFactoryto confirm the mapped names.
This is especially important when integrating with an existing database to ensure your annotations match the actual schema.
Frequently Asked Questions
Can I use the same column name for different fields in different tables?
Yes, column names are scoped to their table. You can have name in both User and Product tables without conflict. The @Column(name = "...") only affects the mapping for that specific entity.
What if I don't specify @Table? What is the default table name?
If you omit @Table, Hibernate uses the entity class name as the table name, transformed by the current naming strategy. For example, UserProfile becomes user_profile with the default snake_case strategy. If you want a different name, you must use @Table.
Does @Column(name = "...") affect the Java property name?
No. The Java field name remains unchanged. The annotation only maps the field to a different database column. This is useful when you want to keep a meaningful Java name like emailAddress but map it to a legacy column like email_addr.
Can I customize names for embedded objects or collections?
Yes. For @Embeddable objects, you can use @AttributeOverride to customize column names within the embedded object. For collections (like @ElementCollection), you can use @CollectionTable and @Column to customize the join table and column names.
What is the difference between @Table and @Entity(name)?
@Entity(name = "...") sets the entity name used in HQL/JPQL queries (e.g., from UserAccount). @Table(name = "...") sets the physical table name. They are independent; you can have an entity name different from the table name.
Is it safe to use custom names with schema generation?
Yes, Hibernate uses these annotations when generating DDL. However, always test in a development environment before applying to production, especially if you use hbm2ddl.auto=update, because it may not always perfectly alter existing tables.