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

相关文章

JVM 的类初始化机制

前言 当你在 Java 程序中new对象时,有没有考虑过 JVM 是如何把静态的字节码(byte code)转化为运行时对象的呢,这个问题看似简单,但清楚的同学相信也不会太多,这篇文章首先介绍 JVM 类初始化的机制,然后给出几个易出错的实例来分析,帮助大家更好理解这个知识点。 JVM 将字节码转化为运行时对象分为三个阶段,分别是:loading 、Linking、initialization

Spring Security 基于表达式的权限控制

前言 spring security 3.0已经可以使用spring el表达式来控制授权,允许在表达式中使用复杂的布尔逻辑来控制访问的权限。 常见的表达式 Spring Security可用表达式对象的基类是SecurityExpressionRoot。 表达式描述hasRole([role])用户拥有制定的角色时返回true (Spring security默认会带有ROLE_前缀),去

浅析Spring Security认证过程

类图 为了方便理解Spring Security认证流程,特意画了如下的类图,包含相关的核心认证类 概述 核心验证器 AuthenticationManager 该对象提供了认证方法的入口,接收一个Authentiaton对象作为参数; public interface AuthenticationManager {Authentication authenticate(Authenti

Spring Security--Architecture Overview

1 核心组件 这一节主要介绍一些在Spring Security中常见且核心的Java类,它们之间的依赖,构建起了整个框架。想要理解整个架构,最起码得对这些类眼熟。 1.1 SecurityContextHolder SecurityContextHolder用于存储安全上下文(security context)的信息。当前操作的用户是谁,该用户是否已经被认证,他拥有哪些角色权限…这些都被保

Spring Security基于数据库验证流程详解

Spring Security 校验流程图 相关解释说明(认真看哦) AbstractAuthenticationProcessingFilter 抽象类 /*** 调用 #requiresAuthentication(HttpServletRequest, HttpServletResponse) 决定是否需要进行验证操作。* 如果需要验证,则会调用 #attemptAuthentica

Spring Security 从入门到进阶系列教程

Spring Security 入门系列 《保护 Web 应用的安全》 《Spring-Security-入门(一):登录与退出》 《Spring-Security-入门(二):基于数据库验证》 《Spring-Security-入门(三):密码加密》 《Spring-Security-入门(四):自定义-Filter》 《Spring-Security-入门(五):在 Sprin

Java架构师知识体认识

源码分析 常用设计模式 Proxy代理模式Factory工厂模式Singleton单例模式Delegate委派模式Strategy策略模式Prototype原型模式Template模板模式 Spring5 beans 接口实例化代理Bean操作 Context Ioc容器设计原理及高级特性Aop设计原理Factorybean与Beanfactory Transaction 声明式事物

mybatis的整体架构

mybatis的整体架构分为三层: 1.基础支持层 该层包括:数据源模块、事务管理模块、缓存模块、Binding模块、反射模块、类型转换模块、日志模块、资源加载模块、解析器模块 2.核心处理层 该层包括:配置解析、参数映射、SQL解析、SQL执行、结果集映射、插件 3.接口层 该层包括:SqlSession 基础支持层 该层保护mybatis的基础模块,它们为核心处理层提供了良好的支撑。

Java进阶13讲__第12讲_1/2

多线程、线程池 1.  线程概念 1.1  什么是线程 1.2  线程的好处 2.   创建线程的三种方式 注意事项 2.1  继承Thread类 2.1.1 认识  2.1.2  编码实现  package cn.hdc.oop10.Thread;import org.slf4j.Logger;import org.slf4j.LoggerFactory

hdu1043(八数码问题,广搜 + hash(实现状态压缩) )

利用康拓展开将一个排列映射成一个自然数,然后就变成了普通的广搜题。 #include<iostream>#include<algorithm>#include<string>#include<stack>#include<queue>#include<map>#include<stdio.h>#include<stdlib.h>#include<ctype.h>#inclu