校园商店项目ssm到springboot笔记5 --新增、更新店铺、 Thumbnailator图片处理、封装Util、Dto之ShopExecution的实现

新增、更新店铺

dao接口:

public interface ShopDao {
	
	//新增商店
	int insertShop(Shop shop);
	//更新
	int updateShop(Shop shop);
}

mapper:

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.cm.o2o.dao.ShopDao">

	<insert id="insertShop" useGeneratedKeys="true"
		keyColumn="shop_id" keyProperty="shopId">
		insert into
		tb_shop(owner_id,area_id,shop_category_id,shop_name,shop_desc,shop_addr,
		phone,shop_img,priority,create_time,last_edit_time,enable_status,advice)
		values
		(#{owner.userId},#{area.areaId},#{shopCategory.shopCategoryId},#{shopName},#{shopDesc},#{shopAddr},
		#{phone},#{shopImg},#{priority},#{createTime},#{lastEditTime},#{enableStatus},#{advice})
	</insert>
	
	<!-- show_id、owner_id、create_time不做更新 -->
	<update id="updateShop" parameterType="com.cm.o2o.entity.Shop">
		update tb_shop 
		<set>
			<if test = "shopName != null">shop_name=#{shopName},</if>
			<if test = "shopDesc != null">shop_desc=#{shopDesc},</if>
			<if test = "shopAddr != null">shop_addr=#{shopAddr},</if>
			<if test = "phone != null">phone=#{phone},</if>
			<if test = "shopImg != null">shop_img=#{shopImg},</if>
			<if test = "priority != null">priority=#{priority},</if>
			<if test = "lastEditTime != null">last_edit_time=#{lastEditTime},</if>
			<if test = "advice != null">advice=#{advice},</if>
			
			<if test = "area != null">area_id=#{area.areaId},</if>
			<if test = "shopCategory != null">shop_category_id=#{shopCategory.shopCategoryId}</if>
		</set> 
		where shop_id = #{shopId}
	</update>
</mapper>


数据库插入数据

insert into tb_person_info (name,profile_img,email,gender,enable_status,user_type,create_time,last_edit_time) 
values ('测试','test','test','1',1,2,null,null);

insert into tb_shop_category (shop_category_id,shop_category_name,shop_category_desc,shop_category_img,priority,create_time,last_edit_time,parent_id) 
values (1,'珍珠奶茶','珍珠奶茶','test',1,null,null,null);

测试:

package com.cm.o2o.dao;

import static org.junit.Assert.assertEquals;

import java.util.Date;

import org.junit.Ignore;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;

import com.cm.o2o.BaseTest;
import com.cm.o2o.entity.Area;
import com.cm.o2o.entity.PersonInfo;
import com.cm.o2o.entity.Shop;
import com.cm.o2o.entity.ShopCategory;

public class ShopDaoTest extends BaseTest{
	
	@Autowired
	private ShopDao shopDao;
	
	@Test
	@Ignore
	public void testInsertShop() {
		Shop shop = new Shop();
		PersonInfo owner = new PersonInfo();
		Area area = new Area();
		ShopCategory shopCategory = new ShopCategory();
		
		owner.setUserId(1L);
		area.setAreaId(2);
		shopCategory.setShopCategoryId(1L);
		
		shop.setOwner(owner);
		shop.setArea(area);
		shop.setShopCategory(shopCategory);
		shop.setShopName("测试店铺");
		shop.setShopDesc("test");
		shop.setShopAddr("test");
		shop.setPhone("test");
		shop.setShopImg("test");
		shop.setCreateTime(new Date());
		shop.setEnableStatus(1);
		shop.setAdvice("审核中");
		
		int effectedNum = shopDao.insertShop(shop);
		assertEquals(1, effectedNum);
	}
	
	@Test
	public void testUpdateShop() {
		Shop shop = new Shop();
		
		shop.setShopId(1L);
		shop.setShopDesc("test描述");
		shop.setShopAddr("test地址");
		shop.setLastEditTime(new Date());
		int effectedNum = shopDao.updateShop(shop);
		assertEquals(1, effectedNum);
	}
}

Thumbnailator图片处理

Thumbnailator依赖导入:

	<!-- 图片处理 -->
	<!-- https://mvnrepository.com/artifact/net.coobird/thumbnailator -->
	<dependency>
	    <groupId>net.coobird</groupId>
	    <artifactId>thumbnailator</artifactId>
	    <version>0.4.8</version>
	</dependency>

水印图片导入:
/o2o/src/main/resources/watermark.png
加水印图片地址:F:/schoolPicture/xiaohuangren.jpg

简单图片添加水印功能实现:

	public static void main(String[] args) throws Exception {
		
		//处理图片文件的路径   输出图片大小  图片添加水印
		Thumbnails.of(new File("F:/schoolPicture/xiaohuangren.jpg"))
		.size(200, 200)           //水印位置     水印图片路径  
		.watermark(Positions.BOTTOM_RIGHT,                              //透明度
				ImageIO.read(new File(basePath+"watermark.png")),0.25f)
		.outputQuality(0.8f)   //压缩比   输出位置
		.toFile("F:/schoolPicture/xiaohuangrennew.jpg");
	}

成功:
在这里插入图片描述

封装Util

编写工具类:PathUtil

/*
 * 提供两类路径
 * --1.根据执行环境不同(操作系统),提供不同的根路径(项目图片存放的路径)
 * --2.相对子路径
 */
public class PathUtil {

		
	//获取文件分隔符
	private static String seperator = System.getProperty("file.seperator");
	public static String getImgBasePath() {
		String os = System.getProperty("os.name");
		String basePath = "";
		//windows  
		//如果设置根目录在classPath下面,一旦部署项目,新生成的图片会被删除,除非一开始就保存在这下面
		//所以要放在工程路径以外、或放在另一个服务器url
		if(os.toLowerCase().startsWith("win")) {
			basePath = "G:/java项目/我的项目/校园图片/";
		}else {
			basePath = "/home/xiangze/image/";
		}
		basePath = basePath.replace("/", seperator);
		return basePath;
	}
	
	//将图片分别存储在各自店铺的路径下
	public static String getShopImagePath(long shopId) {
		String imagePath = "/upload/item/shop/" + shopId + "/";
		return imagePath.replace("/", seperator);
	}

}

编写工具类ImageUtil:

/*
 * 改变图片大小,添加水印,将图片压缩,输出在同级目录底下
 */
public class ImageUtil {
	
	private static String basePath = Thread.currentThread().getContextClassLoader().getResource("").getPath();
	//时间格式  随机数对象
	private static final SimpleDateFormat sDateFormat = new SimpleDateFormat("yyyyMMddHHmmss");
	private static final Random r = new Random();
	
	//处理缩列图(商品小图,店铺门面照)                    文件处理对象                       文件存储路径
	public static void generateThumbnail(CommonsMultipartFile thumbnail,String targetAddr){
		//统一命名
		String realFileName = getRandomFileName();
		//获取扩展名
		String extension = getFileExtension(thumbnail);
		makeDirPath(targetAddr);
		//生成唯一相对路径
		String relativeAddr = targetAddr + realFileName  + extension;
		//根路径+先对路径==文件路径
		File dest = new File(PathUtil.getImgBasePath()+relativeAddr);
		try {
			Thumbnails.of(thumbnail.getInputStream()).size(200, 200)
			.watermark(Positions.BOTTOM_RIGHT, ImageIO.read(new File(basePath+"watermark.png")),0.25f)
			.outputQuality(0.8f)   //压缩比   输出位置
			.toFile(dest);
		}catch(IOException e) {
			e.printStackTrace();
		}
	}
	
	//创建目标路径所涉及到目录   /home/work/xiangze/xxx.jpg
	//那么home   work   xiangze   三个文件夹都自动创建
	private static void makeDirPath(String targetAddr) {       
		//全路径
		String realFileParentPath = PathUtil.getImgBasePath()+targetAddr;
		File dirPath = new File(realFileParentPath);
		if(!dirPath.exists()) {
			dirPath.mkdirs();
		}
	}
	
	//获取输入文件流的扩张名   .jpg
	private static String getFileExtension(CommonsMultipartFile cFile) {
		String originalFileName = cFile.getOriginalFilename();
		return originalFileName.substring(originalFileName.lastIndexOf("."));
	}
	
	/*
	 * 生成随机文件名   当前时间+5位随机数
	 */
	private static String getRandomFileName() {
		//获取随机5位数  10000-89999
		int rannum = r.nextInt(89999) + 10000;
		String nowTimeStr = sDateFormat.format(new Date());
		return nowTimeStr+rannum;
	}
	
	public static void main(String[] args) throws Exception {
		
		//处理图片文件的路径   输出图片大小  图片添加水印
		Thumbnails.of(new File("F:/schoolPicture/xiaohuangren.jpg"))
		.size(200, 200)           //水印位置     水印图片路径  
		.watermark(Positions.BOTTOM_RIGHT,                              //透明度
				ImageIO.read(new File(basePath+"watermark.png")),0.25f)
		.outputQuality(0.8f)   //压缩比   输出位置
		.toFile("F:/schoolPicture/xiaohuangrennew.jpg");
	}

}

Dto之ShopExecution的实现

(添加店铺的返回类型存储到Dto,不用Shop,因为增加Shop是否成功有状态,这些状态需要记录,需要返回给controller处理)

/*
 * 存取店铺信息
 * 存取状态
 */
public class ShopExecution {
	
	//结果状态  以文字形式解释state作用
	private int state;
	//状态标识
	private String stateInfo;
	//店铺数量
	private int count;
	//操作的shop(crud时使用)
	private Shop shop;
	//shop列表(查询时用)
	private List<Shop> shopList;
	
	public ShopExecution() {}
	
	//店铺操作失败时使用的构造器                                   枚举类型
	public ShopExecution(ShopStateEnum stateEnum) {
		//状态值
		this.state = stateEnum.getState();
		this.stateInfo = stateEnum.getStateInfo();
	}
	
	//店铺操作成功的构造器
	public ShopExecution(ShopStateEnum stateEnum,Shop shop) {
		//状态值
		this.state = stateEnum.getState();
		this.stateInfo = stateEnum.getStateInfo();
		this.shop = shop;
	}
	
	//店铺操作返回列表构造器
	public ShopExecution(ShopStateEnum stateEnum,List<Shop> shopList) {
		//状态值
		this.state = stateEnum.getState();
		this.stateInfo = stateEnum.getStateInfo();
		this.shopList = shopList;
	}

	public int getState() {
		return state;
	}

	public void setState(int state) {
		this.state = state;
	}

	public String getStateInfo() {
		return stateInfo;
	}

	public void setStateInfo(String stateInfo) {
		this.stateInfo = stateInfo;
	}

	public int getCount() {
		return count;
	}

	public void setCount(int count) {
		this.count = count;
	}

	public Shop getShop() {
		return shop;
	}

	public void setShop(Shop shop) {
		this.shop = shop;
	}

	public List<Shop> getShopList() {
		return shopList;
	}

	public void setShopList(List<Shop> shopList) {
		this.shopList = shopList;
	}
	
	
}

枚举函数ShopStateEnum:

public enum ShopStateEnum {
	CHECK(0, "审核中"), OFFLINE(-1, "非法店铺"), SUCCESS(1, "操作成功"), PASS(2, "通过认证"), INNER_ERROR(-1001, "内部系统错误"),
	NULL_SHOPID(-1002, "SHopId为空");

	private int state;
	private String stateInfo;

	private ShopStateEnum(int state, String stateInfo) {
		this.state = state;
		this.stateInfo = stateInfo;
	}

	// 依据传入的state返回相应的enum值
	public static ShopStateEnum stateOf(int state) {
		for (ShopStateEnum stateEnum : values()) {
			if (stateEnum.getState() == state) {
				return stateEnum;
			}
		}
		return null;
	}

	public int getState() {
		return state;
	}

	public String getStateInfo() {
		return stateInfo;
	}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值