Junior — Middle
Can you explain what Java Persistence API is and how it is used to interact with a database?
sobes.tech AI
Answer from AI
Java Persistence API (JPA) is a standard interface in Java for managing data persistence, that is, for saving, updating, and retrieving objects from a database. JPA allows working with a database through Java objects, using the ORM (Object-Relational Mapping) concept.
Main components of JPA:
- Entity — a class that maps to a table in the database.
- EntityManager — the primary interface for operations on entities (saving, searching, deleting).
- Persistence Unit — configuration defining connection parameters to the database and settings.
Example of using JPA to save an object:
@Entity
public class User {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String name;
// getters and setters
}
// In service code
EntityManager em = entityManagerFactory.createEntityManager();
em.getTransaction().begin();
User user = new User();
user.setName("Ivan");
em.persist(user);
em.getTransaction().commit();
em.close();
Thus, JPA simplifies working with the database by allowing manipulation of objects rather than writing SQL directly.