Mybatis注解实现动态sql

使用@InsertProvider,@DeleteProvider,@UpdateProvider,@SelectProvider注解
我们需要把sql语句写到一个类中,类中的方法对应着sql语句,返回类型是String,sql语句用StringBuilder拼接
首先创建一个类

public class WechatUserMapperSqlProvider{
	//在类中写方法,方法中写sql语句
	//StringBuilder可变字符串,配合java代码能进行良好的逻辑处理
	//方法中可以判断,遍历,能实现用xml的所有功能
public String saveWechatUserOrDepartment(WechatUser wechatUser) {
		StringBuilder builder = new StringBuilder("insert into `WECHAT_USER_R_DEPARTMENT`(`WECHAT_USER_ID`, `DEPARTMENT_ID`) ");
		builder.append(" values ");
		StringBuilder dataStr=new StringBuilder();
		for (Long departmentId : wechatUser.getDepartmentIdList()) {
			if(dataStr.length() > 0)
			{
				dataStr.append(",");
			}
			if(departmentId != null)
			{
				dataStr.append(" (#{id,jdbcType=INTEGER}, "+departmentId+") ");				
			}
		}
		builder.append(dataStr.toString());
		return builder.toString();
	}

接下来在接口mapper中引用,很简单

/**
	 * 保存微信用户与单位的关系
	 * @param wechatUser
	 * @return
	 */			
	 //type:利用类的反射机制,method:所写的对应的sql语句,接口和方法也可以互相传值														
	@InsertProvider(type = WechatUserMapperSqlProvider.class, method = "saveWechatUserOrDepartment")
	int saveWechatUser_department(WechatUser wechatUser);

你可能感兴趣的:(Mybatis注解实现动态sql)