【ssm框架】Service业务逻辑层&&Mybatis映射层

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

 

  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值