在项目中,我们开发一个功能的时候顺序是写pojo-->写Mapper-->写service-->写controller这样
当在一个项目中需要写许多service而且这些service中的许多方法都是差不多的时候,我们就有必要做一个通用的service。那么通用service中一般有哪些方法?
1、 queryById -- 根据id进行查询
2、 queryAll -- 查询所有数据
3、 queryByWhere--根据条件做查询
4、 queryOne--根据条件查找一条数据
5、 queryListByWhere --根据条件查询数据的集合
6、 queryPageListByWhere-- 分页查询
7、 save --增加数据
8、 update --更新数据
9、 deleteById --根据id删除数据
10、deleteByIds--批量删除数据
该通用方法一般为抽象类,具体代码如下:
package com.taotao.manager.service;
import java.util.Date;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.github.abel533.entity.Example;
import com.github.abel533.mapper.Mapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.taotao.manager.pojo.BasePojo;
@Service
public abstract class BaseService<T extends BasePojo> {
/** 由子类实现该方法,返回具体的Mapper的实现类 **/
// public abstract Mapper<T> getMapper();
/**
* 使用Spring4.x的新特性,根据泛型类型注入对象
*/
@Autowired
private Mapper<T> mapper;
// 为了让子类能够拿到自己的Mapper,然后调用里面的方法。
public Mapper<T> getMapper() {
return mapper;
}
/**
* 根据id查询
* @param id
* @return
*/
public T queryById(Long id){
return this.mapper.selectByPrimaryKey(id);
}
// 查询所有数据
public List<T> queryAll(){
return this.mapper.select(null);
}
// 根据条件查询一条数据
public T queryOne(T t){
return this.mapper.selectOne(t);
}
// 根据条件查询数据集合
public List<T> queryByWhere(T t){
return this.mapper.select(t);
}
// 分页查询
public PageInfo<T> queryPageList(T t,Integer page,Integer rows){
PageHelper.startPage(page, rows);
List<T> list = this.queryByWhere(t);
return new PageInfo<T>(list);
}
// 自定义查询条件,分页查询
public PageInfo<T> queryItemByExample(Example example,Integer page,Integer rows){
PageHelper.startPage(page, rows,true);//设置分页参数
// 查询数据
List<T> list = this.mapper.selectByExample(example);
return new PageInfo<T>(list);
}
// 新增数据
public Integer save(T t){
t.setCreated(new Date());
t.setUpdated(t.getCreated());
return this.mapper.insert(t);
}
// 新增数据,使用不为null的字段
public Integer saveSelective(T t){
t.setCreated(new Date());
t.setUpdated(t.getCreated());
return this.mapper.insertSelective(t);
}
// 更新数据
public Integer update(T t){
t.setUpdated(new Date());
return this.mapper.updateByPrimaryKey(t);
}
// 更新数据,使用不为null的字段
public Integer updateSelective(T t){
t.setUpdated(new Date());
return this.mapper.updateByPrimaryKeySelective(t);
}
// 根据id删除数据
public Integer deleteById(Long id){
return this.mapper.deleteByPrimaryKey(id);
}
// 批量删除数据
public Integer deleteByIds(String property,List<Object> ids,Class<T> class1){
Example example=new Example(class1);
example.createCriteria().andIn(property, ids);
return this.mapper.deleteByExample(example);
}
}
上面代码中出现基础BasePojo是因为我的所有pojo文件继承了basepojo,在该文件中继承了所有表的共同特性:创建日期和修改日期。在BaseService中save()方法中,设置了这两个字段的值。所以要继承一下。