Design and Implementation of an Online Course Purchase System(10)

Complete the function of searching course information by course id

Posted by Chen Xingxu on June 3, 2020

易课寄在线购课系统开发笔记(十)–完成根据课程id查询课程信息的功能

需求

根据课程 id 查询课程信息,返回 JSON 数据。

Dao 层

由于是单表查询,可以使用逆向工程生成的代码。

Service 层

参数:课程 id

返回值:EcoursesItem

业务逻辑:根据课程 id 查询课程信息。

package cn.ecourses.service;

public interface ItemService {
	EcoursesItem getItemById(long ItemId);
}
package cn.ecourses.service.impl;
//管理Service
@Service
public class ItemServiceImpl implements ItemService {

	@Autowired
	private EcoursesItemMapper itemMapper;
	
	@Value("${REDIS_ITEM_PRE}")
	private String REDIS_ITEM_PRE;
	@Value("${ITEM_CACHE_EXPIRE}")
	private Integer ITEM_CACHE_EXPIRE;
	
	@Override
	public EcoursesItem getItemById(long itemId) {
		//查询缓存
		try {
			String json = jedisClient.get(REDIS_ITEM_PRE + ":" + itemId + ":BASE");
			if(StringUtils.isNotBlank(json)) {
				EcoursesItem ecoursesItem = JsonUtils.jsonToPojo(json, EcoursesItem.class);
				return ecoursesItem;
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		//缓存中没有,查询数据库
		EcoursesItemExample example = new EcoursesItemExample();
		Criteria criteria = example.createCriteria();
		//设置查询条件
		criteria.andIdEqualTo(itemId);
		//执行查询
		List<EcoursesItem> list = itemMapper.selectByExample(example);
		if (list != null && list.size() > 0) {
			//把结果添加到缓存
			try {
				jedisClient.set(REDIS_ITEM_PRE + ":" + itemId + ":BASE", JsonUtils.objectToJson(list.get(0)));
				//设置过期时间
				jedisClient.expire(REDIS_ITEM_PRE + ":" + itemId + ":BASE", ITEM_CACHE_EXPIRE);
			} catch (Exception e) {
				e.printStackTrace();
			}
			return list.get(0);
		}
		return null;
	}
}

Controller

package cn.ecourses.controller;

@Controller
public class ItemController {
    
	@Autowired
	private ItemService itemService;
	
	@RequestMapping("/item/{itemId}")
	@ResponseBody
	public EcoursesItem getItemById(@PathVariable Long itemId) {
		EcoursesItem ecoursesItem = itemService.getItemById(itemId);
		return ecoursesItem;
	}
}