Dynamic query with HibernateCritera API & Oracle - performance

后端 未结 2 1850
醉梦人生
醉梦人生 2021-01-23 07:45

I have to use Hibernate and retrieve data from Oracle but the problem is, that the number of parameters passed to the query is not always the same.

For the sake of simpl

2条回答
  •  花落未央
    2021-01-23 07:56

    There are a couple of things here. First of all, you cannot bind an IN list, at least I am pretty sure you cannot. I suspect Hibernate is using some sort of trick you put your array contents into a static inlist Oracle can use.

    Secondly if this query is executed with lots of different parameters, you must you bind variables or the performance of the entire database will suffer.

    That said, there is a way to bind an IN list using a 'trick' which Tom Kyte describes on his blog -

    http://tkyte.blogspot.com/2006/01/how-can-i.html

    The code in there looks like:

    ops$tkyte@ORA10GR2> with bound_inlist
    2  as
    3  (
    4  select
    5    substr(txt,
    6           instr (txt, ',', 1, level  ) + 1,
    7           instr (txt, ',', 1, level+1) - instr (txt, ',', 1, level) -1 )
    8           as token
    9    from (select ','||:txt||',' txt from dual)
    10  connect by level <= length(:txt)-length(replace(:txt,',',''))+1
    11  )
    12  select *
    13    from all_users
    14   where user_id in (select * from bound_inlist);
    
    USERNAME                          USER_ID CREATED
    ------------------------------ ---------- ---------
    SYSTEM                                  5 30-JUN-05
    OPS$TKYTE                             104 20-JAN-06
    

    The part:

    12  select *
    13    from all_users
    14   where user_id in (select * from bound_inlist);
    

    Is basically where your query goes. The bit above is the trick which splits the comma separated string into a list of values. Instead of binding a list into the :txt placeholder, you would need to convert the list to a string and just bind that.

    Are you sure the difference in query times isn't due to caching or load variations on the machine? Parsing the query will take a little time, but several seconds is a long time.

提交回复
热议问题