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:
- Create a Java class that represents the database table.
- Annotate the class with
@Entityand, if necessary, specify the table name using@Table(name = "table_name"). - Define the class fields that correspond to the table columns.
- Annotate the field that is the primary key with
@Idand, if needed, specify the key generation strategy with@GeneratedValue. - Use other annotations as necessary, such as
@Columnfor 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).