ssm(16)增删改查(1)

1.依然是对商品items的操作为例:

项目结构:

 

controller层    ItemController:

@Controller
public class ItemsController {
    @Autowired
    private ItemsService itemsService;
    @RequestMapping("/queryItems")
    public ModelAndView queryItems() throws Exception {
        // SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

        List<Items> itemsList = itemsService.finditemsList();
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.addObject("itemsList", itemsList);
        modelAndView.setViewName("/items/itemsList");
        return modelAndView;
    }
    @RequestMapping("/editItems")
    public ModelAndView editItems() throws Exception {
        //model要调用service获取
        ItemsCustom itemsCustom=itemsService.finItemById(1);
        ModelAndView modelAndView = new ModelAndView();
      //  List<Items> itemsList = itemsService.finditemsList();
      //将商品信息放到model
        modelAndView.addObject("itemsCustom", itemsCustom);
        //指定view
        modelAndView.setViewName("/items/editItems");
        return modelAndView;
    }
    @RequestMapping("/editItemsSubmit")
    public ModelAndView editItemsSubmit()throws Exception{
        ModelAndView modelAndView=new ModelAndView();
        //调用service更新商品信息,页面需将商品信息传到此方法
        //。。。。。。。
        modelAndView.setViewName("success");
        return modelAndView;
    }
}
mapper层    ItemsMapper
public interface ItemsMapper {
    List<Items> selectByExampleWithBLOBs(ItemsExample example);

    List<Items> selectByExample(ItemsExample example);

    Items selectByPrimaryKey(Integer id);

    int updateByPrimaryKeyWithBLOBs(Items record);

}

拓展类ItemsMapperCustom:

public interface ItemsMapperCustom {
    //商品查询列表
    //finditemsList(ItemsQueryVo itemsQueryVo)
    public List<Items>finditemsList()throws Exception;
}

自定义pojo类ItemsCustom 继承Items

public class ItemsCustom extends Items {
}

itemservice接口:

public interface ItemsService {
    //它和mapper接口中的方法一样,但仅此这个,别的都是不一样的,hibenate中service接口和dao接口的代码都是一样的,只是调换了顺序,但mybatis是不一样的
    public List<Items> finditemsList()throws Exception;
    public ItemsCustom finItemById(int id)throws Exception;
    public void updateItems(Integer id,ItemsCustom itemsCustom)throws Exception;
}

service接口的实现类:ItemsServiceImpl

public class ItemsServiceImpl implements ItemsService {
    @Autowired
    private ItemsMapperCustom itemsMapperCustom;
    @Autowired
    private ItemsMapper itemsMapper;

    @Override
    public List<Items> finditemsList() throws Exception {
        //通过注入itemmapper,并用它查询数据库,因为我们在配置文件中遵循了同包同名,启动了注解开发,使用了mapper代理开发的方式
        // 自动扫描指定路径下mapper文件, 并将Mapper接口生成代理注入到Spring容器中由spring进行管理。
        List<Items> list=itemsMapperCustom.finditemsList();
        return list;
    }

    @Override
    public ItemsCustom finItemById(int id) throws Exception {
        Items items=itemsMapper.selectByPrimaryKey(id);
        //中间对商品信息进行业务处理
        //。。。。
        //返回ItemsCustom
        //比如查询商品是否过期,定义扩展类
        ItemsCustom itemsCustom=new ItemsCustom();
        //将item里的属性值拷贝到itemsCustomm,利用工具
        BeanUtils.copyProperties(items,itemsCustom);
        return itemsCustom;
    }

    @Override
    public void updateItems(Integer id, ItemsCustom itemsCustom) throws Exception {
           //添加业务校验,通常在service接口对关键参数进行校验
        //校验id是否为空,为空,则抛出异常,int不好判空,所以建议用Interger
        //更新商品
        //更加updateByExampleWithBLOBs()更新items表里的所有字段,包括大文本类型(text),setId()必须有,哪怕重复
        itemsCustom.setId(id);
        itemsMapper.updateByPrimaryKeyWithBLOBs(itemsCustom);
    }
}

itemmapperCustom.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="cn.itcast.ssm.mapper.ItemsMapperCustom">
    <sql id="query_items_where">
        items.name like '%水%'
/*使用if判断,确保拼接正确*/
      <!--  <if test="itemsCustom!=null">
            <if test="itemsCustom.name !=null and itemsCustom.name!='">
                items.name like '%水%'
            </if>
        </if>-->

    </sql>
   <!-- parameterType="cn.itcast.ssm.pojo.ItemsQueryVo"-->
     <select id="finditemsList"  resultType="cn.itcast.ssm.pojo.Items">
         select * from items
         <where>
             <include refid="query_items_where"></include>
         </where>
     </select>
</mapper>

下面重点是applicationContext的相关配置,坑很多,故记录一下:

applicationContext-dao.xml:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:mvc="http://www.springframework.org/schema/mvc"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
		http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
		http://www.springframework.org/schema/mvc
		http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd
		http://www.springframework.org/schema/context
		http://www.springframework.org/schema/context/spring-context-4.0.xsd
		http://www.springframework.org/schema/aop
		http://www.springframework.org/schema/aop/spring-aop-4.0.xsd
		http://www.springframework.org/schema/tx
		http://www.springframework.org/schema/tx/spring-tx-4.0.xsd
		http://www.springframework.org/schema/task
   		http://www.springframework.org/schema/task/spring-task-4.0.xsd
		http://code.alibabatech.com/schema/dubbo">

<!-- 加载配置文件 -->
    <context:property-placeholder location="classpath:db.properties" />
    <!-- 数据库连接池,druid其实就是一个bean,一个封装好的jdbc的类 -->
    <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource"
          destroy-method="close">
        <property name="url" value="${jdbc.url}" />
        <property name="username" value="${jdbc.username}" />
        <property name="password" value="${jdbc.password}" />
        <property name="driverClassName" value="${jdbc.driver}" />
        <property name="maxActive" value="10" />
        <property name="minIdle" value="5" />
    </bean>
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <!-- 加载mybatis的全局配置文件 -->
        <property name="configLocation" value="classpath:mybatis/SqlMapConfig.xml" />
        <!-- mapper扫描 ,在这里指定mapper文件的扫描路径-->
        <property name="mapperLocations" value="classpath:mapper/*.xml"></property>
        <!-- 数据库连接池 -->
        <property name="dataSource" ref="dataSource" />
    </bean>


    <!-- 让spring管理sqlsessionfactory 使用mybatis和spring整合包中的 -->


    <!--在这里指定mapper文件的位置-->
    <!-- mapper代理开发自动扫描 将Mapper接口生成代理注入到Spring,mapper扫描器 -->
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
       <!-- 扫描的包名-->
        <property name="basePackage" value="cn.itcast.ssm.mapper" />
        <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/>
    </bean>
</beans>

spring-mvc.xml:

<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:mvc="http://www.springframework.org/schema/mvc"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
		http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
		http://www.springframework.org/schema/mvc
		http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd
		http://www.springframework.org/schema/context
		http://www.springframework.org/schema/context/spring-context-4.0.xsd
		http://www.springframework.org/schema/aop
		http://www.springframework.org/schema/aop/spring-aop-4.0.xsd
		http://www.springframework.org/schema/tx
		http://www.springframework.org/schema/tx/spring-tx-4.0.xsd
		http://www.springframework.org/schema/task
   		http://www.springframework.org/schema/task/spring-task-4.0.xsd
		http://code.alibabatech.com/schema/dubbo">

    <!--配置文件主要是:   自动扫描控制器,视图模式,注解的启动这三个-->
   <!-- 注解映射器:-->
 <!--   <bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping"/>
   &lt;!&ndash; 注解适配器:&ndash;&gt;
    <bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter"/>-->
   <!-- 使用mvc:annotation-driver可完全代替上边注解映射器和注解适配器的配置,并且mvc:annotation-driver默认加载很多的参数绑定方法
    比如json的转换的解析器,它就默认将其加载了

-->
    <context:component-scan base-package="cn.itcast.ssm.controller"/>
    <mvc:annotation-driven></mvc:annotation-driven>
    <!--对于注解的handler可以单个配置,可以每次手动的在配置文件中添加bean注册,但建议使用组件扫描方式注册bean-->

    <!--HttpRequestHandlerAdapter适配器,要求编写handler实现HttpRequestHandler-->
   <!-- <bean class="org.springframework.web.servlet.mvc.HttpRequestHandlerAdapter"/>-->

   <!-- 视图解析器-->
  <!--  解析jsp,默认使用jstl,classpath下的有jstl的包,视图解析器的有代码://classname     javax.servlet.jsp.jstl.core.Config-->
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/WEB-INF/jsp/"/>
        <property name="suffix" value=".jsp"/>
    </bean>

</beans>

editItems.jsp:

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>
<html>
<head>
    <meta http-equiv="Content-Type" content="text/html;charset=utf-8"/>
    <title>修改商品</title>
</head>
<body>
<form action="${pageContext.request.contextPath}/editItemsSubmit.action" method="post" id="itemForm" enctype="multipart/form-data">
    <<input type="hidden" name="id" value="${itemsCustom.id}"/>
   修改商品信息:
    <table width="100%" border="1">
        <tr>
            <td>商品名称</td>
            <td><input type="text" name="name" value="${itemsCustom.name}"></td>
        </tr>
        <tr>

            <td>商品价格</td>
            <td><input type="text" name="price" value="${itemsCustom.price}"></td>
           <%-- <td>生产日期</td>
            <td>商品描述</td>
            <td>操作</td>--%>
        </tr>
        <tr>
            <td>商品简介</td>
            <td><textarea rows="3" cols="30" name="detail">${itemsCustom.detail}</textarea></td>
        </tr>
        <tr>
            <td colspan="2" align="center"><input type="submit" value="提交"/></td>
        </tr>
    </table>
</form>
</body>
</html>

itemsLists.jsp:

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>
<html>
<head>
    <meta http-equiv="Content-Type" content="text/html;charset=utf-8"/>
    <title>查询商品列表</title>
</head>
<body>
<form action="${pageContext.request.contextPath}/item/queryItem.action" method="post">
    查询条件:
    <table width="100%" border="1">
        <tr>
            <td><input type="submit" value="查询"></td>
        </tr>
    </table>
    商品列表:
    <table width="100%" border="1">
        <tr>
            <td>商品名称</td>
            <td>商品价格</td>
            <td>生产日期</td>
            <td>商品描述</td>
            <td>操作</td>
        </tr>
        <c:forEach items="${itemsList}" var="item">
            <tr>
            <td>${item.name}</td>
            <td>${item.price}</td>
            <td><fmt:formatDate value="${item.createtime}" pattern="yyyy-MM-dd HH:mm:ss"/></td>
            <td>${item.detail}</td>

            <td><a href="${pageContext.request.contextPath}/editItems.action?id=${item.id}">修改</a> </td>
            </tr>
        </c:forEach>
    </table>
</form>
</body>
</html>

success.jsp:

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
调试成功
</body>
</html>

剩下的代码可参考前面的记录补充完善。

猜你喜欢

转载自blog.csdn.net/qq_41063141/article/details/83901024