SpringMVC,MyBatis商品的增删改查

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了SpringMVC,MyBatis商品的增删改查相关的知识,希望对你有一定的参考价值。

一、需求

商品的增删改查

二、工程结构

技术分享

三、代码

1.Mapper层

(1)

ItemsMapperCustom.java

 1 package com.tony.ssm.mapper;
 2 
 3 import java.util.List;
 4 
 5 import com.tony.ssm.po.ItemsCustom;
 6 import com.tony.ssm.po.ItemsQueryVo;
 7 
 8 public interface ItemsMapperCustom {
 9     //商品查询列表
10     public List<ItemsCustom> findItemsList(ItemsQueryVo itemsQueryVo)throws Exception;
11 }

ItemsMapperCustom.xml

 1 <?xml version="1.0" encoding="UTF-8" ?>
 2 <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd" >
 3 <mapper namespace="com.tony.ssm.mapper.ItemsMapperCustom" >
 4 
 5    <!-- 定义商品查询的sql片段,就是商品查询条件 -->
 6    <sql id="query_items_where">
 7        <!-- 使用动态sql,通过if判断,满足条件进行sql拼接 -->
 8        <!-- 商品查询条件通过ItemsQueryVo包装对象 中itemsCustom属性传递 -->
 9            <if test="itemsCustom!=null">
10                <if test="itemsCustom.name!=null and itemsCustom.name!=‘‘">
11                    items.name LIKE ‘%${itemsCustom.name}%‘
12                </if>
13            </if>
14     
15    </sql>
16       
17       <!-- 商品列表查询 -->
18       <!-- parameterType传入包装对象(包装了查询条件)
19           resultType建议使用扩展对象
20        -->
21       <select id="findItemsList" parameterType="com.tony.ssm.po.ItemsQueryVo"
22            resultType="com.tony.ssm.po.ItemsCustom">
23           SELECT items.* FROM items  
24           <where>
25               <include refid="query_items_where"></include>
26           </where>
27       </select>
28       
29 </mapper>

(2)

ItemsMapper.java

 1 package com.tony.ssm.mapper;
 2 
 3 import com.tony.ssm.po.Items;
 4 import com.tony.ssm.po.ItemsExample;
 5 import java.util.List;
 6 import org.apache.ibatis.annotations.Param;
 7 
 8 public interface ItemsMapper {
 9     int countByExample(ItemsExample example);
10 
11     int deleteByExample(ItemsExample example);
12 
13     int deleteByPrimaryKey(Integer id);
14 
15     int insert(Items record);
16 
17     int insertSelective(Items record);
18 
19     List<Items> selectByExampleWithBLOBs(ItemsExample example);
20 
21     List<Items> selectByExample(ItemsExample example);
22 
23     Items selectByPrimaryKey(Integer id);
24 
25     int updateByExampleSelective(@Param("record") Items record, @Param("example") ItemsExample example);
26 
27     int updateByExampleWithBLOBs(@Param("record") Items record, @Param("example") ItemsExample example);
28 
29     int updateByExample(@Param("record") Items record, @Param("example") ItemsExample example);
30 
31     int updateByPrimaryKeySelective(Items record);
32 
33     int updateByPrimaryKeyWithBLOBs(Items record);
34 
35     int updateByPrimaryKey(Items record);
36 }

ItemsMapper.xml

  1 <?xml version="1.0" encoding="UTF-8" ?>
  2 <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd" >
  3 <mapper namespace="com.tony.ssm.mapper.ItemsMapper" >
  4   <resultMap id="BaseResultMap" type="com.tony.ssm.po.Items" >
  5     <id column="id" property="id" jdbcType="INTEGER" />
  6     <result column="name" property="name" jdbcType="VARCHAR" />
  7     <result column="price" property="price" jdbcType="REAL" />
  8     <result column="pic" property="pic" jdbcType="VARCHAR" />
  9     <result column="createtime" property="createtime" jdbcType="TIMESTAMP" />
 10   </resultMap>
 11   <resultMap id="ResultMapWithBLOBs" type="com.tony.ssm.po.Items" extends="BaseResultMap" >
 12     <result column="detail" property="detail" jdbcType="LONGVARCHAR" />
 13   </resultMap>
 14   <sql id="Example_Where_Clause" >
 15     <where >
 16       <foreach collection="oredCriteria" item="criteria" separator="or" >
 17         <if test="criteria.valid" >
 18           <trim prefix="(" suffix=")" prefixOverrides="and" >
 19             <foreach collection="criteria.criteria" item="criterion" >
 20               <choose >
 21                 <when test="criterion.noValue" >
 22                   and ${criterion.condition}
 23                 </when>
 24                 <when test="criterion.singleValue" >
 25                   and ${criterion.condition} #{criterion.value}
 26                 </when>
 27                 <when test="criterion.betweenValue" >
 28                   and ${criterion.condition} #{criterion.value} and #{criterion.secondValue}
 29                 </when>
 30                 <when test="criterion.listValue" >
 31                   and ${criterion.condition}
 32                   <foreach collection="criterion.value" item="listItem" open="(" close=")" separator="," >
 33                     #{listItem}
 34                   </foreach>
 35                 </when>
 36               </choose>
 37             </foreach>
 38           </trim>
 39         </if>
 40       </foreach>
 41     </where>
 42   </sql>
 43   <sql id="Update_By_Example_Where_Clause" >
 44     <where >
 45       <foreach collection="example.oredCriteria" item="criteria" separator="or" >
 46         <if test="criteria.valid" >
 47           <trim prefix="(" suffix=")" prefixOverrides="and" >
 48             <foreach collection="criteria.criteria" item="criterion" >
 49               <choose >
 50                 <when test="criterion.noValue" >
 51                   and ${criterion.condition}
 52                 </when>
 53                 <when test="criterion.singleValue" >
 54                   and ${criterion.condition} #{criterion.value}
 55                 </when>
 56                 <when test="criterion.betweenValue" >
 57                   and ${criterion.condition} #{criterion.value} and #{criterion.secondValue}
 58                 </when>
 59                 <when test="criterion.listValue" >
 60                   and ${criterion.condition}
 61                   <foreach collection="criterion.value" item="listItem" open="(" close=")" separator="," >
 62                     #{listItem}
 63                   </foreach>
 64                 </when>
 65               </choose>
 66             </foreach>
 67           </trim>
 68         </if>
 69       </foreach>
 70     </where>
 71   </sql>
 72   <sql id="Base_Column_List" >
 73     id, name, price, pic, createtime
 74   </sql>
 75   <sql id="Blob_Column_List" >
 76     detail
 77   </sql>
 78   <select id="selectByExampleWithBLOBs" resultMap="ResultMapWithBLOBs" parameterType="com.tony.ssm.po.ItemsExample" >
 79     select
 80     <if test="distinct" >
 81       distinct
 82     </if>
 83     <include refid="Base_Column_List" />
 84     ,
 85     <include refid="Blob_Column_List" />
 86     from items
 87     <if test="_parameter != null" >
 88       <include refid="Example_Where_Clause" />
 89     </if>
 90     <if test="orderByClause != null" >
 91       order by ${orderByClause}
 92     </if>
 93   </select>
 94   <select id="selectByExample" resultMap="BaseResultMap" parameterType="com.tony.ssm.po.ItemsExample" >
 95     select
 96     <if test="distinct" >
 97       distinct
 98     </if>
 99     <include refid="Base_Column_List" />
100     from items
101     <if test="_parameter != null" >
102       <include refid="Example_Where_Clause" />
103     </if>
104     <if test="orderByClause != null" >
105       order by ${orderByClause}
106     </if>
107   </select>
108   <select id="selectByPrimaryKey" resultMap="ResultMapWithBLOBs" parameterType="java.lang.Integer" >
109     select 
110     <include refid="Base_Column_List" />
111     ,
112     <include refid="Blob_Column_List" />
113     from items
114     where id = #{id,jdbcType=INTEGER}
115   </select>
116   <delete id="deleteByPrimaryKey" parameterType="java.lang.Integer" >
117     delete from items
118     where id = #{id,jdbcType=INTEGER}
119   </delete>
120   <delete id="deleteByExample" parameterType="com.tony.ssm.po.ItemsExample" >
121     delete from items
122     <if test="_parameter != null" >
123       <include refid="Example_Where_Clause" />
124     </if>
125   </delete>
126   <insert id="insert" parameterType="com.tony.ssm.po.Items" >
127     insert into items (id, name, price, 
128       pic, createtime, detail
129       )
130     values (#{id,jdbcType=INTEGER}, #{name,jdbcType=VARCHAR}, #{price,jdbcType=REAL}, 
131       #{pic,jdbcType=VARCHAR}, #{createtime,jdbcType=TIMESTAMP}, #{detail,jdbcType=LONGVARCHAR}
132       )
133   </insert>
134   <insert id="insertSelective" parameterType="com.tony.ssm.po.Items" >
135     insert into items
136     <trim prefix="(" suffix=")" suffixOverrides="," >
137       <if test="id != null" >
138         id,
139       </if>
140       <if test="name != null" >
141         name,
142       </if>
143       <if test="price != null" >
144         price,
145       </if>
146       <if test="pic != null" >
147         pic,
148       </if>
149       <if test="createtime != null" >
150         createtime,
151       </if>
152       <if test="detail != null" >
153         detail,
154       </if>
155     </trim>
156     <trim prefix="values (" suffix=")" suffixOverrides="," >
157       <if test="id != null" >
158         #{id,jdbcType=INTEGER},
159       </if>
160       <if test="name != null" >
161         #{name,jdbcType=VARCHAR},
162       </if>
163       <if test="price != null" >
164         #{price,jdbcType=REAL},
165       </if>
166       <if test="pic != null" >
167         #{pic,jdbcType=VARCHAR},
168       </if>
169       <if test="createtime != null" >
170         #{createtime,jdbcType=TIMESTAMP},
171       </if>
172       <if test="detail != null" >
173         #{detail,jdbcType=LONGVARCHAR},
174       </if>
175     </trim>
176   </insert>
177   <select id="countByExample" parameterType="com.tony.ssm.po.ItemsExample" resultType="java.lang.Integer" >
178     select count(*) from items
179     <if test="_parameter != null" >
180       <include refid="Example_Where_Clause" />
181     </if>
182   </select>
183   <update id="updateByExampleSelective" parameterType="map" >
184     update items
185     <set >
186       <if test="record.id != null" >
187         id = #{record.id,jdbcType=INTEGER},
188       </if>
189       <if test="record.name != null" >
190         name = #{record.name,jdbcType=VARCHAR},
191       </if>
192       <if test="record.price != null" >
193         price = #{record.price,jdbcType=REAL},
194       </if>
195       <if test="record.pic != null" >
196         pic = #{record.pic,jdbcType=VARCHAR},
197       </if>
198       <if test="record.createtime != null" >
199         createtime = #{record.createtime,jdbcType=TIMESTAMP},
200       </if>
201       <if test="record.detail != null" >
202         detail = #{record.detail,jdbcType=LONGVARCHAR},
203       </if>
204     </set>
205     <if test="_parameter != null" >
206       <include refid="Update_By_Example_Where_Clause" />
207     </if>
208   </update>
209   <update id="updateByExampleWithBLOBs" parameterType="map" >
210     update items
211     set id = #{record.id,jdbcType=INTEGER},
212       name = #{record.name,jdbcType=VARCHAR},
213       price = #{record.price,jdbcType=REAL},
214       pic = #{record.pic,jdbcType=VARCHAR},
215       createtime = #{record.createtime,jdbcType=TIMESTAMP},
216       detail = #{record.detail,jdbcType=LONGVARCHAR}
217     <if test="_parameter != null" >
218       <include refid="Update_By_Example_Where_Clause" />
219     </if>
220   </update>
221   <update id="updateByExample" parameterType="map" >
222     update items
223     set id = #{record.id,jdbcType=INTEGER},
224       name = #{record.name,jdbcType=VARCHAR},
225       price = #{record.price,jdbcType=REAL},
226       pic = #{record.pic,jdbcType=VARCHAR},
227       createtime = #{record.createtime,jdbcType=TIMESTAMP}
228     <if test="_parameter != null" >
229       <include refid="Update_By_Example_Where_Clause" />
230     </if>
231   </update>
232   <update id="updateByPrimaryKeySelective" parameterType="com.tony.ssm.po.Items" >
233     update items
234     <set >
235       <if test="name != null" >
236         name = #{name,jdbcType=VARCHAR},
237       </if>
238       <if test="price != null" >
239         price = #{price,jdbcType=REAL},
240       </if>
241       <if test="pic != null" >
242         pic = #{pic,jdbcType=VARCHAR},
243       </if>
244       <if test="createtime != null" >
245         createtime = #{createtime,jdbcType=TIMESTAMP},
246       </if>
247       <if test="detail != null" >
248         detail = #{detail,jdbcType=LONGVARCHAR},
249       </if>
250     </set>
251     where id = #{id,jdbcType=INTEGER}
252   </update>
253   <update id="updateByPrimaryKeyWithBLOBs" parameterType="com.tony.ssm.po.Items" >
254     update items
255     set name = #{name,jdbcType=VARCHAR},
256       price = #{price,jdbcType=REAL},
257       pic = #{pic,jdbcType=VARCHAR},
258       createtime = #{createtime,jdbcType=TIMESTAMP},
259       detail = #{detail,jdbcType=LONGVARCHAR}
260     where id = #{id,jdbcType=INTEGER}
261   </update>
262   <update id="updateByPrimaryKey" parameterType="com.tony.ssm.po.Items" >
263     update items
264     set name = #{name,jdbcType=VARCHAR},
265       price = #{price,jdbcType=REAL},
266       pic = #{pic,jdbcType=VARCHAR},
267       createtime = #{createtime,jdbcType=TIMESTAMP}
268     where id = #{id,jdbcType=INTEGER}
269   </update>
270 </mapper>

 

2.Service层

(1)

ItemsService.java

 1 package com.tony.ssm.service;
 2 
 3 import java.util.List;
 4 
 5 import com.tony.ssm.po.ItemsCustom;
 6 import com.tony.ssm.po.ItemsQueryVo;
 7 
 8 /**
 9  * 
10  * <p>Title: ItemsService</p>
11  * <p>Description:商品管理service </p>
12  */
13 public interface ItemsService {
14     
15     //商品查询列表
16     public List<ItemsCustom> findItemsList(ItemsQueryVo itemsQueryVo) throws Exception;
17     
18     //根据id查询商品信息
19     /**
20      * 
21      * <p>Title: findItemsById</p>
22      * <p>Description: </p>
23      * @param id 查询商品的id
24      * @return
25      * @throws Exception
26      */
27     public ItemsCustom findItemsById(Integer id) throws Exception;
28     
29     //修改商品信息
30     /**
31      * 
32      * <p>Title: updateItems</p>
33      * <p>Description: </p>
34      * @param id 修改商品的id
35      * @param itemsCustom 修改的商品信息
36      * @throws Exception
37      */
38     public void updateItems(Integer id,ItemsCustom itemsCustom) throws Exception;
39     
40 
41 }

 

ItemsServiceImpl.java

 1 package com.tony.ssm.service.impl;
 2 
 3 import java.util.List;
 4 
 5 import org.springframework.beans.BeanUtils;
 6 import org.springframework.beans.factory.annotation.Autowired;
 7 
 8 import com.tony.ssm.exception.CustomException;
 9 import com.tony.ssm.mapper.ItemsMapper;
10 import com.tony.ssm.mapper.ItemsMapperCustom;
11 import com.tony.ssm.po.Items;
12 import com.tony.ssm.po.ItemsCustom;
13 import com.tony.ssm.po.ItemsQueryVo;
14 import com.tony.ssm.service.ItemsService;
15 
16 /**
17  * 
18  * <p>Title: ItemsServiceImpl</p>
19  * <p>Description: 商品管理</p>
20  */
21 public class ItemsServiceImpl implements ItemsService{
22     
23     @Autowired
24     private ItemsMapperCustom itemsMapperCustom;
25     
26     @Autowired
27     private ItemsMapper itemsMapper;
28 
29     @Override
30     public List<ItemsCustom> findItemsList(ItemsQueryVo itemsQueryVo)
31             throws Exception {
32         //通过ItemsMapperCustom查询数据库
33         return itemsMapperCustom.findItemsList(itemsQueryVo);
34     }
35 
36     @Override
37     public ItemsCustom findItemsById(Integer id) throws Exception {
38         
39         Items items = itemsMapper.selectByPrimaryKey(id);
40         if(items==null){
41             throw new CustomException("修改的商品信息不存在!");
42         }
43         //中间对商品信息进行业务处理
44         //....
45         //返回ItemsCustom
46         ItemsCustom itemsCustom = null;
47         //将items的属性值拷贝到itemsCustom
48         if(items!=null){
49             itemsCustom = new ItemsCustom();
50             BeanUtils.copyProperties(items, itemsCustom);
51         }
52         
53         
54         return itemsCustom;
55         
56     }
57 
58     @Override
59     public void updateItems(Integer id, ItemsCustom itemsCustom) throws Exception {
60         //添加业务校验,通常在service接口对关键参数进行校验
61         //校验 id是否为空,如果为空抛出异常
62         
63         //更新商品信息使用updateByPrimaryKeyWithBLOBs根据id更新items表中所有字段,包括 大文本类型字段
64         //updateByPrimaryKeyWithBLOBs要求必须转入id
65         itemsCustom.setId(id);
66         itemsMapper.updateByPrimaryKeyWithBLOBs(itemsCustom);
67     }
68 
69 }

 

3.Controller层

(1)ItemsController.java

  1 package com.tony.ssm.controller;
  2 
  3 import java.io.File;
  4 import java.util.HashMap;
  5 import java.util.List;
  6 import java.util.Map;
  7 import java.util.UUID;
  8 
  9 import javax.servlet.http.HttpServletRequest;
 10 
 11 import org.springframework.beans.factory.annotation.Autowired;
 12 import org.springframework.stereotype.Controller;
 13 import org.springframework.ui.Model;
 14 import org.springframework.validation.BindingResult;
 15 import org.springframework.validation.ObjectError;
 16 import org.springframework.validation.annotation.Validated;
 17 import org.springframework.web.bind.annotation.ModelAttribute;
 18 import org.springframework.web.bind.annotation.PathVariable;
 19 import org.springframework.web.bind.annotation.RequestMapping;
 20 import org.springframework.web.bind.annotation.RequestMethod;
 21 import org.springframework.web.bind.annotation.RequestParam;
 22 import org.springframework.web.bind.annotation.ResponseBody;
 23 import org.springframework.web.multipart.MultipartFile;
 24 import org.springframework.web.servlet.ModelAndView;
 25 
 26 import com.tony.ssm.controller.validation.ValidateGroup1;
 27 import com.tony.ssm.po.ItemsCustom;
 28 import com.tony.ssm.po.ItemsQueryVo;
 29 import com.tony.ssm.service.ItemsService;
 30 
 31 /**
 32  * 
 33  * <p>Title: ItemsController1</p>
 34  * <p>Description:实现controller接口的 处理器 </p>
 35  */
 36 @Controller
 37 @RequestMapping("/items")
 38 public class ItemsController {
 39 
 40     @Autowired
 41     private ItemsService itemsService;
 42     
 43     @RequestMapping("/queryItems")
 44     public ModelAndView queryItems(HttpServletRequest request,
 45             ItemsQueryVo itemsQueryVo) throws Exception {
 46         
 47         // 测试forward后request是否可以共享
 48         System.out.println(request.getParameter("id"));
 49         
 50         //调用service查找 数据库,查询商品列表
 51         List<ItemsCustom> itemsList = itemsService.findItemsList(itemsQueryVo);
 52 
 53         //返回ModelAndView
 54         ModelAndView modelAndView =  new ModelAndView();
 55         //相当 于request的setAttribut,在jsp页面中通过itemsList取数据
 56         modelAndView.addObject("itemsList", itemsList);
 57         
 58         //指定视图
 59         modelAndView.setViewName("items/itemsList");
 60 
 61         return modelAndView;
 62     }
 63     
 64     //@RequestMapping("/editItems")
 65 //    @RequestMapping(value="/editItems",method={RequestMethod.POST,RequestMethod.GET})
 66 //    public ModelAndView editItems() throws Exception {
 67 //        //调用service根据商品id查询商品信息
 68 //        ItemsCustom itemsCustom = itemsService.findItemsById(1);
 69 //        
 70 //        // 返回ModelAndView
 71 //        ModelAndView modelAndView = new ModelAndView();
 72 //        
 73 //        //将商品信息放到model
 74 //        modelAndView.addObject("itemsCustom", itemsCustom);
 75 //        
 76 //        //商品修改页面1
 77 //        modelAndView.setViewName("items/editItems");
 78 //        
 79 //        return modelAndView;
 80 //    }
 81     
 82     //controller可能返回ModelAndView、String、void
 83     // @RequestParam里边指定request传入参数名称和形参进行绑定。
 84     // 通过required属性指定参数是否必须要传入
 85     // 通过defaultValue可以设置默认值,如果id参数没有传入,将默认值和形参绑定。
 86     @RequestMapping(value="/editItems",method={RequestMethod.POST,RequestMethod.GET})
 87     public String editItems(Model model,@RequestParam(value="id") Integer items_id) throws Exception {
 88         //调用service根据商品id查询商品信息
 89         ItemsCustom itemsCustom = itemsService.findItemsById(items_id);
 90         
 91 //        if(itemsCustom == null){
 92 //            throw new CustomException("商品不存在");
 93 //        }
 94         
 95         // 通过形参中的model将model数据传到页面
 96         // 相当于modelAndView.addObject方法
 97         model.addAttribute("items", itemsCustom);
 98         return "items/editItems";
 99     }
100     
101     @RequestMapping("/editItemsSubmit")
102     public String editItemsSubmit(Model model, 
103             HttpServletRequest request, 
104             Integer id, 
105             @ModelAttribute("items") @Validated(value={ValidateGroup1.class}) ItemsCustom itemsCustom, 
106             BindingResult bindingResult,
107             MultipartFile itemsPic) throws Exception {
108         // 获取校验错误信息
109         if(bindingResult.hasErrors()){
110             List<ObjectError> allErrors = bindingResult.getAllErrors();
111             for(ObjectError error : allErrors){
112                 System.out.println(error.getDefaultMessage());
113             }
114             
115             // 将错误信息传到页面
116             model.addAttribute("allErrors", allErrors);
117             
118             //如果不用@ModelAttribute也可以使用model.addAttribute("items", 

以上是关于SpringMVC,MyBatis商品的增删改查的主要内容,如果未能解决你的问题,请参考以下文章

SpringMVC学习--功能完善

springboot集成mybatis环境搭建以及实现快速开发微服务商品模块基本的增删改查!

超详细的JavaWeb用户的增删改查实现总结

商品的增删改查

mybatis生成的增删改查怎么用

SpringMVC实现数据的增删改查(源码)