mybatis系列十二:动态sql的注解配置

 

动态sql也可以采用注解来完成

注解对应的sql类型如下所示

一  先重点来关注查询,用注解进行动态sql查询有两种方式

  1. script标签包围,然后像xml语法一样书写
  2. @Select({
    		"<script>",
    		"select * From student where 1=1",
    		"<when test='gender!=null'>",
    		"and gender=#{gender}",
    		"</when>",
    		"<when test='minAge!=null'>",
    		"and age>=#{minAge}",
    		"</when>",
    		"</script>"
    	})

 测试类代码如下所示

package com.accp.test;

import java.util.HashMap;
import java.util.List;

import org.apache.ibatis.session.SqlSession;

import com.accp.dao.IStudentDao;
import com.accp.entitys.ConditionEntity;
import com.accp.entitys.StuEntity;
import com.accp.entitys.StudentEntity;
import com.accp.utils.MybatisUtil;

public class TestQueryStu03 {
	public static void main(String[] args) {
		SqlSession session=null;
		try {
			session=MybatisUtil.getSession();
			//mapper配置与核心配置文件进行关联
			MybatisUtil.getFactory().getConfiguration().addMapper(IStudentDao.class);
			//获得dao的实例
			IStudentDao stuDao=session.getMapper(IStudentDao.class);
			//传参
			ConditionEntity con=new ConditionEntity(null, "男", 22, null);
			List<StudentEntity> stuList=stuDao.dynQuery(con);
			for(StudentEntity stu:stuList){
				System.out.println(stu.getStuName()+","+stu.getGender()
						+","+stu.getAge());
			}
		} catch (Exception e) {
			e.printStackTrace();
		}finally{
			MybatisUtil.closeSession();
		}
	}
}

参数先传给接口中的方法,再由方法传给动态sql.

2. 用Provider去实现SQL拼接,例如:

这里的注解的意思是:动态sql的提供者是StudentProvider类里面的dynQuery2方法,会自动调用方法的返回值获取.接口中的方法参数会自动传给dynQuery2方法.

StudentProvider类如下所示:

package com.accp.entitys;

import java.util.HashMap;

import org.apache.ibatis.jdbc.SQL;

public class StudentProvider {
	public String dynQuery2(HashMap myParam){
		SQL dynSql=new SQL();
		dynSql.SELECT("*").FROM("student");
		if(myParam.get("gender")!=null){
			dynSql.WHERE("gender=#{gender}");
		}
		if(myParam.get("minAge")!=null){
			dynSql.WHERE("age>=#{minAge}");
		}
		return dynSql.toString();
	}
}

二 接下来看动态更新

MyUpdateProvider类如下:

package com.accp.entitys;

import org.apache.ibatis.jdbc.SQL;

public class MyUpdateProvider {
	public String dynUpdate(StudentEntity stu){
		SQL sql=new SQL();
		sql.UPDATE("student");
		if(stu.getStuName()!=null){
			sql.SET("stuName=#{stuName}");
		}
		if(stu.getGender()!=null){
			sql.SET("gender=#{gender}");
		}
		if(stu.getAge()!=null){
			sql.SET("age=#{age}");
		}
		if(stu.getAddress()!=null){
			sql.SET("address=#{address}");
		}
		if(stu.getDeptIdd()!=null){
			sql.SET("deptIdd=#{deptIdd}");
		}
		sql.WHERE("stuId=#{stuId}");
		return sql.toString();
	}
}

推荐采取sql提供类的方式完成动态sql

怎么样,简单吧

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

御前两把刀刀

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值