1. Dao层新增店铺
具体步骤:
1.1 Dao层 新增ShopDao接口
package com.gs.o2o.dao; import com.gs.o2o.entity.Shop; public interface ShopDao { //新增店铺 int insertShop(Shop shop); }
1.2 ShopDao.xml中 对 ShopDao接口 中的 insertShop() 方法 进行实现。
<?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"> <!-- namespace: 指定mapper去扫描哪个类。 useGeneratedKeys="true" :当数据添加成功,jdbc自动获取主键的值传入到实体类中。 keyColumn:数据库表的主键 ,绑定 keyProperty:实体类中的主键字段。 --> <mapper namespace="com.gs.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>
1.3 由于Shop实体类中,有3个属性 和 对应的实体类 及 数据库表 相关联,我们在设计表关系的时候,设置了外键关系,因此务必确保 设置的这几个id在对应的表中存在。测试的时候先往 对应的数据库添加一些 数据。
/** * 店铺所属店主 */ private PersonInfo owner; /** * 店铺所在区域 */ private Area area; /** * 店铺类别 */ private ShopCategory shopCategory;
tb_area 表:
tb_person_info 表
tb_shop_category表
1.4 单元测试 ShopDaoTest
package com.gs.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.gs.o2o.BaseTest; import com.gs.o2o.entity.Area; import com.gs.o2o.entity.PersonInfo; import com.gs.o2o.entity.Shop; import com.gs.o2o.entity.ShopCategory; public class ShopDaoTest extends BaseTest { @Autowired private ShopDao shopDao; @Test public void testInsertShop() { Shop shop = new Shop(); Area area = new Area(); PersonInfo owner = new PersonInfo(); ShopCategory shopCategory = new ShopCategory(); area.setAreaId(1); owner.setUserId(1L); shopCategory.setShopCategoryId(1L); shop.setArea(area); shop.setOwner(owner); shop.setShopCategory(shopCategory); shop.setShopName("测试的店铺"); shop.setShopDesc("test"); shop.setShopAddr("上海"); shop.setPhone("123456"); shop.setShopImg("/xxx/xxx"); shop.setPriority(99); shop.setCreateTime(new Date()); shop.setLastEditTime(new Date()); shop.setEnableStatus(0); shop.setAdvice("审核中"); int effectNum = shopDao.insertShop(shop);//若添加成功,产生受影响的行数 assertEquals(effectNum,1); } }
运行结果:tb_shop表新增了一条数据。