1

I have a entity called Test.java with 70 fields, some of the fields are related to other entities also(through join one to many, many to one, etc assosiations).

I need to have an object of this type but I don't need all the fields just 3 fields out of them one field has foreign key relation relation with other entity.

So, I wrote a native query while executing the query jpa executing other queries also causes taking so much time to complete.

Here is my entity class:

    public Class Test implements Serializable{

    @Id
    private int id;

    @ManyToOne
    @JoinColumn(name = "STATUSID")
    private xxxxx  xxxxx;


   /// other fields, getters and setters

    }   

Here is my native query

  public List<Order> getAllOpenOrders() {

    final String query = "SELECT t.* from T_TEST";

     Query createNativeQuery = em.createNativeQuery(query, Test.class);

    List<Order> resultList = createNativeQuery.getResultList();

    return resultList;
}

How can I get the Order entity object with selected fields, I don't need other fields means I am using only these three fields for my functionlity.

How can I stop other queries execution?

Thank you.

Naveen Kocherla
  • 399
  • 9
  • 27
  • What 'other queries' are being executed ? How did you find out that there are other queries running along side this native query ? – gaganbm Mar 30 '17 at 11:28
  • I am using jpa with eclipse link as persistance provider, I can see the SQL logs in glassfish server logs.. Other queries means this entity has relations with other enties also.. so queries related to other enties also coming in the log file – Naveen Kocherla Mar 30 '17 at 13:21
  • 1
    I think you are probably doing some more queries (not native queries, but hibernate queries, like entitymanager.persist etc) before calling the native query. Hibernate does not execute non-native queries immediately, and when you send a native query, it executes all pending non-native queries as well. – gaganbm Mar 30 '17 at 13:40

1 Answers1

1

You can select only those columns you need using Projections. You do not have to resort to Native Queries for this.

As far as I remember (I had debugged a long time ago), hibernate does a flush before executing a native query. This results in executing all pending queries as well, right before executing the native query. This might be the case in your situation where you are seeing some other queries.

You can use Projections, which are a bit cleaner way to select only required columns.

As answered here : https://stackoverflow.com/a/11626877/564503

Community
  • 1
  • 1
gaganbm
  • 2,663
  • 3
  • 24
  • 36
  • thanks for the response actaully first I tried with the criteria api only the same problem occured, that's why I wrote native query. By the way this query will exucte firstly as this code will be in EJB Scheduler, no other pending queries – Naveen Kocherla Mar 30 '17 at 14:04