Java Persistence API (JPA) in Java

 Java Persistence API (JPA) in Java


JPA is a standard for object-relational mapping (ORM) in Java. It provides a set of annotations and APIs that allow you to map Java classes to database tables, and to perform database operations using Java code.


Example code:


java


@Entity

public class User {

    @Id

    private int id;

    private String name;

    private String email;

    

    // getters and setters

}


EntityManagerFactory factory = Persistence.createEntityManagerFactory("my-persistence-unit");

EntityManager em = factory.createEntityManager();

EntityTransaction tx = em.getTransaction();


tx.begin();

User user = new User();

user.setId(1);

user.setName("Alice");

user.setEmail("alice@example.com");

em.persist(user);

tx.commit();


User retrievedUser = em.find(User.class, 1);

System.out.println("Retrieved user: " + retrievedUser.getName());

No comments:

Post a Comment

The Importance of Cybersecurity in the Digital Age

 The Importance of Cybersecurity in the Digital Age Introduction: In today's digital age, where technology is deeply intertwined with ev...