Sobes.tech
Junior — Middle

How to define and configure a new entity in Hibernate for database interaction?

sobes.tech AI

Answer from AI

To define and configure a new Entity in Hibernate for database interaction, follow these steps:

  1. Create a Java class that represents the database table.
  2. Annotate the class with @Entity and, if necessary, specify the table name using @Table(name = "table_name").
  3. Define the class fields that correspond to the table columns.
  4. Annotate the field that is the primary key with @Id and, if needed, specify the key generation strategy with @GeneratedValue.
  5. Use other annotations as necessary, such as @Column for column configuration.

Example:

import jakarta.persistence.Entity;
import jakarta.persistence.Id;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.GenerationType;
import jakarta.persistence.Table;

@Entity
@Table(name = "users")
public class User {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    private String username;
    private String email;

    // getters and setters
}

After this, Hibernate can automatically create, read, update, and delete records in the users table through this class.

Also, ensure that the entity is registered in the Hibernate configuration (for example, in persistence.xml or through Spring settings).

How to define and configure a new entity in Hibernate… - sobes.tech