Junior — Middle
Could you explain what an Entity is in the context of JPA and how it is used for data mapping?
sobes.tech AI
Answer from AI
In the context of JPA (Java Persistence API), an Entity is a class that maps to a table in a database. Each object of this class corresponds to a single record (row) in the table.
Entities are used for working with data at the object level, and JPA automatically translates operations on objects into SQL queries to the database.
To create an Entity class, it is annotated with @Entity, and a primary key is specified using @Id.
Example:
import javax.persistence.Entity;
import javax.persistence.Id;
@Entity
public class User {
@Id
private Long id;
private String name;
// getters and setters
public Long getId() { return id; }
public void setId(Long id) { this.id = id; }
public String getName() { return name; }
public void setName(String name) { this.name = name; }
}
Thus, JPA allows working with the database through objects, simplifying development and code maintenance.