溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶(hù)服務(wù)條款》

利用SpringMVC如何操作數(shù)據(jù)庫(kù)并進(jìn)行增刪改查操作

發(fā)布時(shí)間:2020-11-11 15:50:30 來(lái)源:億速云 閱讀:739 作者:Leah 欄目:編程語(yǔ)言

利用SpringMVC如何操作數(shù)據(jù)庫(kù)并進(jìn)行增刪改查操作?相信很多沒(méi)有經(jīng)驗(yàn)的人對(duì)此束手無(wú)策,為此本文總結(jié)了問(wèn)題出現(xiàn)的原因和解決方法,通過(guò)這篇文章希望你能解決這個(gè)問(wèn)題。

雖然已經(jīng)在做關(guān)于SpringMVC的項(xiàng)目。但是還沒(méi)有寫(xiě)一些比較系統(tǒng)的博客。今天就先來(lái)說(shuō)一說(shuō)最簡(jiǎn)單的增刪改查吧。這個(gè)例子是基于SpringMVC+Spring+Mybatis實(shí)現(xiàn)的。

環(huán)境配置

主要是幾項(xiàng)配置:springmvc的配置,spring的配置,MyBatis的配置,jdbc的配置,和web.xml配置

springmvc.xml

<&#63;xml version="1.0" encoding="UTF-8"&#63;>
<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-3.2.xsd 
    http://www.springframework.org/schema/mvc 
    http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd 
    http://www.springframework.org/schema/context 
    http://www.springframework.org/schema/context/spring-context-3.2.xsd 
    http://www.springframework.org/schema/aop 
    http://www.springframework.org/schema/aop/spring-aop-3.2.xsd 
    http://www.springframework.org/schema/tx 
    http://www.springframework.org/schema/tx/spring-tx-3.2.xsd">
  <!-- 文件掃描 -->
  <context:component-scan base-package="com.zhao"></context:component-scan>

  <!-- annotation-driven:默認(rèn)創(chuàng)建了多個(gè)對(duì)象:RequestMappingHandlerMapping,RequestMappingHandlerAdapter
    也就提供對(duì)json格式支持
   -->
  <mvc:annotation-driven/>
  <!-- 視圖解析器 -->
  <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
    <property name="prefix" value="/WEB-INF/jsp/" />
    <property name="suffix" value=".jsp" />
  </bean>
</beans>

beans.xml(Spring的配置)

<&#63;xml version="1.0" encoding="UTF-8"&#63;>
<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-3.2.xsd 
    http://www.springframework.org/schema/mvc 
    http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd 
    http://www.springframework.org/schema/context 
    http://www.springframework.org/schema/context/spring-context-3.2.xsd 
    http://www.springframework.org/schema/aop 
    http://www.springframework.org/schema/aop/spring-aop-3.2.xsd 
    http://www.springframework.org/schema/tx 
    http://www.springframework.org/schema/tx/spring-tx-3.2.xsd">

    <context:component-scan base-package="com.zhao"></context:component-scan>

  <!-- 第一步:配置數(shù)據(jù)源 -->
  <context:property-placeholder location="classpath:jdbc.properties" />
  <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
    <property name="jdbcUrl" value="${jdbc.url}"></property>
    <property name="driverClass" value="${jdbc.driver}"></property>
    <property name="user" value="${jdbc.username}"></property>
    <property name="password" value="${jdbc.password}"></property>

  </bean>

  <!-- 第二步:創(chuàng)建sqlSessionFactory。生產(chǎn)sqlSession -->
  <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
  <property name="dataSource" ref="dataSource"></property>
  <property name="configLocation" value="classpath:sqlMapConfig.xml"></property>
  </bean>
  <!-- 配置mybatis接口代理開(kāi)發(fā)
    * 接口類(lèi)名和映射文件必須同名
    * 接口類(lèi)和映射文件必須在同一個(gè)目錄 下
    * 映射文件namespace名字必須是接口的全類(lèi)路徑名
    * 接口的方法名必須和映射Statement的id一致
   -->
   <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
   <property name="basePackage" value="com.zhao.mapper"></property>
   <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"></property>
   </bean>


  <!-- 第三步:事務(wù) -->
  <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
  <property name="dataSource" ref="dataSource"></property>
  </bean>

  <!-- 配置通知 -->
  <tx:advice id="txAdvice" transaction-manager="transactionManager">
  <tx:attributes>
  <tx:method name="save*" propagation="REQUIRED" />
  <tx:method name="update*" propagation="REQUIRED" />
  <tx:method name="delete*" propagation="REQUIRED" />
  <tx:method name="insert*" propagation="REQUIRED" />
  <tx:method name="*" propagation="REQUIRED" />  
  </tx:attributes>

  </tx:advice>

  <!-- 配置攔截service -->
  <aop:config>
  <aop:advisor advice-ref="txAdvice" pointcut="execution(* com.zhao.service.*.*(..))"/>
  </aop:config>

</beans>

jdbc.properties(數(shù)據(jù)庫(kù)jdbc的配置)

jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc\:mysql\://localhost\:8888/blog
jdbc.username=root
jdbc.password=123456

web.xml的配置

<&#63;xml version="1.0" encoding="UTF-8"&#63;>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" version="2.5">
 <display-name></display-name>
 <welcome-file-list>
  <welcome-file>index.jsp</welcome-file>
 </welcome-file-list>
 <context-param>
  <param-name>contextConfigLocation</param-name>
  <param-value>classpath:beans.xml</param-value>
 </context-param>
 <listener>
  <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
 </listener>
 <filter>
  <filter-name>CharacterEncodingFilter</filter-name>
  <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
  <init-param>
   <param-name>encoding</param-name>
   <param-value>utf-8</param-value>
  </init-param>
 </filter>
 <filter-mapping>
  <filter-name>CharacterEncodingFilter</filter-name>
  <url-pattern>/*</url-pattern>
 </filter-mapping>


 <servlet>
  <servlet-name>springmvc</servlet-name>
  <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
  <init-param>
   <param-name>contextConfigLocation</param-name>
   <param-value>classpath:springmvc.xml</param-value>
  </init-param>
  <load-on-startup>1</load-on-startup>
 </servlet>
 <servlet-mapping>
  <servlet-name>springmvc</servlet-name>
  <url-pattern>/</url-pattern>
 </servlet-mapping>
</web-app>

spring的配置中已經(jīng)添加了對(duì)數(shù)據(jù)源的支持。。在基礎(chǔ)的應(yīng)用中我們并不需要對(duì)MyBatis做什么配置。因此基本的配置就是如上所示。

增刪改查的操作

首先是查的操作

列表顯示所有信息

Controller層實(shí)現(xiàn)

 @RequestMapping("/list")
  public String UserList(Model model) {

    List<User> list =userService.findAll();
    //傳遞數(shù)據(jù)至前端
    model.addAttribute("list",list);
    //返回對(duì)應(yīng)視圖
    return "itemsList";
  }

對(duì)應(yīng)的Service實(shí)現(xiàn)層

  @Override
  public List<User> findAll() {
    UserExample example = new UserExample();
    List<User> list=  userMapper.selectByExample(example);
    return list;
  }

前端頁(yè)面實(shí)現(xiàn)細(xì)節(jié)

<table width="100%" border=1>
<tr>
  <td>ID</td>
  <td>用戶(hù)名</td>
  <td>密碼</td>
  <td>昵稱(chēng)</td>
  <td>電子郵箱</td>
  <td>操作</td>
</tr>
<c:forEach items="${list}" var="item">
<tr>
  <td>
  <input type="checkbox" name="iduser" value="${item.iduser}">
  </td>
  <td>${item.username }</td>
  <td>${item.password }</td>
  <td>${item.nickname }</td>
  <td>${item.email }</td>
  <td><a href="${pageContext.request.contextPath }/user/edit&#63;iduser=${item.iduser}" rel="external nofollow" >修改</a>
  <a href="${pageContext.request.contextPath }/user/deleteByID&#63;iduser=${item.iduser}" rel="external nofollow" >刪除</a>
  </td>

</tr>
</c:forEach>

根據(jù)id修改相應(yīng)的數(shù)據(jù)

Controller層實(shí)現(xiàn)

  @RequestMapping("/edit")
  public String Edit(Integer iduser,Model model)
  {
    User user=userService.findById(iduser);
    model.addAttribute("item",user);
    return "editItem";
  }

Service實(shí)現(xiàn)層實(shí)現(xiàn)

  @RequestMapping("/edit")
  public String Edit(Integer iduser,Model model)
  {
    User user=userService.findById(iduser);
    //將要修改的值傳遞到前端
    model.addAttribute("item",user);
    return "editItem";
  }
  @RequestMapping(value ="/saveOrUpdate",method = RequestMethod.POST)
  public String saveOrUpdate(User user)
  {
    //保存修改的值
    userService.update(user);
    //跳轉(zhuǎn)到對(duì)應(yīng)的list路由
    return "redirect:list";
  }

前端頁(yè)面實(shí)現(xiàn)

<form id="itemForm" action="${pageContext.request.contextPath }/user/saveOrUpdate" method="post">
<input type="hidden" name="iduser" value="${item.iduser }"/>
修改商品信息:
<table width="100%" border=1>
<tr>
  <td>用戶(hù)名稱(chēng)</td>
  <td><input type="text" name="username" value="${item.username }"/></td>
</tr>
<tr>
  <td>密碼</td>
  <td><input type="text" name="password" value="${item.password}"/></td>
</tr>
<tr>
  <td>昵稱(chēng)</td>
  <td><input type="text" name="nickname" value="${item.nickname}"/></td>
</tr>
<tr>
  <td>email</td>
  <td><input type="text" name="email" value="${item.email}"/></td>
</tr>

<tr>
<td colspan="2" align="center"><input type="submit" value="提交"/>
</td>
</tr>
</table>

</form>

上述流程并未對(duì)是否查詢(xún)成功做對(duì)應(yīng)處理。有興趣的同學(xué)可以嘗試將其補(bǔ)充完整

根據(jù)id刪除對(duì)應(yīng)的數(shù)據(jù)

Controller層實(shí)現(xiàn)

  @RequestMapping("/deleteByID")
  public String deleteByID(Integer iduser)
  {

    userService.deleteById(iduser);
    return "redirect:list";
  }

Service實(shí)現(xiàn)層實(shí)現(xiàn)

  @Override
  public void deleteById(Integer iduser) {
    // TODO Auto-generated method stub
    userMapper.deleteByPrimaryKey(iduser);
  }

前端頁(yè)面上需要做的修改。已經(jīng)在上述列表頁(yè)面展示過(guò)了。在此不再贅述。

新增數(shù)據(jù)

Controller層實(shí)現(xiàn)

  //超鏈接到對(duì)應(yīng)的頁(yè)面
  @RequestMapping("/add")
  public String Add()
  {
    return "AddUser";
  }
  //保存數(shù)據(jù)到數(shù)據(jù)庫(kù)后跳轉(zhuǎn)到列表頁(yè)面
  @RequestMapping("/addUser")
  public String Insert(User user)
  {
    userService.insert(user);
    return "redirect:list";
  }

Service實(shí)現(xiàn)層實(shí)現(xiàn)

  @Override
  public void insert(User user) {
    userMapper.insert(user);

  }

前端頁(yè)面實(shí)現(xiàn)

<form id="itemForm" action="${pageContext.request.contextPath }/user/addUser" method="post">
商品信息:
<table width="100%" border=1>
<tr>
  <td>用戶(hù)名稱(chēng)</td>
  <td><input type="text" name="username"/></td>
</tr>
<tr>
  <td>密碼</td>
  <td><input type="text" name="password"/></td>
</tr>
<tr>
  <td>昵稱(chēng)</td>
  <td><input type="text" name="nickname" /></td>
</tr>
<tr>
  <td>email</td>
  <td><input type="text" name="email"/></td>
</tr>
<tr>
<td colspan="2" align="center"><input type="submit" value="提交"/>
</td>
</tr>
</table>

</form>

看完上述內(nèi)容,你們掌握利用SpringMVC如何操作數(shù)據(jù)庫(kù)并進(jìn)行增刪改查操作的方法了嗎?如果還想學(xué)到更多技能或想了解更多相關(guān)內(nèi)容,歡迎關(guān)注億速云行業(yè)資訊頻道,感謝各位的閱讀!

向AI問(wèn)一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI