SpringMVC构建REST接口:第六篇 服务层实现

       服务层,是控制层和数据库持久层之间的纽带,对数据进行具体的处理。在这一层,最基本的要求就是对数据库的CURD处理以及事物处理。

一、服务层接口编写

       在com.jiahe.rest.demo2.service中增加接口DishesCookService.java,然后把com.jiahe.rest.demo2.dao.DishesCookMapper.java中定义的接口拷贝过来,形成以下:

public interface DishesCookService {


public int insert(DishesCook dishesCook) throws Exception;


public int update(DishesCook dishesCook) throws Exception;


public int deleteByCondition(DishesCook dishesCook) throws Exception;


public int deleteByID(DishesCook dishesCook) throws Exception;


public List<DishesCook> findByCondition(DishesCook dishesCook) throws Exception;


public DishesCook findByID(DishesCook dishesCook) throws Exception;


public Long findCountByCondition(DishesCook dishesCook) throws Exception;
}

       注意:每个方法多了throws Exception.

二、服务层实现编写

      1、在com.jiahe.rest.demo2.service.impl中增加类DishesCookServiceImpl.java

      2、注解为dishesCookService服务,在类上面添加@Service("dishesCookService")

      3、使DishesCookServiceImpl继承DishesCookService,在类名后添加 implements DishesCookService

      4、点击类 前面的灯泡符号,添加没有实现的方法,如图6-1


图6-1

5、添加dao变量

@Resource  
private DishesCookMapper mapper;

      6、利用Eclips对mapper添加get/set

      7、实现insert方法

            A、在insert方法上添加注解@Transactional,实现事物管理

            B、在insert方法中,替换return 0;为return mapper.insert(dishesCook);

           结果如下:

@Override@Transactional
public int insert(DishesCook dishesCook) throws Exception {
return mapper.insert(dishesCook);
}

      8、实现update方法,代码如下

        @Override@Transactional
public int update(DishesCook dishesCook) throws Exception {
return mapper.update(dishesCook);
}

       9、实现...

       。。。

      整个服务层实现代码如下:

@Service("dishesCookService")
public class DishesCookServiceImpl implements DishesCookService{


@Resource  
    private DishesCookMapper mapper;


@Override@Transactional
public int insert(DishesCook dishesCook) throws Exception {
return mapper.insert(dishesCook);
}


@Override@Transactional
public int update(DishesCook dishesCook) throws Exception {
return mapper.update(dishesCook);
}


@Override@Transactional
public int deleteByCondition(DishesCook dishesCook) throws Exception {
return mapper.deleteByCondition(dishesCook);
}


@Override@Transactional
public int deleteByID(DishesCook dishesCook) throws Exception {
return mapper.deleteByID(dishesCook);
}


@Override
public List<DishesCook> findByCondition(DishesCook dishesCook)
throws Exception {
return mapper.findByCondition(dishesCook);
}


@Override
public DishesCook findByID(DishesCook dishesCook) throws Exception {
return mapper.findByID(dishesCook);
}


@Override
public Long findCountByCondition(DishesCook dishesCook) throws Exception {
return mapper.findCountByCondition(dishesCook);
}


public DishesCookMapper getMapper() {
return mapper;
}


public void setMapper(DishesCookMapper mapper) {
this.mapper = mapper;
}
}

             服务层的CURD,其实就是一个皮,一句话直接调用dao。





展开阅读全文

没有更多推荐了,返回首页