MyBatis 3.4.5及以上涕刚,支持向@SelectProvider對(duì)象方法傳遞泛型,通過ProviderContext對(duì)象
一、通用Mapper
通過@InsertProvider,@UpdateProvider,@DeleteProvider 和@SelectProvider等注解實(shí)現(xiàn)
@SelectProvider示例
package com.my.world.common.mybatis.mapper;
import com.my.world.common.mybatis.provider.CommonSqlProvider;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.SelectProvider;
public interface CommonBaseMapper<T> {
@SelectProvider(type = CommonSqlProvider.class, method = "selectById")
T selectById(@Param("id") String id);
}
public class CommonSqlProvider {
private Class getPoClass(ProviderContext providerContext) {
Class mapperType = providerContext.getMapperType();
ParameterizedType genericSuperclass = (ParameterizedType) mapperType.getGenericInterfaces()[0];
return (Class) genericSuperclass.getActualTypeArguments()[0];
}
public String selectById(Map<String, Object> para, ProviderContext providerContext) {
Class poClass = getPoClass(providerContext);
Annotation annotation = poClass.getAnnotation(TableName.class);
String tableName = annotation == null ? poClass.getName().toLowerCase() : ((TableName) annotation).value();
String idName = null;
SQL sql = new SQL();
for (Field field : poClass.getDeclaredFields()) {
String fieldName = DBUtil.humpToLine(field.getName());
sql.SELECT(fieldName + " as "+field.getName());
if (field.getAnnotation(ID.class) != null) {
idName = fieldName;
}
}
sql.FROM(tableName);
sql.WHERE(idName+"=#{id}");
return sql.toString();
}
}
使用:
@Repository
public interface UserMapper extends CommonBaseMapper<User> {
}
二乙帮、通用Service
public abstract class CommonBaseService<T> {
@Autowired
private CommonBaseMapper<T> commonBaseMapper;
public T selectById(String id) {
return commonBaseMapper.selectById(id);
}
}
三杜漠、通用Controller
public abstract class CommonBaseController<T> {
@Autowired
private CommonBaseMapper<T> commonBaseMapper;
@RequestMapping(value = {"/{id}"}, method = RequestMethod.GET)
public Object getUserById(@PathVariable("id") String id) {
T po = commonBaseMapper.selectById(id);
HashMap<String, Object> data = new HashMap<String, Object>(20);
ObjectData objectData = new ObjectData();
objectData.setData(po);
return objectData;
}
}