主要内容:
RequestMapping特性
Controller方法返回值
参数绑定
一、需求分析
这里我们还是使用上次整合的工程。
操作流程:
(1)进入商品查询列表页面
(2)点击修改,进入商品修改页面,页面中显示了要修改的商品信息(从数据库中查询),要修改的商品从数据查询,根据商品id(主键)查询商品信息
(3)在商品修改页面,修改商品信息,修改后,点击提交。
二、开发 mapper
根据上面的需求我们可以知道,mapper中此处需要完成两个功能:
根据id查询商品信息,返回给页面显示
更新items表的数据,更新数据库
但是这里的两个功能需求是相对简单的,在逆向工程中已经帮我们生成好了相关代码,我们只需要直接使用即可,不需要再次开发。
三、开发 service
根据持久层mapper的相关业务需求,这里我们就可以知道业务层的功能需求
根据id查询商品信息
修改商品信息
3.1 接口
ItemsServiceI.java
//根据id查询商品信息
public ItemsCustom findItemsById(Integer id) throws Exception;
//修改商品信息,这里id本来已经在itemsCustom存在,但是为了更好的开发,还是将id提取出来
//作为一个参数,表明此id必须传入
public void updateItems(Integer id, ItemsCustom itemsCustom) throws Exception;
3.2 实现
ItemsServiceImpl.java
package cn.itcast.ssm.service.impl;
import java.util.List;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import cn.itcast.ssm.mapper.ItemsMapper;
import cn.itcast.ssm.mapper.ItemsMapperCustom;
import cn.itcast.ssm.pojo.Items;
import cn.itcast.ssm.pojo.ItemsCustom;
import cn.itcast.ssm.pojo.ItemsQueryVo;
import cn.itcast.ssm.service.ItemsServiceI;
public class ItemsServiceImpl implements ItemsServiceI{
@Autowired
private ItemsMapperCustom itemsMapperCustom;
@Autowired
private ItemsMapper itemsMapper;
@Override
public List findItemsList(ItemsQueryVo itemsQueryVo)
throws Exception {
//通过ItemsMapperCustom查询数据库,通过spring注入
return itemsMapperCustom.findItemsList(itemsQueryVo);
}
@Override
public ItemsCustom findItemsById(Integer id) throws Exception {
Items items = itemsMapper.selectByPrimaryKey(id);
//查询出来的数据可能需要进行一些业务处理,最后要返回ItemsCustom
ItemsCustom itemsCustom = new ItemsCustom();
//将Items内容拷贝到ItemsCustom
BeanUtils.copyProperties(items, itemsCustom);
return itemsCustom;
}
@Override
public void updateItems(Integer id, ItemsCustom itemsCustom) throws Exception {
//添加一些业务校验,通常在service接口对关键的参数进行校验
//校验id是否为空等等,如果为空则抛出异常
//更新商品信息,使用updateByPrimaryKeyWithBLOBs可以根据id更新表中所有字段,
//包括大文本字段,这里因为表中有个字段属性为text,所以使用此方法
//要求必须传入id,即使类中已经存在
itemsCustom.setId(id);
itemsMapper.updateByPrimaryKeyWithBLOBs(itemsCustom);
}
}