John Jerrby
John Jerrby

Reputation: 1703

Read Data from JPA the ways to do it

I read in the documentation and i see that to read the jpa data i need to use the following code. this is the only way to read the data from the JPA tables via sql?

 factory = Persistence.createEntityManagerFactory("abc");
EntityManager entityManager = factory.createEntityManager();
Query query = entityManager.createQuery("SELECT p FROM " + className + " p");

Upvotes: 0

Views: 6203

Answers (1)

DannyMo
DannyMo

Reputation: 11984

There are several ways to read data using JPA. The example you provided is using JPQL. Additionally, you can:

  1. execute a native SQL query via EntityManager#createNativeQuery(String nativeSql):

    Query q = entityManager.createNativeQuery("SELECT * FROM MY_TABLE");
    
  2. use the Criteria API

  3. retrieve a single entity by it's primary key using EntityManager#find(...):

    MyObject myObject = entityManager.find(MyObject.class, myObectId);
    

Upvotes: 2

Related Questions