mybatis provider list 参数的使用

使用mybatis provider 时因为传入的参数只能是map类型,所以如果查询条件中有list就需要放入map中再传入

记录一下传入list参数后如何获取list参数中的值

首先取得传入的list参数

final List<Integer> userIds = params.get("userIds")==null?null: (List<Integer>) params.get("userIds");
然后在拼接sql语句的时候使用userIds[0]的方式拼接,生成sql语句之后就能自动按照list的顺序将值赋给sql语句
if (userIds != null && userIds.size()>0) {
                    String str = "";
                    for (int i = 0; i < userIds.size(); i++) {
                        if (Objects.equals(str, "")) {
                            str = "(#{userIds["+i+"]}";
                        } else {
                            str += ", #{userIds["+i+"]}";
                        }
                    }
                    str += ")";
                    WHERE("u.userid in "+str);
                }

顺便,写一下子查询

new SQL(){{
                SELECT("*");
                FROM("user u");
                JOIN("("+new SQL(){{
                    SELECT("userid,finishyear,ROUND(AVG(score)) as avgyear");
                    FROM("work");
                    WHERE("finishtime is NOT NULL");
                    if (finishyear != null) {
                        WHERE("finishyear=#{finishyear}");
                    }
                    GROUP_BY("userid,finishyear");
                }}.toString()+") y on u.userid = y.userid");
}}.toString();


顺便,再写一下mybatis generator生成provider 时自定义分页的添加

在自定义分页类中重写providerSelectByExampleWithBLOBsMethodGenerated和providerSelectByExampleWithoutBLOBsMethodGenerated方法即可

一下是分页全部代码,BootPage为自定义类有offset和limit两个属性即可

/**
 * 
 * MyBatise针对MySQL的分页插件
 * 
 * @author Helios
 * @date 2014年11月20日 下午2:10:55
 * 
 */

public class MySQLPaginationPlugin extends PluginAdapter
{

	/**
	 * Page类所在的类路径:其中Page类中一定要有begin和end属性(即:开始记录位置和结束记录位置)
	 */
	public static final String pageClassPath = "com.partwork.common.plugin.page.BootPage";

	/**
	 * 给自动生成Example对象添加page对象的set和get方法
	 * @param topLevelClass
	 * @param introspectedTable
	 * @return
	 */
	@Override
	public boolean modelExampleClassGenerated(TopLevelClass topLevelClass, IntrospectedTable introspectedTable)
	{
		// add field, getter, setter for limit clause
		addPage(topLevelClass, introspectedTable, "page");
		return super.modelExampleClassGenerated(topLevelClass, introspectedTable);
	}


	/**
	 * 生成xml文件SelectByExample方法自动添加分页节点
	 * @param element
	 * @param introspectedTable
	 * @return
	 */
	@Override
	public boolean sqlMapSelectByExampleWithoutBLOBsElementGenerated(XmlElement element, IntrospectedTable introspectedTable)
	{
		XmlElement page = new XmlElement("if");
		page.addAttribute(new Attribute("test", "page != null"));
		page.addElement(new TextElement("limit #{page.offset} , #{page.limit}"));
		element.addElement(page);

		return super.sqlMapUpdateByExampleWithoutBLOBsElementGenerated(element, introspectedTable);
	}

	@Override
	public boolean providerSelectByExampleWithBLOBsMethodGenerated(Method method, TopLevelClass topLevelClass, IntrospectedTable introspectedTable) {
		addLimitLines(method, topLevelClass, introspectedTable);
		return super.providerSelectByExampleWithBLOBsMethodGenerated(method, topLevelClass, introspectedTable);
	}

	@Override
	public boolean providerSelectByExampleWithoutBLOBsMethodGenerated(Method method, TopLevelClass topLevelClass, IntrospectedTable introspectedTable) {

		addLimitLines(method, topLevelClass, introspectedTable);
		return super.providerSelectByExampleWithoutBLOBsMethodGenerated(method, topLevelClass, introspectedTable);
	}

	private void addLimitLines(Method method, TopLevelClass topLevelClass, IntrospectedTable introspectedTable) {
		List<String> limits = Arrays.asList(
		"if (example != null && example.getPage() != null) {",
				"return sql.toString()+\" limit \"+example.getPage().getOffset()+\",\"+example.getPage().getLimit();",
			"}"
		);
		method.addBodyLines(method.getBodyLines().size()-1,limits);
	}

	/**
	 * 对Example对象添加page属性
	 * @param topLevelClass
	 * @param introspectedTable
	 * @param name
	 */
	private void addPage(TopLevelClass topLevelClass, IntrospectedTable introspectedTable, String name)
	{
		topLevelClass.addImportedType(new FullyQualifiedJavaType(pageClassPath));
		CommentGenerator commentGenerator = context.getCommentGenerator();
		Field field = new Field();
		field.setVisibility(JavaVisibility.PROTECTED);
		field.setType(new FullyQualifiedJavaType(pageClassPath));
		field.setName(name);
		commentGenerator.addFieldComment(field, introspectedTable);
		topLevelClass.addField(field);
		char c = name.charAt(0);
		String camel = Character.toUpperCase(c) + name.substring(1);
		Method method = new Method();
		method.setVisibility(JavaVisibility.PUBLIC);
		method.setName("set" + camel);
		method.addParameter(new Parameter(new FullyQualifiedJavaType(pageClassPath), name));
		method.addBodyLine("this." + name + "=" + name + ";");
		commentGenerator.addGeneralMethodComment(method, introspectedTable);
		topLevelClass.addMethod(method);
		method = new Method();
		method.setVisibility(JavaVisibility.PUBLIC);
		method.setReturnType(new FullyQualifiedJavaType(pageClassPath));
		method.setName("get" + camel);
		method.addBodyLine("return " + name + ";");
		commentGenerator.addGeneralMethodComment(method, introspectedTable);
		topLevelClass.addMethod(method);
	}



	/**
	 * This plugin is always valid - no properties are required
	 */
	public boolean validate(List<String> warnings)
	{
		return true;
	}
}
生成xml的插件内容使用,请参考:
http://blog.csdn.net/xzknet/article/details/44158009




在Java中使用MyBatis进行批量修改操作可以通过以下步骤实现: 1. 首先,确保你已经正确配置了MyBatis和数据库连接。 2. 创建一个Mapper接口,用于定义批量修改的方法。在该接口中,使用`@UpdateProvider`注解指定一个提供SQL语句的类。 ```java public interface MyMapper { @UpdateProvider(type = MyProvider.class, method = "updateBatch") void updateBatch(List<YourEntity> entityList); } ``` 3. 创建一个提供SQL语句的类,该类需要实现`org.apache.ibatis.annotations.Provider`接口,并且包含一个名为`updateBatch`的方法。 ```java public class MyProvider implements Provider { public String updateBatch(Map<String, Object> parameter) { List<YourEntity> entityList = (List<YourEntity>) parameter.get("list"); StringBuilder sb = new StringBuilder(); sb.append("UPDATE your_table SET column1 = CASE id "); for (YourEntity entity : entityList) { sb.append("WHEN ").append(entity.getId()).append(" THEN ").append(entity.getColumn1()); } sb.append(" END WHERE id IN ("); for (YourEntity entity : entityList) { sb.append(entity.getId()).append(","); } sb.deleteCharAt(sb.length() - 1); sb.append(")"); return sb.toString(); } } ``` 4. 在你的代码中,通过`SqlSession`对象获取Mapper接口的实例,并调用批量修改方法。 ```java SqlSession sqlSession = sqlSessionFactory.openSession(); MyMapper myMapper = sqlSession.getMapper(MyMapper.class); myMapper.updateBatch(entityList); sqlSession.commit(); sqlSession.close(); ``` 这样,你就可以使用MyBatis进行批量修改操作了。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值