接上一篇:企业实战_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