Mark As Completed Discussion

Hibernate Annotations

Hibernate provides a set of annotations that can be used for advanced mapping configurations. These annotations allow you to define the mapping between Java objects and database tables, specify relationships between entities, and customize various aspects of the persistence behavior.

Let's explore some of the commonly used Hibernate annotations:

  • @Entity: This annotation is used to mark a Java class as an entity, indicating that it should be persisted to a database table. Entities typically represent database tables or views in the object-oriented world.
  • @Table: This annotation allows you to specify the name of the database table associated with an entity. By default, Hibernate uses the entity class name as the table name, but you can use the @Table annotation to provide a different name.
  • @Column: This annotation is used to specify the mapping between a Java attribute and a database column. It allows you to customize various column attributes such as name, length, nullable, and unique.
  • @Id: This annotation is used to mark a Java attribute as the primary key of an entity. Hibernate uses this information to determine the primary key column for the corresponding database table.
  • @GeneratedValue: This annotation is used in conjunction with @Id to specify the strategy for generating primary key values. Common strategies include IDENTITY, SEQUENCE, and TABLE.

Here's an example of a User entity class using Hibernate annotations:

TEXT/X-JAVA
1@Entity
2@Table(name = "users")
3public class User {
4
5    @Id
6    @GeneratedValue(strategy = GenerationType.IDENTITY)
7    private Long id;
8
9    @Column(name = "username", nullable = false, unique = true)
10    private String username;
11
12    @Column(name = "password", nullable = false)
13    private String password;
14
15    // Getters and Setters
16}

In the above example, the User class is marked as an entity using the @Entity annotation, and the @Table annotation specifies the name of the database table as "users".

The id attribute is annotated with @Id and @GeneratedValue to indicate that it is the primary key and the generation strategy is IDENTITY.

The username attribute is mapped to the "username" column in the database table using the @Column annotation, with additional attributes such as nullable and unique.

Similarly, the password attribute is mapped to the "password" column.

These are just a few examples of Hibernate annotations for mapping Java objects to database tables. There are many more annotations available for various mapping scenarios and configuration options.