java - How to use PreparedStatement efficiently? -


i use dao pattern , have class sql request particular table , jpa entity. have example like:

public class mydao {      @persistencecontext(name = "mycontext")     private entitymanager entitymanager;      public list<myentity> find(string code)  {          return getentitymanager()             .createquery("from myentity e e.code = :code")             .setparameter("code", code)             .getresultlist();      }  } 

but know can use named query directly on entity class static method (i don't way):

@entity @table @namedqueries({     @namedquery(name = "find", query = "from myentity e e.code = :code") }) public class myentity {      ...      public static list<myentity> find(entitymanager entitymanager, string code) {          return entitymanager.createnamedquery("find", myentity.class)             .setparameter("code", code)             .getresultlist();      }  } 

is 1 of method better other 1 ? if want execute same sql query thousands of times in same transaction, both methods keep in jpa memory (or somewhere else) prepared statement ? seems practise in case. think second method because it's static not first one. wrong ?

the advantage declaritively defined queries via @namedquery precompiled, can cached within secondary cache , syntactically validated on startup if enable within persistence.xml using jpa non-hibernate specific api.

so if plan on executing query, using jpa, best use namedquery , cache query.

so jpa using hibernate this:

            @namedquery(name="abstractbasequestion.findallinstancesbygroupid", query="select q abstractbasequestion q q.istemplate = false", hints={@queryhint(name="org.hibernate.cacheable", value="true"),@queryhint(name="org.hibernate.cachemode", value="normal"),}), 

within persistence.xml hibernate can validate these @namedqueries on startup:

      <property name="hibernate.hbm2ddl.auto" value="validate"/> 

now first method suggested can cached , precompiled if use hibernate session api. imagine there equivalents on eclipselink , other orm's @ point using non-jpa features make moving 1 jpa implementation difficult.

if don't implementation specific work query going not cached , pay performance penalty.

i hope helps.


Comments

Popular posts from this blog

java - pagination of xlsx file to XSSFworkbook using apache POI -

Unlimited choices in BASH case statement -

apache - How do I stop my index.php being run twice for every user -