Skip to main content

Hibernate : How to use @Column Annotation

Points To Remember


  • @Column annotation is used to define the column name, type, constraints.
  • It should be used with the fields either above the getter or above field declaration.
The @Column annotation can take the following configuration.

PropertyTypeDefault ValueDescription
nameOptional""The name of the column. Defaults to the property or field name
uniqueOptionalfalseWhether the column is a unique key.
nullableOptionaltrueWhether the database column is nullable.
insertableOptionaltrueWhether the column is included in SQL INSERT statements generated by the persistence provider.
updatableOptionaltrueWhether the column is included in SQL UPDATE statements generated by the persistence provider.
columnDefinitionOptional""The SQL fragment that is used when generating the DDL for the column.
tableOptional""The name of the table that contains the column. If absent the column is assumed to be in the primary table.
lengthOptional255The column length. (Applies only if a string-valued column is used.
precisionOptional0The precision for a decimal (exact numeric) column. (Applies only if a decimal column is used.)
scaleOptional0The scale for a decimal (exact numeric) column (Applies only if a decimal column is used.)

How to use @Column Annotation in Hibernate

We will we taking the example of @Entity annotation to show the changes made by @Column annotation.

package com.ekiras.domian;

import com.ekiras.enums.Gender;

import javax.persistence.*;
import java.util.Date;

@Entity
public class User {

@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;

@Column(name = "name",length = 100)
private String name;

@Column(name = "current_age")
private Integer age;

@Column(name = "address",columnDefinition = "text")
private String address;

@Column
private Gender gender;

@Column(name = "email",updatable = false, nullable = false, unique = true)
private String email;

private Long mobile;

@Temporal(value = TemporalType.DATE)
private Date dateCreated;

// GETTERS AND SETTERS
}

The above Entity definition will create the output as shown in the image below.


What @Column annotation did is

  • mapped age to current_age in database.
  • changed address ddl type to text.
  • added nullable and unique constraints to field email.
  • changes name ddl from varchar(255) to varchar(100).

Also read about the following
  • See the use of @Temporal annotation in hibernate.
  • See the how to use columnDefinition property of @Column annotation.


Comments