Question

I am trying to formulate a dynamic query in MyBatis-3.2. The query involves an 'IN' clause where a list of items is passed. MyBatis does support 'IN' clause via foreach construct. The query is going to be used very frequently with variable sized list of items. Also, I do not want oracle to hard parse this sql query each time.

So, here are my concerns -

1) Foreach in MyBatis is hard parsed or soft parsed?

2) If it is soft parsed, when is the values substituted to the list of IN clause?

3) If it is hard parsed, is there a work around to support this use case? Can we bind the list to a variable to support soft parsing in this case?

I have search on web regarding all these concerns but could not find any luck. Any comments on this would be of great help. :)

Thanks in Advance,

No correct solution

OTHER TIPS

From what I know, MyBatis will substitute your foreach before the SQL is sent to the database to process. It first substitutes all params that you provide and process all the foreach, if etc. tags and then sends the complete SQL to the database

First of all, before invest significant effort into this make sure parsing is really a bottleneck. Network round-trip and disk access are usually add much more to query execution time.

So the first thing you need to do is to measure and guide your work by measurement to avoid premature optimization.

Think about foreach in mybatis as a way to construct query string (which you can do also in java with more verbosity) which then is submitted to database for execution. soft/hard parse make sense only during query processing in database so mybatis has nothing to do with that.

There are some ways to overcome SQL limitation regarding IN clause. First of all follow some general guidelines for simplification of parsing and/or reusing of parsed statements:

  1. If possible do not use IN at all. Think where parameters to IN come from. Are they come as a result of some query? Can you merge two queries and do not pass list to IN?
  2. Use simple queries. If the query is simple the 'hard' phase of parsing will also take less time.

You may also try to create stored procedure which takes array and returns result set. This will definitely allow you to reuse parsed queries however add some complexity and potentially overhead to query processing which require measurement if it makes sense.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top