Suppose you have the following table "shops"
shop_cd | name |
---|---|
0001 | Main store |
0002 | Dictionary store |
0003 | Bunko store |
0004 | Picture book store |
I want a list of stores by specifying WHERE shop_cd IN (0001, 0002)
.
@Getter
@Setter
public class Shop {
private String shopCd;
private String name;
}
public interface ShopMapper {
/**
*Receives a list of store codes and returns a list of stores
*/
@SelectProvider(type = SqlProvider.class, method = "selectByShopCodes")
List<Shop> selectByShopCodes(List<String> shopCodes);
class SqlProvider {
public String selectByShopCodes(List<String> shopCodes) {
final String inParams = getInPhraseParamString(shopCodes, "shopCodes");
SQL sql = new SQL() {
{
SELECT("*");
FROM("shops");
WHERE(String.format("shops.shop_cd IN (%s)", inParams));
ORDER_BY("shop_cd ASC");
}
};
return sql.toString();
}
/**
*Receive the list and IN()Returns the parameter string used in the clause
*Example: #{shopCodes[0]}, #{shopCodes[1]}, #{shopCodes[2]}
*/
private String getInPhraseParamString(List<String> values, String paramName) {
String paramString = "";
int i = 0;
for (String value : values) {
if (i != 0) {
paramString += ",";
}
paramString += String.format("#{%s[%s]}", paramName ,i);
i++;
}
return paramString;
}
}
}
# {list [0]}, # {list [1]}, # {list [2]} ...
according to the length of the list and use them in the IN clause.Recommended Posts