In the previous recipe, you learned how to create a table in the database with attributes. Now, we will take a look at how to declare a column in the table with some useful options.
First of all, we take a basic example of creating a column:
empCode
in the employee
table. As no information is provided for the column name, hibernate uses a variable name. Enter the following code:@Entity public class Employee { @Column private String empCode; // fields and getter/setter }
@Column(name="emp_code") private String empCode;
Now, hibernate will create a column with the name "emp_code"
.
Let's take a look at some useful attributes available for the @Column
annotation.
The length
attribute is used to provide the column with a maximum size.
Here is an example:
@Column(name="emp_code", length=100) private String empCode;
The nullable
attribute accepts a Boolean value. If nullable
is true
, it means that the column contains a NULL
value. It does not accept NULL
if the value of nullable
is set to false
, but the default value of nullable
is true
.
Here is an example:
@Column(name="emp_code", nullable=false) private String empCode;
The unique
attribute also accepts a Boolean value. If unique
is set to true
, hibernate will create a column with a UNIQUE
index. However, the default value is false
.
Here is an example:
@Column(name="emp_code", unique=true) private String empCode;
Here, hibernate creates a UNIQUE
index for the "emp_code"
column.
This is a useful attribute of the annotation. It accepts a string value. We can give it a SQL fragment, which is used at the time of table creation.
Let's consider a useful example.
If we have a date field and want to set a default date but no date is provided at the time of the insertion of the rows, we can use the following code:
@Column(columnDefinition = "timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP") private Date startDate;
Hibernate directly uses this string while creating the table.
We will consider scale and precision together for a better understanding.
The precision
and scale
attributes come into the picture when we have the decimal data type of the column and want to store the value with the decimal point.
Here is an example:
@Column(precision = 7, scale = 2) private BigDecimal salary;
This will create a salary column with the decimal data type and length 7,2
. This means that you can enter a value up to 7
and from among that 2
digit contains decimal part.
There is another annotation, @JoinColumn
, which is used when we want a reference between tables. We will discuss this is in Chapter 5, Working with Associations.