Home Python C Language C ++ HTML 5 CSS Javascript Java Kotlin SQL DJango Bootstrap React.js R C# PHP ASP.Net Numpy Dart Pandas Digital Marketing

EntityManager and JPQL (Java Persistence Query Language)


In Java Persistence API (JPA), the EntityManager is the primary interface for interacting with the persistence context. JPQL (Java Persistence Query Language) is used to query entities using object-oriented syntax rather than SQL. This article explains these concepts with examples.

Step 1: Understanding EntityManager

The EntityManager interface provides methods to manage entity lifecycle and perform database operations. Some key methods include:

Example: Using EntityManager

First, set up the persistence.xml file:

            <persistence xmlns="http://xmlns.jcp.org/xml/ns/persistence" version="2.1">
                <persistence-unit name="examplePU">
                    <properties>
                        <property name="javax.persistence.jdbc.url" value="jdbc:mysql://localhost:3306/jpa_example"/>
                        <property name="javax.persistence.jdbc.user" value="root"/>
                        <property name="javax.persistence.jdbc.password" value="password"/>
                        <property name="javax.persistence.jdbc.driver" value="com.mysql.cj.jdbc.Driver"/>
                        <property name="hibernate.hbm2ddl.auto" value="update"/>
                        <property name="hibernate.show_sql" value="true"/>
                    </properties>
                </persistence-unit>
            </persistence>
        

Define an entity class:

            import javax.persistence.Entity;
            import javax.persistence.Id;
            import javax.persistence.GeneratedValue;
            import javax.persistence.GenerationType;

            @Entity
            public class Product {
                @Id
                @GeneratedValue(strategy = GenerationType.IDENTITY)
                private int id;
                private String name;
                private double price;

                // Getters and setters
                public int getId() {
                    return id;
                }

                public void setId(int id) {
                    this.id = id;
                }

                public String getName() {
                    return name;
                }

                public void setName(String name) {
                    this.name = name;
                }

                public double getPrice() {
                    return price;
                }

                public void setPrice(double price) {
                    this.price = price;
                }
            }
        

Using EntityManager to persist data:

            import javax.persistence.EntityManager;
            import javax.persistence.EntityManagerFactory;
            import javax.persistence.Persistence;

            public class MainApp {
                public static void main(String[] args) {
                    EntityManagerFactory emf = Persistence.createEntityManagerFactory("examplePU");
                    EntityManager em = emf.createEntityManager();

                    Product product = new Product();
                    product.setName("Smartphone");
                    product.setPrice(699.99);

                    em.getTransaction().begin();
                    em.persist(product);
                    em.getTransaction().commit();

                    em.close();
                    emf.close();

                    System.out.println("Product saved successfully!");
                }
            }
        

Step 2: Introduction to JPQL

JPQL (Java Persistence Query Language) is a query language for entities. Unlike SQL, it uses entity names and field names instead of table and column names. JPQL can be used for retrieval, updates, and deletions.

JPQL syntax:

Example: Retrieving Data Using JPQL

            import javax.persistence.EntityManager;
            import javax.persistence.EntityManagerFactory;
            import javax.persistence.Persistence;
            import javax.persistence.Query;
            import java.util.List;

            public class JPQLExample {
                public static void main(String[] args) {
                    EntityManagerFactory emf = Persistence.createEntityManagerFactory("examplePU");
                    EntityManager em = emf.createEntityManager();

                    em.getTransaction().begin();

                    // JPQL query
                    Query query = em.createQuery("SELECT p FROM Product p WHERE p.price > :minPrice");
                    query.setParameter("minPrice", 500.00);
                    List<Product> products = query.getResultList();

                    for (Product product : products) {
                        System.out.println(product.getName() + " - " + product.getPrice());
                    }

                    em.getTransaction().commit();
                    em.close();
                    emf.close();
                }
            }
        

Step 3: Updating and Deleting Data Using JPQL

Updating Data

            em.getTransaction().begin();

            Query updateQuery = em.createQuery("UPDATE Product p SET p.price = :newPrice WHERE p.name = :name");
            updateQuery.setParameter("newPrice", 799.99);
            updateQuery.setParameter("name", "Smartphone");
            int rowsUpdated = updateQuery.executeUpdate();

            em.getTransaction().commit();
            System.out.println("Rows updated: " + rowsUpdated);
        

Deleting Data

            em.getTransaction().begin();

            Query deleteQuery = em.createQuery("DELETE FROM Product p WHERE p.name = :name");
            deleteQuery.setParameter("name", "Smartphone");
            int rowsDeleted = deleteQuery.executeUpdate();

            em.getTransaction().commit();
            System.out.println("Rows deleted: " + rowsDeleted);
        

Step 4: Named Queries

Named queries are predefined JPQL queries with fixed syntax. They are defined using the @NamedQuery annotation.

            @Entity
            @NamedQuery(name = "Product.findAll", query = "SELECT p FROM Product p")
            public class Product {
                // Fields, getters, and setters
            }

            // Using NamedQuery
            Query namedQuery = em.createNamedQuery("Product.findAll");
            List<Product> products = namedQuery.getResultList();
        

Conclusion

The EntityManager interface and JPQL are core components of JPA, enabling developers to interact with databases using object-oriented concepts. Understanding their usage helps create efficient and maintainable data-driven applications.



Advertisement





Q3 Schools : India


Online Complier

HTML 5

Python

java

C++

C

JavaScript

Website Development

HTML

CSS

JavaScript

Python

SQL

Campus Learning

C

C#

java