商铺项目(店铺注册功能模块(一))
package com.ouyan.o2o.dao; import com.ouyan.o2o.entity.Shop; public interface ShopDao { /** * 新增店铺 * @param shopCondition * @param rowIndex * @param pageSize * @return */ int insertShop(Shop shop); }
注意这个地方,因为使用了useGeneratedKeys,所以想通过IDBC获取插入数据的主键值,这时候就需要指定KeyColumn和KeyProperty,前者是数据库中的主键,后者是对应的实体类的属性:
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd"> <mapper namespace="com.ouyan.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> </mapper>
package com.ouyan.o2o.dao; import static org.junit.Assert.assertEquals; import java.util.Date; import org.junit.Test; import org.springframework.beans.factory.annotation.Autowired; import com.ouyan.o2o.BaseTest; import com.ouyan.o2o.entity.Area; import com.ouyan.o2o.entity.PersonInfo; import com.ouyan.o2o.entity.Shop; import com.ouyan.o2o.entity.ShopCategory; public class ShopDaoTest extends BaseTest{ @Autowired private ShopDao shopDao; @Test public void testInsertShop(){ Shop shop = new Shop(); PersonInfo owner = new PersonInfo(); Area area = new Area(); ShopCategory shopCategory = new ShopCategory(); owner.setUserId(1L); area.setAreaId(2L); shopCategory.setShopCategoryId(33L); 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); } }
注意要在数据库中添加数据:
然后测试,查看数据库,成功插入数据。
接下来更新店铺:
package com.ouyan.o2o.dao; import com.ouyan.o2o.entity.Shop; public interface ShopDao { /** * 新增店铺 */ int insertShop(Shop shop); /** * 更新店铺信息 */ int updateShop(Shop shop); }
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd"> <mapper namespace="com.ouyan.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> <update id="updateShop" parameterType="com.ouyan.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="enableStatus != null">enable_status=#{enableStatus},</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>
package com.ouyan.o2o.dao; import static org.junit.Assert.assertEquals; import java.util.Date; import org.junit.Test; import org.springframework.beans.factory.annotation.Autowired; import com.ouyan.o2o.BaseTest; import com.ouyan.o2o.entity.Area; import com.ouyan.o2o.entity.PersonInfo; import com.ouyan.o2o.entity.Shop; import com.ouyan.o2o.entity.ShopCategory; public class ShopDaoTest extends BaseTest{ @Autowired private ShopDao shopDao; @Test public void testInsertShop(){ Shop shop = new Shop(); PersonInfo owner = new PersonInfo(); Area area = new Area(); ShopCategory shopCategory = new ShopCategory(); owner.setUserId(1L); area.setAreaId(2L); shopCategory.setShopCategoryId(33L); 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(30L); shop.setShopDesc("测试描述"); shop.setShopAddr("测试地址"); shop.setLastEditTime(new Date()); int effectedNum = shopDao.updateShop(shop); assertEquals(1,effectedNum); } }
测试请注意,如果想要只执行testUpdateShop方法,要么双击该方法名,然后运行,要么在testInsertShop上加@Ignore。
接下来看Thumbnailator图片处理和封装Util:
然后添加到pom.xml中。
这里我已经把水印图片放入src/main/resources下,运行main函数即可在d盘里找到合成的图片(这个地方有点坑,两个反斜杠)。
package com.ouyan.o2o.util; import java.io.File; import java.io.IOException; import javax.imageio.ImageIO; import net.coobird.thumbnailator.Thumbnails; import net.coobird.thumbnailator.geometry.Positions; public class imageUtil { public static void main(String[] args) throws IOException { String basePath = Thread.currentThread().getContextClassLoader().getResource("").getPath(); Thumbnails.of(new File("d:\\timg.jpg")).size(2000, 2000) .watermark(Positions.BOTTOM_RIGHT,ImageIO.read(new File(basePath+"/watermark.jpg")),0.25f) .outputQuality(0.8f).toFile("d:\\timgnew.jpg"); } }
package com.ouyan.o2o.util; import java.io.File; import java.io.IOException; import java.text.SimpleDateFormat; import java.util.Date; import java.util.Random; import javax.imageio.ImageIO; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.web.multipart.commons.CommonsMultipartFile; import net.coobird.thumbnailator.Thumbnails; import net.coobird.thumbnailator.geometry.Positions; 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(); private static Logger logger = LoggerFactory.getLogger(imageUtil.class); /** * 将CommonsMultipartFile转换成file * @param cFile * @return */ public static File transferCommonsMultipartFileToFile(CommonsMultipartFile cFile){ File newFile = new File(cFile.getOriginalFilename()); try { cFile.transferTo(newFile); } catch (IllegalStateException e) { logger.error(e.toString()); e.printStackTrace(); } catch (IOException e) { logger.error(e.toString()); e.printStackTrace(); } return newFile; } /** * 处理缩略图并返回新生成图片的相对值路径 * @param thumbnail * @param targetAddr * @return */ public static String generateThumbnail(File thumbnail, String targetAddr) { String realFileName = getRandomFileName(); String extension = getFileExtesion(thumbnail); makeDirPath(targetAddr); String relativeAddr = targetAddr + realFileName + extension; logger.error("current relativeAddr is:"+ relativeAddr); File dest = new File(PathUtil.getImgBasePath() + relativeAddr); logger.debug("current complete addr is :" + PathUtil.getImgBasePath() + relativeAddr); try { Thumbnails.of(thumbnail).size(200, 200) .watermark(Positions.BOTTOM_RIGHT, ImageIO.read(new File(basePath + "/watermark.jpg")), 0.25f) .outputQuality(0.8).toFile(dest); } catch (IOException e) { logger.error(e.toString()); e.printStackTrace(); } return relativeAddr; } /** * 创建目标路径涉及的目录 * @param targetAddr */ private static void makeDirPath(String targetAddr) { String realFileParentPath = PathUtil.getImgBasePath()+targetAddr; File dirPath = new File(realFileParentPath); if(!dirPath.exists()){ dirPath.mkdirs(); } } /** * 获取输入文件的扩展名 * @param thumbnail * @return */ private static String getFileExtesion(File cFile) { String originalFilename = cFile.getName(); return originalFilename.substring(originalFilename.lastIndexOf(".")); } /** * 生成随机文件名,当前年月是小时分钟秒钟+五位随机数 * * @return */ private static String getRandomFileName() { // 获取随机的五位数 int rannum = r.nextInt(89999) + 10000; String nowTimeStr = sDateFormat.format(new Date()); return nowTimeStr+rannum; } public static void main(String[] args) throws IOException { Thumbnails.of(new File("d:\\timg.jpg")).size(2000, 2000) .watermark(Positions.BOTTOM_RIGHT, ImageIO.read(new File(basePath + "/watermark.jpg")), 0.25f) .outputQuality(0.8f).toFile("d:\\timgnew.jpg"); } }
package com.ouyan.o2o.util; public class PathUtil { private static String separator = System.getProperty("file.separator"); public static String getImgBasePath(){ String os = System.getProperty("os.name"); String basePath=""; if(os.toLowerCase().startsWith("win")){ basePath = "D:/projectdev/image/"; }else{ basePath = "/home/ouyan/image/"; } basePath = basePath.replace("/", separator); return basePath; } public static String getShopImagePath(long shopId){ String imagePath = "upload/item/shop"+shopId+"/"; return imagePath.replace("/", separator); } }