Reputation: 872
I use PostrgeSQL 9.6 and MyBatis 3.1 (under there is also Java 8 and Spring), and I need to execute a custom query, which I create dynamically with a StringBuilder because of it's complexity.
How can I pass it to my class mapper.xml file ?
I've heard about @SelectProvider, but ? can't find complete examples... Can someone give me a step by step guide ?
I was also reading of The SQL Builder Class, of MyBatis, following the official guide but I miss how to launch that query/object I've created. By the way this doesn't seems the right way to me, because of the complexity of the query I have to build. Following the guide it seems I can't use contidional operators like IF or FOR to create the query string... So it can't work for my use.
thanks.
Upvotes: 1
Views: 5999
Reputation: 31
<select id="methodName" resultMap="alarmPieEntry">
${your_raw_sql}
</select>
Just use ${your_raw_sql}
variables in myClass_mapper.xml
file , don't use #{your_raw_sql}
.
Upvotes: 1
Reputation: 46
I only use @SelectProvider for java annotation ,this is a easy way to use it , this is my simple example earlier this year
package com.mybatis;
import java.util.Map;
import java.util.logging.Logger;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.jdbc.SQL;
public class SqlProvider {
public String sqlProvider(Map<String, Object> map){
Logger.getLogger(SqlProvider.class.getName()).info("select * from student where id="+map.get("0"));
return "select * from student where id="+map.get("0");
}
public String findById(@Param("id") int id){
return new SQL(){{
SELECT("id,name,info");
FROM("student");
WHERE("id="+id);
}
}.toString();
}
}
you can use a string produce your sql query ,but also new SQL(){{some clauses such as SELECT(string),WHERE(string) etc. }}.toString();
we can use @SelectProvider(type=Class,method="methodName") specified class and method
package com.mybatis;
import java.util.List;
import java.util.Map;
import org.apache.ibatis.annotations.Delete;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Options;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Result;
import org.apache.ibatis.annotations.Results;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.annotations.SelectProvider;
import org.apache.ibatis.annotations.Update;
/*
*
*Stu is an entity map to your table in db
*
*/
@Mapper
public interface StuMapper {
@SelectProvider(type=SqlProvider.class,method="sqlProvider")
public Stus sqlProvider(Map<String, Object> map);
@SelectProvider(type=SqlProvider.class,method="findById")
public Stus findById_(@Param("id") int id);
}
Last , using you mapper .
more details ,see https://github.com/v5developer/maven-framework-project/blob/master/reference/Java.Persistence.with.MyBatis.3.pdf
especially in chapter 4.
Upvotes: 2