学习目标
DAO层的实现 插入
在ShopDao接口中加入方法
/** * 新增店铺 * @param shop * @return */ int insertShop(Shop shop);
在mapper中 创建ShopDao.xml
<?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.ryanxu.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>
其中,id 就是 Dao中的方法名,
useGeneratedKeys 为true时,通过getGeneratedKeys获取数据库的自增主键,即是当数据插入成功时获取主键值,在保存图片时,创建的文件夹名就是主键值 唯一,
keyColumn 就是数据库中的列名
keyProperty 就是Shop类的名字 和 列名对应
因为传入的是个对象,所以用#{owner.userId} 花括号里面就是实体类对应的成员变量的名字
Area 和 ShopCategory 也是如此
DAO层的实现 更新
/** * 更新店铺信息 * @param shop * @return */ int updateShop(Shop shop);
ShopDao.xml中加入
动态sql语句的使用 (两列 a 和 b ,只修改a 就用这个)
<update id="updateShop" parameterType="com.ryanxu.o2o.entity.Shop"> update tb_shop <set> <!-- <if test="xxx!=null">xxx_xxx=#{xxx}</if> --> <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>
parameterType 需要传入的类型
如果传入的shopName 不为空 就将数据库中的shop_name 改成传入的shopName
同时需要注意ShopCategory 和 Area
在mybatis中对sql语句使用条件判断,注意在最后一个if判断语句中,最后是没有逗号的