接上一篇:企业实战_01_Spring SpringMVC 整合Mybaits
https://blog.csdn.net/weixin_40816738/article/details/101343414

文章目录

  • 一、数据库操作
    • 1.1. 创建数据库
    • 1.2. 表结构
  • 二、整合实战
    • 2.1. 整合思路
      • 2.1.1. Dao层
      • 2.1.2. service层
      • 2.1.3. Dao层表现层
    • 2.2. Dao整合
      • 2.2.1. 创建SqlMapConfig.xml配置文件
      • 2.2.2. Spring整合mybatis
    • 2.3. Service整合
    • 2.4. 事务管理
    • 2.5. 表现层整合
    • 2.6. Web.xml

一、数据库操作

1.1. 创建数据库

  • Navicat Premium 12 创建数据库——方案1

  • 命令版本——方案2
  • 命令简单的演示了创建数据库的过程,数据名为 ly:
[root@host]# mysql -u root -p
Enter password:******  # 登录后进入终端mysql> create DATABASE ly;
  • IntelliJ IDEA 2019.1 创建数据库

1.2. 表结构

#使用ly数据库
use ly;
#删除已经存在的tb_item表
DROP TABLE IF EXISTS `tb_item`;
#创建tb_item表
CREATE TABLE `tb_item` (`id` bigint(20) NOT NULL COMMENT '商品id,同时也是商品编号',`title` varchar(100) NOT NULL COMMENT '商品标题',`sell_point` varchar(500) DEFAULT NULL COMMENT '商品卖点',`price` bigint(20) NOT NULL COMMENT '商品价格,单位为:分',`num` int(10) NOT NULL COMMENT '库存数量',`barcode` varchar(30) DEFAULT NULL COMMENT '商品条形码',`image` varchar(500) DEFAULT NULL COMMENT '商品图片',`cid` bigint(10) NOT NULL COMMENT '所属类目,叶子类目',`status` tinyint(4) NOT NULL DEFAULT '1' COMMENT '商品状态,1-正常,2-下架,3-删除',`created` datetime NOT NULL COMMENT '创建时间',`updated` datetime NOT NULL COMMENT '更新时间',PRIMARY KEY (`id`),KEY `cid` (`cid`),KEY `status` (`status`),KEY `updated` (`updated`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='商品表';

二、整合实战

2.1. 整合思路

2.1.1. Dao层

Mybatis的配置文件:SqlMapConfig.xml
不需要配置任何内容,需要有文件头。文件必须存在。
applicationContext-dao.xml:
mybatis整合spring,通过由spring创建数据库连接池,spring管理SqlSessionFactory、mapper代理对象。
需要mybatis和spring的整合包。

2.1.2. service层

applicationContext-service.xml:
所有的service实现类都放到spring容器中管理。并由spring管理事务

2.1.3. Dao层表现层

Springmvc框架,由springmvc管理controller。
Springmvc的三大组件

2.2. Dao整合

2.2.1. 创建SqlMapConfig.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></configuration>

2.2.2. Spring整合mybatis

创建applicationContext-dao.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:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"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-4.2.xsdhttp://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.2.xsdhttp://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.2.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.2.xsdhttp://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-4.2.xsd"><!-- 数据库连接池 --><!-- 加载配置文件 --><context:property-placeholder location="classpath:conf/db.properties"/><!-- 数据库连接池 --><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><!-- 让spring管理sqlsessionfactory 使用mybatis和spring整合包中的 --><bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"><!-- 数据库连接池 --><property name="dataSource" ref="dataSource"/><!-- 加载mybatis的全局配置文件 --><property name="configLocation" value="classpath:mybatis/SqlMapConfig.xml"/></bean><bean class="org.mybatis.spring.mapper.MapperScannerConfigurer"><property name="basePackage" value="com.gblfy.mapper"/></bean>
</beans>

db.properties

jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/ly?characterEncoding=utf-8
jdbc.username=root
jdbc.password=root

2.3. Service整合

applicationContext-service.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:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"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-4.2.xsdhttp://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.2.xsdhttp://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.2.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.2.xsdhttp://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-4.2.xsd"><context:component-scan base-package="com.gblfy.service"/>
</beans>

2.4. 事务管理

创建applicationContext-trans.xml

<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:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"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-4.2.xsdhttp://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.2.xsdhttp://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.2.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.2.xsdhttp://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-4.2.xsd"><!-- 事务管理器 --><bean id="transactionManager"class="org.springframework.jdbc.datasource.DataSourceTransactionManager"><!-- 数据源 --><property name="dataSource" ref="dataSource"/></bean><!-- 通知 --><tx:advice id="txAdvice" transaction-manager="transactionManager"><tx:attributes><!-- 传播行为 --><tx:method name="save*" propagation="REQUIRED"/><tx:method name="insert*" propagation="REQUIRED"/><tx:method name="add*" propagation="REQUIRED"/><tx:method name="create*" propagation="REQUIRED"/><tx:method name="delete*" propagation="REQUIRED"/><tx:method name="update*" propagation="REQUIRED"/><tx:method name="find*" propagation="SUPPORTS" read-only="true"/><tx:method name="select*" propagation="SUPPORTS" read-only="true"/><tx:method name="get*" propagation="SUPPORTS" read-only="true"/></tx:attributes></tx:advice><!-- 切面 --><aop:config><aop:advisor advice-ref="txAdvice"pointcut="execution(* com.gblfy.service.*.*(..))"/></aop:config>
</beans>

2.5. 表现层整合

springmvc.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:p="http://www.springframework.org/schema/p"xmlns:context="http://www.springframework.org/schema/context"xmlns:mvc="http://www.springframework.org/schema/mvc"xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.2.xsdhttp://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.2.xsdhttp://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.2.xsd"><context:component-scan base-package="com.gblfy.controller" /><mvc:annotation-driven /><beanclass="org.springframework.web.servlet.view.InternalResourceViewResolver"><property name="prefix" value="/WEB-INF/jsp/" /><property name="suffix" value=".jsp" /></bean>
</beans>

2.6. Web.xml

<?xml version="1.0" encoding="UTF-8"?>
<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/javaeehttp://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"id="WebApp_ID" version="2.5"><!--web项目名称--><display-name>ly-web</display-name><!--欢迎页面--><welcome-file-list><welcome-file>index.jsp</welcome-file></welcome-file-list><!-- 加载spring容器 --><context-param><param-name>contextConfigLocation</param-name><param-value>classpath:spring/applicationContext-*.xml</param-value></context-param><listener><listener-class>org.springframework.web.context.ContextLoaderListener</listener-class></listener><!-- 解决post乱码 --><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><!-- springmvc的前端控制器 --><servlet><servlet-name>ly-manager</servlet-name><servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class><!-- contextConfigLocation不是必须的, 如果不配置contextConfigLocation, springmvc的配置文件默认在:WEB-INF/servlet的name+"-servlet.xml" --><init-param><param-name>contextConfigLocation</param-name><param-value>classpath:spring/springmvc.xml</param-value></init-param><load-on-startup>1</load-on-startup></servlet><servlet-mapping><servlet-name>ly-manager</servlet-name><url-pattern>/</url-pattern></servlet-mapping></web-app>

需求:
根据商品id查询商品信息,返回json数据。

entity

package com.gblfy.entity;import java.util.Date;public class TbItem {private Long id;private String title;private String sellPoint;private Long price;private Integer num;private String barcode;private String image;private Long cid;private Byte status;private Date created;private Date updated;public Long getId() {return id;}public void setId(Long id) {this.id = id;}public String getTitle() {return title;}public void setTitle(String title) {this.title = title == null ? null : title.trim();}public String getSellPoint() {return sellPoint;}public void setSellPoint(String sellPoint) {this.sellPoint = sellPoint == null ? null : sellPoint.trim();}public Long getPrice() {return price;}public void setPrice(Long price) {this.price = price;}public Integer getNum() {return num;}public void setNum(Integer num) {this.num = num;}public String getBarcode() {return barcode;}public void setBarcode(String barcode) {this.barcode = barcode == null ? null : barcode.trim();}public String getImage() {return image;}public void setImage(String image) {this.image = image == null ? null : image.trim();}public Long getCid() {return cid;}public void setCid(Long cid) {this.cid = cid;}public Byte getStatus() {return status;}public void setStatus(Byte status) {this.status = status;}public Date getCreated() {return created;}public void setCreated(Date created) {this.created = created;}public Date getUpdated() {return updated;}public void setUpdated(Date updated) {this.updated = updated;}
}

创建接口:
TbItemMapper

package com.gblfy.mapper;import com.gblfy.entity.TbItem;
import com.gblfy.entity.TbItemExample;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;import java.util.List;public interface TbItemMapper {/*注解形式*/@Select("SELECT * FROM tb_item")List<TbItem> getList();/*xml形式*/int countByExample(TbItemExample example);int deleteByExample(TbItemExample example);int deleteByPrimaryKey(Long id);int insert(TbItem record);int insertSelective(TbItem record);List<TbItem> selectByExample(TbItemExample example);TbItem selectByPrimaryKey(Long id);int updateByExampleSelective(@Param("record") TbItem record, @Param("example") TbItemExample example);int updateByExample(@Param("record") TbItem record, @Param("example") TbItemExample example);int updateByPrimaryKeySelective(TbItem record);int updateByPrimaryKey(TbItem record);
}

TbItemMapper.xml

略(源码有)
服务接口

package com.gblfy.service;import com.gblfy.entity.TbItem;
import java.util.List;public interface ItemService {TbItem getItemById(long itemId);List<TbItem> getItemlist();
}

impl

package com.gblfy.service;import com.gblfy.entity.TbItem;
import com.gblfy.mapper.TbItemMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;import java.util.List;/*** @author gblfy* @ClassNme ItemServiceImpl* @Description TODO* @Date 2019/9/25 13:00* @version1.0*/
@Service
public class ItemServiceImpl implements ItemService {@Autowiredprivate TbItemMapper itemMapper;@Overridepublic TbItem getItemById(long id) {TbItem item = itemMapper.selectByPrimaryKey(id);return item;}@Overridepublic List<TbItem> getItemlist() {List<TbItem> list = itemMapper.getList();return list;}}

controller

package com.gblfy.controller;import com.gblfy.entity.TbItem;
import com.gblfy.service.ItemService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;import java.util.List;/*** @author gblfy* @ClassNme ItemController* @Description TODO* @Date 2019/9/25 12:59* @version1.0*/
@RestController
public class ItemController {@Autowiredprivate ItemService itemService;/*** 通过id获取商品信息* 测试链接:http://localhost:8080/item/1** @param itemId* @return*/@RequestMapping("/item/{itemId}")private TbItem getItemById(@PathVariable Long itemId) {TbItem tbItem = itemService.getItemById(itemId);return tbItem;}@RequestMapping("/item/list")private List<TbItem> getItemList() {List<TbItem> itemlist = itemService.getItemlist();return itemlist;}
}

Gitlab源码:
https://gitlab.com/gb-heima/ly-parent

实战_02_Spring SpringMVC 整合Mybaits相关推荐

  1. 实战_01_Spring SpringMVC 整合Mybaits

    文章目录 一.技术选型 1.1. maven坐标说明 1.2. 环境准备 二.工程所属关系 2.1. 项目结构总览 2.2. 工程所属关系总览 三.创建聚合工程 3.1. 聚合工程_ly-parent ...

  2. 【速学java】 java后台框架 springmvc整合mybatis框架源码

    三大数据库 mysql  oracle  sqlsever   更专业.更强悍.适合不同用户群体 [新录针对本系统的视频教程,手把手教开发一个模块,快速掌握本系统] A 调用摄像头拍照,自定义裁剪编辑 ...

  3. springmvc整合mybatis框架源码 bootstrap html5 mysql oracle

    获取[下载地址]   QQ 313596790 三大数据库 mysql  oracle  sqlsever   更专业.更强悍.适合不同用户群体 [新录针对本系统的视频教程,手把手教开发一个模块,快速 ...

  4. SpringMVC整合fastdfs-client-java实现web文件上传下载

    为什么80%的码农都做不了架构师?>>>    版权声明:本文为博主原创文章,转载请标明出处(http://blog.csdn.net/wlwlwlwl015)Thanks. 目录( ...

  5. springmvc整合redis架构搭建实例

    新换环境,又有新东西可以学习了,哈皮! 抽空学习之余看了一下redis,个人对Springmvc的爱是忠贞不渝,所以整理了一下Springmvc整合redis的环境搭建.分享学习. 第一步 : 创建  ...

  6. 六:Dubbo与Zookeeper、SpringMvc整合和使用

    DUBBO与ZOOKEEPER.SPRINGMVC整合和使用 互联网的发展,网站应用的规模不断扩大,常规的垂直应用架构已无法应对,分布式服务架构以及流动计算架构势在必行,Dubbo是一个分布式服务框架 ...

  7. 【转】Dubbo_与Zookeeper、SpringMVC整合和使用(负载均衡、容错)

    原文链接:http://blog.csdn.net/congcong68/article/details/41113239 互联网的发展,网站应用的规模不断扩大,常规的垂直应用架构已无法应对,分布式服 ...

  8. Dubbo与Zookeeper、SpringMVC整合和使用(负载均衡、容错)(转)

    互联网的发展,网站应用的规模不断扩大,常规的垂直应用架构已无法应对,分布式服务架构以及流动计算架构势在必行,Dubbo是一个分布式服务框架,在这种情况下诞生的.现在核心业务抽取出来,作为独立的服务,使 ...

  9. SpringMVC整合MongoDB

    首先,在pom文件中新增spring-data-mongodb的依赖: <dependency> <groupId>org.springframework.data</g ...

最新文章

  1. 常用构建数据科学应用程序的七个Python库
  2. 【计算机网络】深入浅出网络层(看不懂你来打我.上)
  3. 结对项目之需求分析与原型模型设计
  4. 利用JS提交表单的几种方法和验证
  5. 如何读取超大文本文件
  6. Markdown设置字体大小、颜色...,CSDN博客编写设置字体大小、颜色、粗细。字体,文字背景设置。
  7. mysql的datetime使用_datetime数据类型 MySQL数据库使用教程
  8. 堆初始化-二叉堆一般用数组来表示。例如,根节点在数组中的位置是0,第n个位置的子节点分别在2n+1和 2n+2-icoding-void init_min_heap(PMinHeap pq, int
  9. c语言几千行代码图片,【图片】发几个C语言课程设计源代码(恭喜自己当上技术小吧主)【东华理工大学吧】_百度贴吧...
  10. 【Oracle】表级别分区操作对索引(本地分区索引,全局分区索引,非分区索引)的影响
  11. 《必玩》!学习大师们的游戏设计经验,激发你的游戏创造力!
  12. 一款好看透明个人主页源码
  13. python no such file or directory_python No such file or Directory
  14. 为什么网站打得开,却ping不通, 网站却打得开
  15. UCB CS285课程笔记目录
  16. 菜鸟的草缸 篇四:菜鸟的草缸:二氧化碳CO2
  17. C++错误 C1189
  18. (windows)Hexo博客建站$ npm install -g hexo-cli时遇到npm ERR! Response timeout……的解决方案
  19. 【Hexo】Hexo搭建Butterfly主题并快速美化
  20. 老照片修复怎么修?这三个方法可以让你实现修复操作

热门文章

  1. 想学好数学,请收好这份宝典!
  2. 本地缓存之Guava简单使用
  3. C语言fread函数了解
  4. Debug和Realease版本的区别
  5. 阿里云李飞飞:什么是云原生数据库
  6. 阿里云发布OAMKubernetes标准实现与核心依赖库
  7. 大家都关注的Serverless,阿里怎么做的?
  8. 码上用它开始Flutter混合开发——FlutterBoost
  9. 阿里云云效如何保障双11大型项目管理
  10. 探索交通治理新思路,广州黄埔智能交通治“堵”