Swiftorial Logo
Home
Swift Lessons
Matchups
CodeSnaps
Tutorials
Career
Resources

Basic Annotations in Hibernate

Introduction to Annotations

Annotations in Hibernate are a form of metadata that provide information about how Java classes and their properties map to database tables and columns. They make it easier to configure Hibernate without the need for XML configuration files.

Popular Annotations

There are several key annotations in Hibernate that are commonly used. Below are some of the most important ones:

  • @Entity: Marks a class as a Hibernate entity.
  • @Table: Specifies the database table to which the entity is mapped.
  • @Id: Indicates the primary key of the entity.
  • @GeneratedValue: Defines the strategy for primary key generation.
  • @Column: Specifies the mapped column in the database table.

Example of Basic Annotations

Let's create a simple example of a Hibernate entity using the annotations discussed. We will create a Student class that maps to a students table.

import javax.persistence.*;

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

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

    @Column(name = "name", nullable = false)
    private String name;

    @Column(name = "age")
    private int age;

    // Getters and Setters
}
                

Explanation of the Example

In the Student class:

  • The @Entity annotation indicates that this class is a Hibernate entity.
  • The @Table annotation specifies the database table name to which this entity is mapped.
  • The @Id annotation marks the id field as the primary key.
  • The @GeneratedValue annotation defines how the primary key is generated, in this case using the identity strategy.
  • The @Column annotation specifies the column name in the database and additional constraints like nullable.

Conclusion

Basic annotations in Hibernate simplify the process of mapping Java objects to database tables. By utilizing these annotations, developers can achieve cleaner code without the overhead of XML configurations. Mastering these annotations is essential for effective Hibernate usage.