In my project, I ran into the issue that I have to use Sql In statement and the value in the in() is dynamic. With mybatis, we can create dynamic sql foreach.
Here is my case:
1. In the mapper class, I define my method:
@Component("twitterTweetMapper")
public interface TweetMapper{
public List<Tweet> getTweetsByOrganizationIds(List<Long> organizationIds);
}
2. In the mapper.xml file, I define my sql statement.
<select id="getTweetsByOrganizationIds" resultType="org.twitter.model.Tweet">
SELECT * FROM TWEET
WHERE ORGANIZATIONID in
<foreach item="item" index="index" collection="list" open="(" separator="," close=")">
#{item}
</foreach>
ORDER BY TWEETCREATEDATE DESC LIMIT 3
</select>
That's all. It's very easy, right?
For more dynamic queries, read the link:
http://loianegroner.com/2011/03/ibatis-mybatis-working-with-dynamic-queries-sql/