Hibernate uses annotations to map Java classes to database tables. The steps include: adding dependencies, importing annotations, creating entity classes, and mapping properties. For example, the user entity class User is mapped to the users table and the id, username, and password columns are defined. The annotations @Id, @GeneratedValue, @Table, and @Column are used to specify the primary key, primary key generation strategy, table name, and column attributes. This mapping simplifies the interaction between objects and persistence, and Hibernate automatically handles object persistence and retrieval.
Hibernate is a popular object-relational mapping (ORM) framework that uses annotations to map database tables and objects. Java classes map to database tables. This eliminates tedious manual mapping and simplifies the interaction between models and persistence.
Add Hibernate dependency:
org.hibernate hibernate-core 5.6.4.Final
Import necessary annotations:
import javax.persistence.*;
Create entity class:
@Entity @Table(name = "users") public class User { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; private String username; private String password; }
Consider a simple user table with the following columns:
id
: Auto-increment primary keyusername
: Stringpassword
: String## Java code:
@Entity @Table(name = "users") public class User { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; @Column(name = "username", nullable = false, length = 50) private String username; @Column(name = "password", nullable = false, length = 100) private String password; }
SQL table:
CREATE TABLE users ( id INT NOT NULL AUTO_INCREMENT, username VARCHAR(50) NOT NULL, password VARCHAR(100) NOT NULL, PRIMARY KEY (id) );
Useris mapped to the database table
users. Hibernate can automatically handle persistence and retrieval of objects to the database.
The above is the detailed content of How do annotations map database tables and objects in Hibernate?. For more information, please follow other related articles on the PHP Chinese website!