1.创建数据库springmvc及表items,且插入一些数据

  1. DROP TABLE IF EXISTS `items`;
  2. CREATE TABLE `items` (
  3. `id` int(11) NOT NULL AUTO_INCREMENT,
  4. `name` varchar(32) NOT NULL COMMENT '商品名称',
  5. `price` float(10,1) NOT NULL COMMENT '商品定价',
  6. `detail` text COMMENT '商品描述',
  7. `pic` varchar(64) DEFAULT NULL COMMENT '商品图片',
  8. `createtime` datetime NOT NULL COMMENT '生产日期',
  9. PRIMARY KEY (`id`)
  10. ) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=utf8;
  11. INSERT INTO `springmvc`.`items` (`id`, `name`, `price`, `detail`, `pic`, `createtime`) VALUES ('1', '台式机', '3000.0', '该电脑质量非常好!!!!', NULL, '2019-09-21 13:22:53');
  12. INSERT INTO `springmvc`.`items` (`id`, `name`, `price`, `detail`, `pic`, `createtime`) VALUES ('2', '笔记本', '6000.0', '笔记本性能好,质量好!!!!!', NULL, '2019-09-21 13:22:57');
  13. INSERT INTO `springmvc`.`items` (`id`, `name`, `price`, `detail`, `pic`, `createtime`) VALUES ('3', '背包', '200.0', '名牌背包,容量大质量好!!!!', NULL, '2019-09-21 13:23:02');

2.创建java web工程,此处以第一篇博文创建的demo项目为基准--基于idea创建的demo项目

3.导入需要用到的jar包,且加载依赖到项目中去

4.根据逆向工程,生成mapper文件和pojo类文件,或者手写,以及创建service相关类

下面是各个文件内容:

  1. 4.1 ItemsMapper.jav
  1. package cn.springmvc.mapper;
  2. import cn.springmvc.pojo.Items;
  3. import cn.springmvc.pojo.ItemsExample;
  4. import org.apache.ibatis.annotations.Param;
  5. import java.util.List;
  6. public interface ItemsMapper {
  7. int countByExample(ItemsExample example);
  8. int deleteByExample(ItemsExample example);
  9. int deleteByPrimaryKey(Integer id);
  10. int insert(Items record);
  11. int insertSelective(Items record);
  12. List<Items> selectByExampleWithBLOBs(ItemsExample example);
  13. List<Items> selectByExample(ItemsExample example);
  14. Items selectByPrimaryKey(Integer id);
  15. int updateByExampleSelective(@Param("record") Items record, @Param("example") ItemsExample example);
  16. int updateByExampleWithBLOBs(@Param("record") Items record, @Param("example") ItemsExample example);
  17. int updateByExample(@Param("record") Items record, @Param("example") ItemsExample example);
  18. int updateByPrimaryKeySelective(Items record);
  19. int updateByPrimaryKeyWithBLOBs(Items record);
  20. int updateByPrimaryKey(Items record);
  21. }
  1. 4.2 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="cn.springmvc.mapper.ItemsMapper" >
  4. <resultMap id="BaseResultMap" type="cn.springmvc.pojo.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="cn.springmvc.pojo.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="Base_Column_List" >
  44. id, name, price, pic, createtime
  45. </sql>
  46. <sql id="Blob_Column_List" >
  47. detail
  48. </sql>
  49. <select id="selectByExampleWithBLOBs" resultMap="ResultMapWithBLOBs" parameterType="cn.springmvc.pojo.ItemsExample" >
  50. select
  51. <if test="distinct" >
  52. distinct
  53. </if>
  54. <include refid="Base_Column_List" />
  55. ,
  56. <include refid="Blob_Column_List" />
  57. from items
  58. <if test="_parameter != null" >
  59. <include refid="Example_Where_Clause" />
  60. </if>
  61. <if test="orderByClause != null" >
  62. order by ${orderByClause}
  63. </if>
  64. </select>
  65. <select id="selectByExample" resultMap="BaseResultMap" parameterType="cn.springmvc.pojo.ItemsExample" >
  66. select
  67. <if test="distinct" >
  68. distinct
  69. </if>
  70. <include refid="Base_Column_List" />
  71. from items
  72. <if test="_parameter != null" >
  73. <include refid="Example_Where_Clause" />
  74. </if>
  75. <if test="orderByClause != null" >
  76. order by ${orderByClause}
  77. </if>
  78. </select>
  79. <select id="selectByPrimaryKey" resultMap="ResultMapWithBLOBs" parameterType="java.lang.Integer" >
  80. select
  81. <include refid="Base_Column_List" />
  82. ,
  83. <include refid="Blob_Column_List" />
  84. from items
  85. where id = #{id,jdbcType=INTEGER}
  86. </select>
  87. <select id="countByExample" parameterType="cn.springmvc.pojo.ItemsExample" resultType="java.lang.Integer" >
  88. select count(*) from items
  89. <if test="_parameter != null" >
  90. <include refid="Example_Where_Clause" />
  91. </if>
  92. </select>
  93. </mapper>
  1. 4.3 Items.java
  1. package cn.springmvc.pojo;
  2. import java.util.Date;
  3. public class Items {
  4. private Integer id;
  5. private String name;
  6. private Float price;
  7. private String pic;
  8. private Date createtime;
  9. private String detail;
  10. public Integer getId() {
  11. return id;
  12. }
  13. public void setId(Integer id) {
  14. this.id = id;
  15. }
  16. public String getName() {
  17. return name;
  18. }
  19. public void setName(String name) {
  20. this.name = name == null ? null : name.trim();
  21. }
  22. public Float getPrice() {
  23. return price;
  24. }
  25. public void setPrice(Float price) {
  26. this.price = price;
  27. }
  28. public String getPic() {
  29. return pic;
  30. }
  31. public void setPic(String pic) {
  32. this.pic = pic == null ? null : pic.trim();
  33. }
  34. public Date getCreatetime() {
  35. return createtime;
  36. }
  37. public void setCreatetime(Date createtime) {
  38. this.createtime = createtime;
  39. }
  40. public String getDetail() {
  41. return detail;
  42. }
  43. public void setDetail(String detail) {
  44. this.detail = detail == null ? null : detail.trim();
  45. }
  46. }
  1. 4.4 ItemsExample.java
  1. package cn.springmvc.pojo;
  2. import java.util.ArrayList;
  3. import java.util.Date;
  4. import java.util.List;
  5. public class ItemsExample {
  6. protected List<Criteria> oredCriteria;
  7. public ItemsExample() {
  8. oredCriteria = new ArrayList<Criteria>();
  9. }
  10. protected abstract static class GeneratedCriteria {
  11. protected List<Criterion> criteria;
  12. protected GeneratedCriteria() {
  13. super();
  14. criteria = new ArrayList<Criterion>();
  15. }
  16. }
  17. public static class Criteria extends GeneratedCriteria {
  18. protected Criteria() {
  19. super();
  20. }
  21. }
  22. public static class Criterion {
  23. private String condition;
  24. private Object value;
  25. private Object secondValue;
  26. private boolean noValue;
  27. private boolean singleValue;
  28. private boolean betweenValue;
  29. private boolean listValue;
  30. private String typeHandler;
  31. protected Criterion(String condition) {
  32. super();
  33. this.condition = condition;
  34. this.typeHandler = null;
  35. this.noValue = true;
  36. }
  37. protected Criterion(String condition, Object value, String typeHandler) {
  38. super();
  39. this.condition = condition;
  40. this.value = value;
  41. this.typeHandler = typeHandler;
  42. if (value instanceof List<?>) {
  43. this.listValue = true;
  44. } else {
  45. this.singleValue = true;
  46. }
  47. }
  48. }
  49. }
  1. 4.5 ItemService.java
  1. package cn.springmvc.service;
  2. import cn.springmvc.pojo.Items;
  3. import java.util.List;
  4. public interface ItemService {
  5. //查询商品列表
  6. public List<Items> selectItemsList();
  7. }
  1. 4.6  ItemServiceImpl
  1. package cn.springmvc.service;
  2. import cn.springmvc.mapper.ItemsMapper;
  3. import cn.springmvc.pojo.Items;
  4. import org.springframework.beans.factory.annotation.Autowired;
  5. import org.springframework.stereotype.Service;
  6. import java.util.List;
  7. /**
  8. * 查询商品信息
  9. * @author lx
  10. *
  11. */
  12. @Service
  13. public class ItemServiceImpl implements ItemService {
  14. @Autowired
  15. private ItemsMapper itemsMapper;
  16. //查询商品列表
  17. public List<Items> selectItemsList(){
  18. return itemsMapper.selectByExampleWithBLOBs(null);
  19. }
  20. }

5..创建相关配置文件

把创建的相关配置文件放到src目录下即可,如下图所示,记得把创建的applicationContext.xml文件给配置加载依赖到项目中去,具体加载方法请看上一篇博文。

4.1创建db.properties

  1. jdbc.driver=com.mysql.jdbc.Driver
  2. jdbc.url=jdbc:mysql://localhost:3306/springmvc?characterEncoding=utf-8
  3. jdbc.username=root
  4. jdbc.password=root

4.2 创建sqlMapConfig.xml

  1. <?xml version="1.0" encoding="UTF-8" ?>
  2. <!DOCTYPE configuration
  3. PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
  4. "http://mybatis.org/dtd/mybatis-3-config.dtd">
  5. <configuration>
  6. <!-- 设置别名 -->
  7. <typeAliases>
  8. <!-- 2. 指定扫描包,会把包内所有的类都设置别名,别名的名称就是类名,大小写不敏感 -->
  9. <package name="cn.springmvc.pojo" />
  10. </typeAliases>
  11. </configuration>

4.3 创建log4g.properties

  1. # Global logging configuration
  2. log4j.rootLogger=DEBUG, stdout
  3. # Console output...
  4. log4j.appender.stdout=org.apache.log4j.ConsoleAppender
  5. log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
  6. log4j.appender.stdout.layout.ConversionPattern=%5p [%t] - %m%n

4.4 创建applicationContexnt.xml

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <beans xmlns="http://www.springframework.org/schema/beans"
  3. xmlns:context="http://www.springframework.org/schema/context" xmlns:p="http://www.springframework.org/schema/p"
  4. xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"
  5. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  6. xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
  7. http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd
  8. 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
  9. http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-4.0.xsd">
  10. <context:property-placeholder location="classpath:db.properties"/>
  11. <!-- 数据库连接池 -->
  12. <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"
  13. destroy-method="close">
  14. <property name="driverClassName" value="${jdbc.driver}" />
  15. <property name="url" value="${jdbc.url}" />
  16. <property name="username" value="${jdbc.username}" />
  17. <property name="password" value="${jdbc.password}" />
  18. <property name="maxActive" value="10" />
  19. <property name="maxIdle" value="5" />
  20. </bean>
  21. <!-- Mybatis的工厂 -->
  22. <bean id="sqlSessionFactoryBean" class="org.mybatis.spring.SqlSessionFactoryBean">
  23. <property name="dataSource" ref="dataSource"/>
  24. <!-- 核心配置文件的位置 -->
  25. <property name="configLocation" value="classpath:sqlMapConfig.xml"/>
  26. </bean>
  27. <!-- Mapper动态代理开发 扫描 -->
  28. <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
  29. <!-- 基本包 -->
  30. <property name="basePackage" value="cn.springmvc.mapper"/>
  31. </bean>
  32. <!-- 注解事务 -->
  33. <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
  34. <property name="dataSource" ref="dataSource"/>
  35. </bean>
  36. <!-- 开启注解 -->
  37. <tx:annotation-driven transaction-manager="transactionManager"/>
  38. </beans>

4.5 配置修改web.xml,如下图所示

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="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" id="WebApp_ID" version="2.5">
  3. <display-name>springmvc-mybatis</display-name>
  4. <welcome-file-list>
  5. <welcome-file>index.html</welcome-file>
  6. <welcome-file>index.htm</welcome-file>
  7. <welcome-file>index.jsp</welcome-file>
  8. <welcome-file>default.html</welcome-file>
  9. <welcome-file>default.htm</welcome-file>
  10. <welcome-file>default.jsp</welcome-file>
  11. </welcome-file-list>
  12. <context-param>
  13. <param-name>contextConfigLocation</param-name>
  14. <param-value>classpath:applicationContext.xml</param-value>
  15. </context-param>
  16. <!-- Spring监听器 -->
  17. <listener>
  18. <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
  19. </listener>
  20. <!-- 处理POST提交乱码问题 -->
  21. <filter>
  22. <filter-name>encoding</filter-name>
  23. <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
  24. <init-param>
  25. <param-name>encoding</param-name>
  26. <param-value>UTF-8</param-value>
  27. </init-param>
  28. </filter>
  29. <filter-mapping>
  30. <filter-name>encoding</filter-name>
  31. <url-pattern>*.action</url-pattern>
  32. </filter-mapping>
  33. <!-- 前端控制器 -->
  34. <servlet>
  35. <servlet-name>springmvc</servlet-name>
  36. <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
  37. <!-- 默认找 /WEB-INF/[servlet的名称]-servlet.xml -->
  38. <init-param>
  39. <param-name>contextConfigLocation</param-name>
  40. <param-value>classpath:springmvc.xml</param-value>
  41. </init-param>
  42. </servlet>
  43. <servlet-mapping>
  44. <servlet-name>springmvc</servlet-name>
  45. <!--
  46. 1. /* 拦截所有 jsp js png .css 真的全拦截 建议不使用
  47. 2. *.action *.do 拦截以do action 结尾的请求 肯定能使用 ERP
  48. 3. / 拦截所有 (不包括jsp) (包含.js .png.css) 强烈建议使用 前台 面向消费者 www.jd.com/search /对静态资源放行
  49. -->
  50. <url-pattern>*.action</url-pattern>
  51. </servlet-mapping>
  52. </web-app>

6.创建jsp文件

创建itemList.jsp,放到WEB-INF/jsp目录下

  1. <%@ page language="java" contentType="text/html; charset=UTF-8"
  2. pageEncoding="UTF-8"%>
  3. <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
  4. <%@ taglib uri="http://java.sun.com/jsp/jstl/fmt" prefix="fmt"%>
  5. <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
  6. <html>
  7. <head>
  8. <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
  9. <title>查询商品列表</title>
  10. </head>
  11. <body>
  12. <form action="${pageContext.request.contextPath }/item/queryitem.action" method="post">
  13. 查询条件:
  14. <table width="100%" border=1>
  15. <tr>
  16. <td><input type="submit" value="查询"/></td>
  17. </tr>
  18. </table>
  19. 商品列表:
  20. <table width="100%" border=1>
  21. <tr>
  22. <td>商品名称</td>
  23. <td>商品价格</td>
  24. <td>生产日期</td>
  25. <td>商品描述</td>
  26. <td>操作</td>
  27. </tr>
  28. <c:forEach items="${itemList }" var="item">
  29. <tr>
  30. <td>${item.name }</td>
  31. <td>${item.price }</td>
  32. <td><fmt:formatDate value="${item.createtime}" pattern="yyyy-MM-dd HH:mm:ss"/></td>
  33. <td>${item.detail }</td>
  34. <td><a href="${pageContext.request.contextPath }/itemEdit.action?id=${item.id}">修改</a></td>
  35. </tr>
  36. </c:forEach>
  37. </table>
  38. </form>
  39. </body>
  40. </html>

7.启动tomcat,访问http://localhost:8080/springmvcdemo/samePage.action,如下图所示

Springmvc入门基础(三) ---与mybatis框架整合的更多相关文章

  1. SSM(Spring+SpringMVC+MyBatis)框架整合开发流程

    回忆了 Spring.SpringMVC.MyBatis 框架整合,完善一个小demo,包括基本的增删改查功能. 开发环境 IDEA MySQL 5.7 Tomcat 9 Maven 3.2.5 需要 ...

  2. SSM(Spring,SpringMVC,Mybatis)框架整合项目

    快速上手SSM(Spring,SpringMVC,Mybatis)框架整合项目 环境要求: IDEA MySQL 8.0.25 Tomcat 9 Maven 3.6 数据库环境: 创建一个存放书籍数据 ...

  3. mybatis框架整合及逆向工程

    mybatis框架整合及逆向工程 一.三大框架整合 ​ 整合SSM框架 1.导入pom文件 1.导入spring的pom依赖 <?xml version="1.0" enco ...

  4. struts2 + spring + mybatis 框架整合详细介绍

    struts2 + spring + mybatis  框架整合详细介绍 参考地址: https://blog.csdn.net/qq_22028771/article/details/5149898 ...

  5. SSM Spring SpringMVC Mybatis框架整合Java配置完整版

    以前用着SSH都是老师给配好的,自己直接改就可以.但是公司主流还是SSM,就自己研究了一下Java版本的配置.网上大多是基于xnl的配置,但是越往后越新的项目都开始基于JavaConfig配置了,这也 ...

  6. SSM框架-----------SpringMVC+Spring+Mybatis框架整合详细教程

    1.基本概念 1.1.Spring Spring是一个开源框架,Spring是于2003 年兴起的一个轻量级的Java 开发框架,由Rod Johnson 在其著作Expert One-On-One  ...

  7. mybatis入门基础(三)----SqlMapConfig.xml全局配置文件解析

    一:SqlMapConfig.xml配置文件的内容和配置顺序如下 properties(属性) settings(全局配置参数) typeAiases(类型别名) typeHandlers(类型处理器 ...

  8. ssm(spring、springmvc、mybatis)框架整合

    第一次接触这3大框架,打算一个一个慢慢学,参照网上资料搭建了一个ssm项目,作为新手吃亏在jar包的导入上,比如jdbc DataSource配置的时候由于导入的jar包不兼容或者缺包导致项目无法正常 ...

  9. SpringMVC Spring MyBatis 框架整合 Annotation MavenProject

    项目结构目录 pom.xml   jar包管理 <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi=&q ...

随机推荐

  1. [Java]Java入门笔记(三):类、对象和方法

    七.类.对象和方法 类和对象的关系 类定义了对象的本质: 类(class)是对象(object)的模板,而对象(object)是类的一个实例(instance). 使多个对象的指向相同: Studen ...

  2. 神奇!这款 Vue 后台框架居然不用手动配置路由

    前言 做 Vue 开发脱离不了路由,尤其是中大型项目,页面多且杂,在配置路由的时候总是会变得逐渐暴躁,因为费时,并且又没有什么太多技术含量,总觉得是在浪费时间. 另外如果接手了别人的项目,当业务有变更 ...

  3. 在 WPF 客户端实现 AOP 和接口缓存

    随着业务越来越复杂,最近决定把一些频繁查询但是数据不会怎么变更的接口做一下缓存,这种功能一般用 AOP 就能实现了,找了一下客户端又没现成的直接可以用,嗐,就只能自己开发了. 代理模式和AOP 理解代 ...

  4. 把SQLAlchemy查询对象转换成字典

    1-假设查出来的为单个对象 1-1 在model.py中为模型对象添加字典转换函数: from exts import db class User(db.Model): __tablename__ = ...

  5. OLAP阵营又增一猛将,比肩Power BI不是说说而已!

    说到大数据应用最多的技术,不得不提OLAP技术,在国内外,不论传统公司还是互联网公司,都开始利用OLAP技术分析挖掘大数据的价值.也许很多人对OLAP的概念还不是很清楚,简单来说,就把数据处理成数据立 ...

  6. Android编译优化系列-kapt篇

    作者:字节跳动终端技术---王龙海 封光 兰军健 一.背景 本文是编译优化系列文章之 kapt 优化篇,后续还会有 build cache, kotlin, dex 优化等文章,敬请期待.本文由Cli ...

  7. UnicodeDecodeError

    'gbk' codec can't decode byte 0x80 in position xx open文件时,添加参数'encoding='utf-8' 'utf-8' codec can't ...

  8. boostrap的select2自动换行的问题解决

    最近在使用boostrap的select2控件实现多选效果时发现一个问题正常效果:但是当选择了两个长一些的option时,发现select2莫名其妙的换了一行空白行:经过F12调试发现是因为selec ...

  9. .NET的两种部署模式,了解一下

    前言 以往部署程序一直是习惯性先安装运行时环境,然后再将发布打包好的程序运行起来:但当多个程序依赖不同版本框架平台时,如果部署在同一台机器上,那就需要在同一台机器上安装多个版本的运行时,总感觉有点不太 ...

  10. 震撼的Linux全景图:业界成熟的内核架构长什么样?

    1)Linux怎么来的? Linus 为了方便访问大学服务器中的资源 ,在自己的机器上写了一个文件系统和硬盘驱动,这样就可以把自己需要的资源下载到自己的机器中.随后linus把这款操作系统雏形开源,成 ...