springboot整合mybatis 注解实现

springboot 整合myabtis sql预警xml 配置文件实现请见spring-boot整合myabtis

本节中将实现注解完成sql

首先需要了解几个注解@Select ,@Update ,@Delete,@Insert

以上节获取role 为例

package com.zyc.springboot.dao;

import java.util.List;

import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Select;

import com.zyc.springboot.entity.Role;

@Mapper
public interface RoleDao {

	@Select(value="select id ,role_name as roleName from role where id=#{id}")
	public List getRole(String id);
}

@Upate,@Delete,@Insert同理,上方select语句得到的结果要和Role类中的属性保持一致可使用@Results注解

package com.zyc.springboot.dao;

import java.util.List;

import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Result;
import org.apache.ibatis.annotations.Results;
import org.apache.ibatis.annotations.Select;

import com.zyc.springboot.entity.Role;

@Mapper
public interface RoleDao {

	@Select(value="select id ,role_name from role where id=#{id}")
	@Results({@Result(property="id",column="id"),
	@Result(property="roleName",column="role_name")
	})
	public List getRole(String id);
}

上面这种方法拼写复杂的sql不太方便可以使用@SelectProvider,@UpdateProvider,@DeleteProvider,@InsertProvider

使用@SelectProvider注解如下

package com.zyc.springboot.dao;

import java.util.List;

import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Result;
import org.apache.ibatis.annotations.Results;
import org.apache.ibatis.annotations.SelectProvider;

import com.zyc.springboot.entity.RoleProvider;
import com.zyc.springboot.entity.Role;

@Mapper
public interface RoleDao {

	
	@SelectProvider(type=RoleProvider.class,method="getRole")
	@Results({@Result(property="id",column="id"),
		@Result(property="roleName",column="role_name")
		})
	public List getRole(@Param("id")String id,@Param("name")String name);
}

RoleProvider实现类如下,多个参数要使用Map接收,并且在dao层使用@Param注解与之对应

package com.zyc.springboot.entity;

import java.util.Map;
import org.apache.ibatis.jdbc.SQL;

import com.zyc.springboot.util.StringUtils;

/**
 * 拼接sql类实现
 * @author Administrator
 *
 */
public class RoleProvider {

	 public String getRole(Map param) {
	        SQL sql = new SQL().SELECT("*").FROM("Role");
	        String id= param.get("id").toString();
	        if (id!=null&&!id.trim().equals("")) {
	            sql.WHERE("id = #{id}");
	        }
	        String roleName= param.get("name").toString();
	        if (roleName!= null&&!roleName.trim().equals("")) {
	            sql.WHERE(" role_name LIKE #{roleName}");
	        }
	        System.out.println(sql.toString());
	        return sql.toString();
	    }
}

@UpdateProvider,@DeleteProvider,@InsertProvider同理


你可能感兴趣的:(mybatis,spring-boot)