原创

Spring + Spring MVC + MyBatis(SSM)

1、搭建 Spring + Spring MVCMyBatis(SSM)工程

1.1 表结构设计

1.2 项目搭建

1.2.1 引入MyBatis相关jar包

1.2.2 引入Spring相关jar包

1.2.3 配置工作

web.xml文件配置

	<!-- SpringMVC核心控制器 -->
	<servlet>
		<servlet-name>DispatcherServlet</servlet-name>
		<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
		<init-param>
			<param-name>contextConfigLocation</param-name>
			<!-- 加载SpringMVC的配置文件,分开配置时叫spring-mvc.xml文件,同时 也可以在applicationContext.xml文件中配置MVC的内容 -->
			<param-value>classpath:applicationContext.xml</param-value>
		</init-param>
	</servlet>
	<!-- SpringMVC核心控制器的URL -->
	<servlet-mapping>
		<servlet-name>DispatcherServlet</servlet-name>
		<!-- 如果所有请求都要被SpringMVC接收时直接使用"/" -->
		<url-pattern>*.xhtml</url-pattern>
	</servlet-mapping>

applicationContext.xml文件配置

① 命名空间选择

② Spring自己的基本配置

<!-- 注册Spring注解的处理类 -->
<context:annotation-config />
<!-- 设置Spring注解扫描路径 -->
<context:component-scan base-package="com.zpark.tea_mgr.service,
 com.zpark.tea_mgr.controller" />

③ Spring MVC相关的配置

<!-- SpringMVC开始 -->
<!-- SpringMVC的注册处理器 -->
<mvc:annotation-driven />
<!-- SpringMVC的视图处理器 -->
<bean id="internalResourceViewResolver"
	class="org.springframework.web.servlet.view.InternalResourceViewResolver">
	<property name="prefix" value="/" />		<!-- 前缀 -->
	<property name="suffix" value=".jsp" />		<!-- 后缀 -->
</bean>
<!-- SpringMVC完成 -->

④ Spring整合MaBatis的配置

首先在src源目录下要有这两个文件

整合部分的配置代码

<!-- 整合MyBatis开始 -->
	<!-- 引入jdbc配置文件 -->
	<context:property-placeholder location="classpath:jdbc.properties" />
	<!-- 创建jdbc数据源 -->
	<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource">
		<property name="driverClassName" value="${db.driverClassName}" />
		<property name="url" value="${db.url}" />
		<property name="username" value="${db.username}" />
		<property name="password" value="${db.password}" />
	</bean>
	<!-- 配置MyBatis的sqlSession -->
	<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
		<property name="configLocation" value="classpath:mybatis.xml" />
		<property name="dataSource" ref="dataSource" />
	</bean>

	<!-- 映射Mapper目录 -->
	<!-- Mapper接口的所在包名,Spring会自动查找其下的Mapper -->
	<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
		<property name="basePackage" value="com.zpark.tea_mgr.mapper" />
	</bean>

	<!-- 可通过注解控制事务 -->
	<tx:annotation-driven transaction-manager="transactionManager" />
	<bean id="transactionManager"
		class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
		<property name="dataSource" ref="dataSource" />
	</bean>
	<!-- 整合MyBatis完成 -->

1.3 编写实体类

Goods
public class Goods {
//	goods_id	int
	private Integer goodsId;
//	goods_name	varchar
	private String goodsName;
//	goods_price	double
	private Double goodsPrice;
//	goods_num	int
	private Integer goodsNum;
//	goods_type	int
	private GoodsType goodsType;
//  一个商品可能有若干条入库记录
	private List<GoodsStockIn> goodsStockInList;
	}
GoodsStockIn
public class GoodsStockIn {
//	stock_in_id	int
	private Integer stockInId;
//	stock_in_goods	int
	private Goods stockInGoods;
//	stock_in_price	double
	private Double stockInPrice;
//	stock_in_num	int
	private Integer stockInNum;
//	stock_in_time	timestamp
	private Timestamp stockInTime;
	}
GoodsType
public class GoodsType {
//	typeId	int
	private Integer typeId;
//	typeName	varchar
	private String typeName;
//  一个商品类型下面会有若干商品信息
	private List<Goods> goodsList;
}

1.4 编写Mapper接口

@Repository("GoodsMapper")
public interface GoodsMapper {
	public List<Goods> findAll();
	public Goods findById(int goodsId);
}
@Repository("GoodsStockInMapper")
public interface GoodsStockInMapper {
	public List<GoodsStockIn> findByGoods(int goodsId);
}
@Repository("GoodsTypeMapper")
public interface GoodsTypeMapper {
}

1.5 编写Mapper.xml文件

GoodsMapper.xml
<mapper namespace="com.zpark.tea_mgr.mapper.GoodsMapper">
	
	<select id="findAll" resultMap="BaseResultMap">
		select * from goods
		left join goods_type
		on goods_type.typeId = goods.goods_type
	</select>
	
	<select id="findById" parameterType="int" resultMap="BaseResultMap">
		select * from goods
		left join goods_type
		on goods_type.typeId = goods.goods_type
		where goods_id = #{id}
	</select>
	
	<resultMap type="com.zpark.tea_mgr.domain.Goods" id="BaseResultMap">
		<id column="goods_id" property="goodsId" jdbcType="INTEGER" />
		<result column="goods_name" property="goodsName" jdbcType="VARCHAR" />
		<result column="goods_price" property="goodsPrice" jdbcType="DOUBLE" />
		<result column="goods_num" property="goodsNum" jdbcType="INTEGER" />
		<association property="goodsType" javaType="com.zpark.tea_mgr.domain.GoodsType"
			resultMap="com.zpark.tea_mgr.mapper.GoodsTypeMapper.BaseResultMap" />
	</resultMap> 
	
</mapper>
GoodsTypeMapper.xml
<mapper namespace="com.zpark.tea_mgr.mapper.GoodsTypeMapper">
	<resultMap id="BaseResultMap" 
type="com.zpark.tea_mgr.domain.GoodsType">
	  <id column="typeId" property="typeId" jdbcType="INTEGER" />
	  <result column="typeName" property="typeName" jdbcType="VARCHAR" />
	</resultMap>
</mapper>
GoodsStockInMapper.xml
<mapper namespace="com.zpark.tea_mgr.mapper.GoodsStockInMapper">
	<select id="findByGoods" parameterType="int" resultMap="BaseResultMap">
		select * from goods_stock_in
		where stock_in_goods = #{id}
	</select>
	<resultMap id="BaseResultMap"
 type="com.zpark.tea_mgr.domain.GoodsStockIn">
		<id column="stock_in_id" property="stockInId" jdbcType="INTEGER" />
		<result column="stock_in_goods" property="stockInGoods.goodsId" jdbcType="INTEGER" />
		<result column="stock_in_price" property="stockInPrice" jdbcType="DOUBLE" />
		<result column="stock_in_num" property="stockInNum" jdbcType="INTEGER" />
		<result column="stock_in_time" property="stockInTime" jdbcType="TIMESTAMP" />
	</resultMap>
</mapper>

1.6 编写业务类

@Service("GoodsService")
public class GoodsService {

	@Resource
	private GoodsMapper goodsMapper;
	@Resource
	private GoodsStockInMapper goodsStockInMapper;
	
	@Transactional(propagation=Propagation.REQUIRED, readOnly=true)
	public List<Goods> findAll(){
		try {
			return this.goodsMapper.findAll();
		} catch (Exception e) {
			e.printStackTrace();
			throw new RuntimeException(e);
		}
	}
	
	@Transactional(propagation=Propagation.REQUIRED, readOnly=true)
	public Goods findById(int goodsId){
		Goods goods = null;
		try {
			goods = this.goodsMapper.findById(goodsId);
			List<GoodsStockIn> goodsStockInList = this.goodsStockInMapper.findByGoods(goodsId);
			goods.setGoodsStockInList(goodsStockInList);
			return goods;
		} catch (Exception e) {
			e.printStackTrace();
			throw new RuntimeException(e);
		}
	}
	
}

1.7 编写Controller

@Controller("GoodsController")
@RequestMapping("/goods")
public class GoodsController {
	@Resource
	private GoodsService goodsService;
	@RequestMapping("showList")
	public String showList(Model model){
		List<Goods> goodsList = this.goodsService.findAll();
		model.addAttribute("goodsList", goodsList);
		return "showList";
	}
	@RequestMapping("showGoods")
	public String showGoods(int goodsId, Model model){
		Goods goods = this.goodsService.findById(goodsId);
		model.addAttribute("goods", goods);
		return "showGoods";
	}
}

1.8 编写Jsp页面

查所有商品: showList.jsp

<!-- 首先使用taglib指令,引入jstl标签库 -->
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<body>
    <table border="1" cellspacing="0" cellpadding="0">
      <tr>
      	<th>序号</th>
      	<th>商品名称</th>
      	<th>类型名称</th>
      	<th>商品数量</th>
      	<th>商品价格</th>
      	<th>入库说明</th>
      </tr>
      <c:forEach items="${requestScope.goodsList }" var="goods" varStatus="statu">
      	<tr>
      	  <td>${statu.count }</td>
      	  <td>${goods.goodsName }</td>
      	  <td>${goods.goodsType.typeName }</td>
      	  <td>${goods.goodsPrice }</td>
      	  <td>${goods.goodsNum }</td>
      	  <td>
      	  	<a href="${pageContext.request.contextPath }/goods/showGoods.xhtml?goodsId=${goods.goodsId}">入库</a>
      	  </td>
      	</tr>
      </c:forEach>
    </table>
  </body>

查单个商品:showGoods.jsp


<body>
    商品Id:${requestScope.goods.goodsId }<br>
    商品名称:${requestScope.goods.goodsName }<br>
    类型名称:${requestScope.goods.goodsType.typeName }<br>
    商品价格:${requestScope.goods.goodsPrice }<br>
    商品数量:${requestScope.goods.goodsNum }<hr>
    <c:choose>
    	<c:when test="${not empty requestScope.goods.goodsStockInList }">
		    <c:forEach items="${requestScope.goods.goodsStockInList }" var="stockIn" varStatus="statu">
		    	${statu.count } -- ${stockIn.stockInPrice } -- ${stockIn.stockInNum } -- ${stockIn.stockInTime }<br>
		    </c:forEach>
    	</c:when>
    	<c:otherwise>
    		暂时没有查到入库记录!
    	</c:otherwise>
    </c:choose>
  </body>

2、添加商品入库记录

2.1 编写Mapper接口的方法

2.1.1 编写GoodsStockInMapper接口的保存方法
public void save(GoodsStockIn goodsStockIn);
2.1.2 编写GoodsMapper接口的修改库存的方法
public void update(@Param("goodsId") int goodsId, @Param("upNum") int upNum);

2.2 编写Mapper.xml文件

<update id="update">
	update goods 
	set goods_num = goods_num + #{upNum}
	where goods_id = #{goodsId}
</update>
<insert id="save" parameterType="com.zpark.tea_mgr.domain.GoodsStockIn">
	insert into goods_stock_in (stock_in_price, stock_in_num, stock_in_goods)
	values (#{stockInPrice}, #{stockInNum}, #{stockInGoods.goodsId})
</insert>

2.3 编写Service

@Service("GoodsStockInService")
public class GoodsStockInService {
	@Resource
	private GoodsStockInMapper goodsStockInMapper;
	@Resource
	private GoodsMapper goodsMapper;
	
	@Transactional(propagation=Propagation.REQUIRED, rollbackFor={Exception.class})
	public void save(GoodsStockIn goodsStockIn){
		try {
			this.goodsStockInMapper.save(goodsStockIn);
			int goodsId = goodsStockIn.getStockInGoods().getGoodsId();
			int upNum = goodsStockIn.getStockInNum();
			this.goodsMapper.update(goodsId, upNum);
		} catch (Exception e) {
			e.printStackTrace();
			throw new RuntimeException(e);
		}
	}
	
}
2.4 编写Controller
@Controller("GoodsStockInController")
@RequestMapping("/stockIn")
public class GoodsStockInController {
	@Resource
	private GoodsStockInService goodsStockInService;
	
	@RequestMapping("save")
	public String save(GoodsStockIn goodsStockIn, Model model){
		try {
			this.goodsStockInService.save(goodsStockIn);
			int goodsId = goodsStockIn.getStockInGoods().getGoodsId();
			model.addAttribute("goodsId", goodsId);
			return "redirect:/goods/showGoods.xhtml";
		} catch (Exception e) {
			e.printStackTrace();
			return "自己写";
		}
	}
}

2.5 编写JSP

<form action="${pageContext.request.contextPath }/stockIn/save.xhtml"
 method="post">
    	入库数量:<input name="stockInNum" /><br>
    	入库价格:<input name="stockInPrice" /><br>
    	<input type="hidden" name="stockInGoods.goodsId" value="${requestScope.goods.goodsId }" />
    	<input type="submit" value="入库" >
    </form>
  • 作者:管理员(联系作者)
  • 发表时间:2020-04-22 04:43
  • 版权声明:自由转载-非商用-非衍生-保持署名
  • 公众号转载:请在文末添加作者公众号二维码
  • 评论

    ゞ 正在缓冲99% QQ
    6666666666
    AIMER 游客
    踩一踩
    你的 游客
    太6666