mickeymoon mickeymoon - 4 months ago 9
SQL Question

Access public static final string in mybatis sql in mapper files

I have a sql written in a MyBatis mapper file which is something like this:

<select id="somesql">
select a,b,c from tbl_name where d = ?
</select>


The placeholder value for
d
is supposed to be a constant declared in a file called
Constants.java
as:

public static final String d = "d_value";


How do I replace the placeholder with the value without actually passing a parameter in the
<select>
construct? I tried
#{com.pkg.name.Constants.d}
but it didn't work.

No hard coding!!!

Answer

With the out of the box behavior of MyBatis, as far as I know, you can't.

You could try to write an interceptor for the ParameterHandler and inject the value there but this can't always be possible since you can play only with two methods on the parameter handler:

  • getParameterObject which returns the parameter that was sent to the query (can be a constant, a String, a Map, a custom object or even null as it is the case of your example where you don't send a parameter)
  • setParameters where I guess you could try to set the parameter if you know where it is on the prepared statement (which most of the times you might not).

My suggestion is to pass it as parameter to your query. The interceptor features of MyBatis are not very well documented, so you might not get the correct working combination from the start and you can end up with more trouble than it's worth.