日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 前端技术 > javascript >内容正文

javascript

实战_02_Spring SpringMVC 整合Mybaits

發布時間:2024/9/27 javascript 28 豆豆
生活随笔 收集整理的這篇文章主要介紹了 实战_02_Spring SpringMVC 整合Mybaits 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

接上一篇:企業實戰_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的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。