Sobes.tech
Junior — Middle

Can you explain what Java Persistence API is and what it is used for?

sobes.tech AI

Answer from AI

Java Persistence API (JPA) is a specification in Java for managing object-relational mapping (ORM). It allows developers to work with databases through Java objects without delving into SQL query details.

JPA is used for:

  • Saving, updating, deleting, and searching objects in a database.
  • Automatic conversion between Java objects and database tables.
  • Managing the lifecycle of objects and transactions.

Example of using JPA with EntityManager:

@Entity
public class User {
    @Id
    private Long id;
    private String name;
    // getters and setters
}

// In code
EntityManager em = entityManagerFactory.createEntityManager();
em.getTransaction().begin();
User user = new User();
user.setId(1L);
user.setName("Ivan");
em.persist(user);
em.getTransaction().commit();
em.close();

Thus, JPA simplifies working with databases, making the code cleaner and easier to maintain.

Can you explain what Java Persistence API is and what… - sobes.tech