@Column JPA Example

The @Column annotation is used to specify the mapping between a basic entity attribute and the database table column.

We can use the @Column annotation to mention the details of a column in the table.

@Column JPA Annotation Example

The @Column annotation is used to specify the mapping between a basic entity attribute and the database table column:
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;

@Entity
@Table(name = "student")
public class Student {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "id")
    private int id;

    @Column(name = "first_name", length=50, nullable=false, unique=false)
    private String firstName;

    @Column(name = "last_name", length=50, nullable=false, unique=false)
    private String lastName;

    @Column(name = "email")
    private String email;

    public Student() {

    }

    public Student(String firstName, String lastName, String email) {
        this.firstName = firstName;
        this.lastName = lastName;
        this.email = email;
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getFirstName() {
        return firstName;
    }

    public void setFirstName(String firstName) {
        this.firstName = firstName;
    }

    public String getLastName() {
        return lastName;
    }

    public void setLastName(String lastName) {
        this.lastName = lastName;
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    @Override
    public String toString() {
        return "Student [id=" + id + ", firstName=" + firstName + ", lastName=" + lastName + ", email=" + email + "]";
    }
}
The @Column annotation has many elements such as namelengthnullable, and unique.

The name element specifies the name of the column in the table. 
The length element specifies its length. 
The nullable element specifies whether the column is nullable or not, and the unique element specifies whether the column is unique.

If we don't specify this annotation, the name of the field will be considered the name of the column in the table.

Comments