mybatis-springmvc+mybatis实现增删改查

2024-08-30 02:32

本文主要是介绍mybatis-springmvc+mybatis实现增删改查,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

源码下载:http://download.csdn.net/detail/u013147600/9074541

遇到过的问题(org.mybatis.spring.transaction.SpringManagedTransactionFactory.newTransaction

http://blog.csdn.net/u013147600/article/details/48182041

所需jar包:

commons-logging-1.0.4.jar
hamcrest-core-1.3.jar
junit-4.12.jar
mybatis-3.2.0-SNAPSHOT.jar
mybatis-spring-1.1.1.jar
ojdbc14.jar
spring-aop-3.2.0.RC2.jar
spring-aspects-3.2.0.RC2.jar
spring-beans-3.2.0.RC2.jar
spring-context-3.2.0.RC2.jar
spring-context-support-3.2.0.RC2.jar
spring-core-3.2.0.RC2.jar
spring-expression-3.2.0.RC2.jar
spring-jdbc-3.2.0.RC2.jar
spring-jms-3.2.0.RC2.jar
spring-orm-3.2.0.RC2.jar
spring-tx-3.2.0.RC2.jar
spring-web-3.2.0.RC2.jar
spring-webmvc-3.2.0.RC2.jar

实体类:

package com.mybatis.entity;/*** @author lyx*	* 2015-9-2下午7:37:44**com.mybatis.entity.StyleCategory**/
public class StyleCategory {private int styleId;private String styleName;public int getStyleId() {return styleId;}public void setStyleId(int styleId) {this.styleId = styleId;}public String getStyleName() {return styleName;}public void setStyleName(String styleName) {this.styleName = styleName;}public StyleCategory(int styleId, String styleName) {super();this.styleId = styleId;this.styleName = styleName;}public StyleCategory(String styleName) {super();this.styleName = styleName;}public StyleCategory() {super();}}

(styleMapper.xml)sql映射文件

<?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.mybatis.dao.StyleMapper"><sql id="queryFields">styleId,styleName</sql><!-- 根据id查询style信息 --><select id="getStyleCategoryInfoById" parameterType="int" resultType="StyleCategory">select<include refid="queryFields"></include>from STYLE_CATEGORY where styleId=#{styleId}</select><select id="getAllStyleCategoryInfo" resultType="StyleCategory" >select * from STYLE_CATEGORY</select><delete id="deleteStyleCategory" parameterType="int">delete from STYLE_CATEGORY where styleId =#{styleId}</delete><update id="updateStyleCategory" parameterType="StyleCategory">update STYLE_CATEGORY set styleName=#{styleName} where styleId=#{styleId}</update><insert id="addStyleCategory" parameterType="StyleCategory" keyProperty="styleId" ><!-- <selectKey resultType="int" order="BEFORE" keyProperty="styleId">select SEQUENCE_STYLECATEGORY.nextval as STYLEID from dual; select nextval('dual')</selectKey> -->insert into STYLE_CATEGORY(styleName) values(#{styleName})</insert></mapper>

mybatis主配置文件:mybatis-config.xml

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configurationPUBLIC "-//mybatis.org//DTD Config 3.0//EN""http://mybatis.org/dtd/mybatis-3-config.dtd"><configuration><!-- 别名 --><typeAliases><typeAlias type="com.mybatis.entity.StyleCategory" alias="StyleCategory"/></typeAliases><!-- 配置sql映射文件 --><mappers><mapper resource="mapper/styleMapper.xml"/></mappers></configuration>

springmvc配置文件:springmvc-servlet.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"  xmlns:context="http://www.springframework.org/schema/context"  xmlns:p="http://www.springframework.org/schema/p"  xmlns:mvc="http://www.springframework.org/schema/mvc"  xmlns:cache="http://www.springframework.org/schema/cache"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  xsi:schemaLocation="http://www.springframework.org/schema/beans  http://www.springframework.org/schema/beans/spring-beans-3.0.xsd  http://www.springframework.org/schema/context  http://www.springframework.org/schema/context/spring-context.xsd  http://www.springframework.org/schema/mvc  http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsdhttp://www.springframework.org/schema/cache  http://www.springframework.org/schema/cache/spring-cache-3.2.xsd "><!-- 基本配置  -begin--><!-- 自动注入 --><context:annotation-config/><!-- 自动扫描包  组件扫描--><context:component-scan base-package="com.mybatis"></context:component-scan><!-- 注释驱动 --><mvc:annotation-driven/> <!-- 配置不用DispatcherServlet 拦截的路径 --><mvc:resources location="/res/" mapping="/res/**"/> <!-- 默认分发处理器不会拦截静态资源 --><!--  <mvc:default-servlet-handler/> --><!-- 默认地址栏访问跳转到首页 --><!--   <mvc:view-controller path="/" view-name="forward:/index"/>  --><!-- 也可以利用<mvc:view-controller/>配置错误页面的跳转 --><!-- 避免IE执行AJAX时,返回JSON出现下载文件 --><bean id="mappingJacksonHttpMessageConverter" class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter"><property name="supportedMediaTypes"><list><value>text/html;charset=UTF-8</value></list></property></bean><!-- 启动Spring MVC的注解功能,完成请求和注解POJO的映射 --><bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter"><property name="messageConverters"><list><ref bean="mappingJacksonHttpMessageConverter" /><!-- json转换器 --></list></property></bean><!-- 视图解析器 --><bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver" ><property name="prefix" value="/"></property><property name="suffix" value=".jsp"></property><property name="viewClass"  value="org.springframework.web.servlet.view.JstlView"></property>  </bean>   	  <!-- 引入项目配置文件 --><!-- <bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"><property name="locations"><list><value>classpath:dbconfig.properties</value></list></property></bean>  --><!-- 	<context:property-placeholder location="classpath:dbconfig.properties"/> --><!-- datasource 配置数据库 --><!-- datasource --><!--  destroy-method="close"的作用是当数据库连接不使用的时候,就把该连接重新放到数据池中,方便下次使用调用.--><!-- <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource" ><property name="url" value="${url}"></property><property name="driverClassName" value="${driverClassName}"></property><property name="username" value="${username}"></property><property name="password" value="${password}"></property></bean> --><bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource"><property name="url" value="jdbc:oracle:thin:@localhost:1521:orcl"></property><property name="driverClassName"  value="oracle.jdbc.driver.OracleDriver"></property><property name="username" value="lyx"></property><property name="password" value="lyx"></property></bean> <!-- mybatis配置 --><bean id="dataSourceTransactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> <property name="dataSource" ref="dataSource"></property></bean><bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"><property name="configLocation" value="classpath:mybatis-config.xml"></property><property name="dataSource" ref="dataSource"></property> </bean> <!-- mapper bean  数据访问接口对应的实现bean通过MapperFactoryBean创建出来。需要执行接口类全称和SqlSession工厂bean的引用。如果注释了这个类时: 可在public interface StyleMapper 上加上注解@Transactional--><!-- <bean id="studentMapper" class="org.mybatis.spring.mapper.MapperFactoryBean">接口类全称<property name="mapperInterface" value="com.mybatis.dao.StyleMapper"></property>工厂bean<property name="sqlSessionFactory" ref="sqlSessionFactory"></property></bean> --><!-- 扫描 --><bean class="org.mybatis.spring.mapper.MapperScannerConfigurer"><property name="annotationClass" value="org.springframework.stereotype.Repository"></property><property name="basePackage" value="com.mybatis"></property><property name="sqlSessionFactory" ref="sqlSessionFactory"></property></bean>  <!-- 基本配置  -end--></beans>

web.xml配置

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"><display-name></display-name>	<welcome-file-list><welcome-file>index.jsp</welcome-file></welcome-file-list><!-- 加载顺序 context-param,listener,filter,servlet --><context-param><param-name>contextConfigLocation</param-name><param-value>classpath:springmvc-servlet.xml</param-value></context-param><!-- 防止发生java.beans.Introspector内存泄露,应将它配置在ContextLoaderListener的前面 --><listener><listener-class>org.springframework.web.util.IntrospectorCleanupListener</listener-class></listener> <!-- 监听 --><listener><listener-class>org.springframework.web.context.ContextLoaderListener</listener-class></listener><!-- 解决乱码问题 --><filter><filter-name>EncodingFilter</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><init-param><param-name>forceEncoding</param-name><param-value>true</param-value></init-param></filter><filter-mapping><filter-name>EncodingFilter</filter-name><url-pattern>/*</url-pattern></filter-mapping><!-- springMvc配置 --><servlet><servlet-name>springMvc</servlet-name><servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class><!-- springMvc-XML配置文件 --><init-param><param-name>contextConfigLocation</param-name><param-value>classpath:springmvc-servlet.xml</param-value></init-param><!-- 执行顺序 --><load-on-startup>0</load-on-startup></servlet><servlet-mapping><servlet-name>springMvc</servlet-name><url-pattern>/</url-pattern></servlet-mapping>
</web-app>

StyleMapper.java接口

package com.mybatis.dao;import java.util.List;import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;import com.mybatis.entity.StyleCategory;@Repository
//@Transactional
public interface StyleMapper {public StyleCategory getStyleCategoryInfoById(int styleId);public List<StyleCategory> getAllStyleCategoryInfo();public boolean deleteStyleCategory(int styleId);public boolean updateStyleCategory(StyleCategory style);public boolean addStyleCategory(StyleCategory style);
}

StyleController.java

package com.mybatis.controller;import java.io.IOException;
import java.io.Reader;
import java.util.List;import javax.servlet.http.HttpServletRequest;import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;import com.mybatis.dao.StyleMapper;
import com.mybatis.entity.StyleCategory;/*** @author lyx*	* 2015-9-2下午2:48:45**com.mybatis.controller.StyleController**/
@Controller
@RequestMapping("/style")
public class StyleController {@Autowiredprivate StyleMapper styleMapper;/*** @param styleId* @param request* @return* @throws IOException* 查询单条数据*/@RequestMapping("/queryByOne")public String queryByOne(@RequestParam("styleId")int styleId,HttpServletRequest request) throws IOException{/*Reader reader =Resources.getResourceAsReader("mybatis-config.xml");SqlSessionFactory sqlSession = new SqlSessionFactoryBuilder().build(reader); SqlSession session =sqlSession.openSession();StyleCategory style=session.selectOne("com.mybatis.dao.StyleMapper.getStyleCategoryInfoById",2);*/StyleCategory style = styleMapper.getStyleCategoryInfoById(styleId);System.out.println(style.getStyleId()+":"+style.getStyleName());request.setAttribute("style", style);return "/index";}/*** @param request* @return* 查询全部数据*/@RequestMapping("/queryAllInfo")public String queryAllInfo(HttpServletRequest request){List<StyleCategory>list = styleMapper.getAllStyleCategoryInfo();for (StyleCategory style : list) {System.out.println(style.getStyleId()+":"+style.getStyleName());}request.setAttribute("styleList", list);return "/list";}/*** @param styleId* @param request* @return* 删除*/@RequestMapping("/deleteInfo")public String deleteInfo(@RequestParam("styleId")int styleId,HttpServletRequest request){boolean b =styleMapper.deleteStyleCategory(styleId);if(b){System.out.println("删除成功");}else{System.out.println("删除失败");}return "redirect:/style/queryAllInfo";}/*** @param request* @return* 增加*/@RequestMapping("/addInfo")public String addInfo(HttpServletRequest request){String styleName = request.getParameter("styleName");StyleCategory style = new StyleCategory(styleName);if(styleMapper.addStyleCategory(style)){System.out.println("增加成功");}else{System.out.println("增加失败");}return "redirect:/style/queryAllInfo";}/*** @param styleId* @param request* @return* 先跳转到更新页面*/@RequestMapping("/beforeUpdate")public String beforeUpdate(@RequestParam("styleId") int styleId,HttpServletRequest request){StyleCategory style = styleMapper.getStyleCategoryInfoById(styleId);System.out.println("Update:"+styleId+";"+style.getStyleName());request.setAttribute("style",style);return "/update";}/*** @param request* @return* 更新数据*/@RequestMapping("/updateInfo")public String updateInfo(HttpServletRequest request){int styleId = Integer.valueOf(request.getParameter("styleId"));String styleName =request.getParameter("styleName");StyleCategory style = new StyleCategory(styleId, styleName);boolean b=styleMapper.updateStyleCategory(style);if(b){System.out.println("更新成功");}else{System.out.println("更新失败");}return "redirect:/style/queryAllInfo";}}

list.jsp页面

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html><head><base href="<%=basePath%>"><title>My JSP 'index.jsp' starting page</title><meta http-equiv="pragma" content="no-cache"><meta http-equiv="cache-control" content="no-cache"><meta http-equiv="expires" content="0">    <meta http-equiv="keywords" content="keyword1,keyword2,keyword3"><meta http-equiv="description" content="This is my page"><!--<link rel="stylesheet" type="text/css" href="styles.css">--></head><body><h3><a href="<%=path%>/add.jsp" target="_blank">增加 </a></h3><table><tr><th>StyleId</th><th>StyleName</th><th>Operate</th></tr><c:forEach items="${styleList}"  var="style" varStatus="stus"><tr><td>${style.styleId }</td><td>${style.styleName }</td><td><a href="<%=basePath%>/style/queryByOne?styleId=${style.styleId } " target="_blank">查看</a><a href="<%=basePath%>/style/deleteInfo?styleId=${style.styleId }" target="_blank">删除</a><a href="<%=basePath%>/style/beforeUpdate?styleId=${style.styleId }" target="_blank">修改</a></td></tr></c:forEach></table></body>
</html>

index.jsp页面

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html><head><base href="<%=basePath%>"><title>My JSP 'index.jsp' starting page</title><meta http-equiv="pragma" content="no-cache"><meta http-equiv="cache-control" content="no-cache"><meta http-equiv="expires" content="0">    <meta http-equiv="keywords" content="keyword1,keyword2,keyword3"><meta http-equiv="description" content="This is my page"><!--<link rel="stylesheet" type="text/css" href="styles.css">--></head><body>查看<br><h2>styleId:${style.styleId } ----styleName: ${style.styleName }</h2></body>
</html>

add.jsp

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html><head><base href="<%=basePath%>"><title>My JSP 'index.jsp' starting page</title><meta http-equiv="pragma" content="no-cache"><meta http-equiv="cache-control" content="no-cache"><meta http-equiv="expires" content="0">    <meta http-equiv="keywords" content="keyword1,keyword2,keyword3"><meta http-equiv="description" content="This is my page"><!--<link rel="stylesheet" type="text/css" href="styles.css">--></head><body><br><h2>增加</h2><form action="<%= request.getContextPath()%>/style/addInfo" method="post" >styleName:<input type="text" name="styleName" ><input type="submit" value="提交"></form></body>
</html>


update.jsp

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html><head><base href="<%=basePath%>"><title>My JSP 'index.jsp' starting page</title><meta http-equiv="pragma" content="no-cache"><meta http-equiv="cache-control" content="no-cache"><meta http-equiv="expires" content="0">    <meta http-equiv="keywords" content="keyword1,keyword2,keyword3"><meta http-equiv="description" content="This is my page"><!--<link rel="stylesheet" type="text/css" href="styles.css">--></head><body><br><h2>修改</h2><form action="<%= request.getContextPath()%>/style/updateInfo" method="post" >styleId:<input type="text" name="styleId" value="${style.styleId}" readonly="readonly">styleName:<input type="text" name="styleName" value="${style.styleName }"><input type="submit" value="提交"></form></body>
</html>


这篇关于mybatis-springmvc+mybatis实现增删改查的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/1119544

相关文章

Java中StopWatch的使用示例详解

《Java中StopWatch的使用示例详解》stopWatch是org.springframework.util包下的一个工具类,使用它可直观的输出代码执行耗时,以及执行时间百分比,这篇文章主要介绍... 目录stopWatch 是org.springframework.util 包下的一个工具类,使用它

Java进行文件格式校验的方案详解

《Java进行文件格式校验的方案详解》这篇文章主要为大家详细介绍了Java中进行文件格式校验的相关方案,文中的示例代码讲解详细,感兴趣的小伙伴可以跟随小编一起学习一下... 目录一、背景异常现象原因排查用户的无心之过二、解决方案Magandroidic Number判断主流检测库对比Tika的使用区分zip

Java实现时间与字符串互相转换详解

《Java实现时间与字符串互相转换详解》这篇文章主要为大家详细介绍了Java中实现时间与字符串互相转换的相关方法,文中的示例代码讲解详细,感兴趣的小伙伴可以跟随小编一起学习一下... 目录一、日期格式化为字符串(一)使用预定义格式(二)自定义格式二、字符串解析为日期(一)解析ISO格式字符串(二)解析自定义

opencv图像处理之指纹验证的实现

《opencv图像处理之指纹验证的实现》本文主要介绍了opencv图像处理之指纹验证的实现,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学... 目录一、简介二、具体案例实现1. 图像显示函数2. 指纹验证函数3. 主函数4、运行结果三、总结一、

Java使用Curator进行ZooKeeper操作的详细教程

《Java使用Curator进行ZooKeeper操作的详细教程》ApacheCurator是一个基于ZooKeeper的Java客户端库,它极大地简化了使用ZooKeeper的开发工作,在分布式系统... 目录1、简述2、核心功能2.1 CuratorFramework2.2 Recipes3、示例实践3

Springboot处理跨域的实现方式(附Demo)

《Springboot处理跨域的实现方式(附Demo)》:本文主要介绍Springboot处理跨域的实现方式(附Demo),具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不... 目录Springboot处理跨域的方式1. 基本知识2. @CrossOrigin3. 全局跨域设置4.

springboot security使用jwt认证方式

《springbootsecurity使用jwt认证方式》:本文主要介绍springbootsecurity使用jwt认证方式,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地... 目录前言代码示例依赖定义mapper定义用户信息的实体beansecurity相关的类提供登录接口测试提供一

Spring Boot 3.4.3 基于 Spring WebFlux 实现 SSE 功能(代码示例)

《SpringBoot3.4.3基于SpringWebFlux实现SSE功能(代码示例)》SpringBoot3.4.3结合SpringWebFlux实现SSE功能,为实时数据推送提供... 目录1. SSE 简介1.1 什么是 SSE?1.2 SSE 的优点1.3 适用场景2. Spring WebFlu

基于SpringBoot实现文件秒传功能

《基于SpringBoot实现文件秒传功能》在开发Web应用时,文件上传是一个常见需求,然而,当用户需要上传大文件或相同文件多次时,会造成带宽浪费和服务器存储冗余,此时可以使用文件秒传技术通过识别重复... 目录前言文件秒传原理代码实现1. 创建项目基础结构2. 创建上传存储代码3. 创建Result类4.

Java利用JSONPath操作JSON数据的技术指南

《Java利用JSONPath操作JSON数据的技术指南》JSONPath是一种强大的工具,用于查询和操作JSON数据,类似于SQL的语法,它为处理复杂的JSON数据结构提供了简单且高效... 目录1、简述2、什么是 jsONPath?3、Java 示例3.1 基本查询3.2 过滤查询3.3 递归搜索3.4