Service层
通常业务处理的代码并不直接放在controller层中,那样会显得职责不单一,不方便维护。Service业务逻辑层通常用来处理各种各样的业务逻辑。我们将最基本的增删改查抽取出来,作为一个基类放在BaseService层中,这样子类就不用再去重复这些代码,如果有其他需求再自行扩展即可。
public class BaseModel implements Serializable{
private Long id;
private Timestamp cdate;
private Timestamp mdate;
private Boolean isValid;
//省略set/get方法
}
public class BaseService<T extendsBaseModel> {
@Autowired
BaseMapper<T> mapper;
protected final Logger log =LoggerFactory.getLogger(this.getClass());
public List<T> listAll() throwsException{
log.info("===查询所有实体记录===");
return mapper.selectAll();
}
public void delete(Long id) throwsException{
log.info("===删除实体记录===");
T record = queryById(id);
record.setMdate(newTimestamp(System.currentTimeMillis()));
record.setValid(false);
mapper.updateByPrimaryKey(record);
}
public T insert(T record) throws Exception{
log.info("===保存实体记录===");
record.setCdate(newTimestamp(System.currentTimeMillis()));
record.setMdate(newTimestamp(System.currentTimeMillis()));
record.setValid(true);
mapper.insert(record);
return record;
}
public T update(T record) throwsException{
log.info("===更新实体记录===");
record.setMdate(newTimestamp(System.currentTimeMillis()));
if (record.getId() == null) {
record.setCdate(newTimestamp(System.currentTimeMillis()));
mapper.insert(record);
} else {
mapper.updateByPrimaryKey(record);
}
return record;
}
@SuppressWarnings("unchecked")
public T queryById(Long id) throwsException{
log.info("===根据id查询实体记录===");
T record =mapper.selectByPrimaryKey(id);
return record;
}
}
Mapper映射层
我们知道Mybatis是通过定义接口,通过反射机制来实现它的数据库操作的。既然是数据库操作,那么最基本的增删改查自然是所有Mapper都会有的,因此也可以抽取出基类。
public interface BaseMapper<T extends BaseModel>{
List<T> selectAll();
int deleteByPrimaryKey(Long id);
T selectByPrimaryKey(Long id);
int insert(T t);
int updateByPrimaryKey(T t);
}
建好表之后,具体的model,mapper接口,mapper.xml都可以通过Mybatis的代码自动生成来构建。关于mybatis generator的配置,可参考http://www.jianshu.com/p/e09d2370b796