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.
Property | Type | Default Value | Description |
---|---|---|---|
name | Optional | "" | The name of the column. Defaults to the property or field name |
unique | Optional | false | Whether the column is a unique key. |
nullable | Optional | true | Whether the database column is nullable. |
insertable | Optional | true | Whether the column is included in SQL INSERT statements generated by the persistence provider. |
updatable | Optional | true | Whether the column is included in SQL UPDATE statements generated by the persistence provider. |
columnDefinition | Optional | "" | The SQL fragment that is used when generating the DDL for the column. |
table | Optional | "" | The name of the table that contains the column. If absent the column is assumed to be in the primary table. |
length | Optional | 255 | The column length. (Applies only if a string-valued column is used. |
precision | Optional | 0 | The precision for a decimal (exact numeric) column. (Applies only if a decimal column is used.) |
scale | Optional | 0 | The 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
}
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
Post a Comment