MyBatis的一个小程序(购物系统)

来源:互联网 发布:如何在mac上玩dota2 编辑:程序博客网 时间:2024/05/17 22:17

MyBatis的一个小程序(购物系统)

mybatisConfig.xml

<?xml version="1.0" encoding="utf-8"?><!DOCTYPE configuration  PUBLIC "-//mybatis.org//DTD Config 3.0//EN"  "http://mybatis.org/dtd/mybatis-3-config.dtd"><configuration><plugins><!-- 配置分pageHrlper分页插件 --><plugin interceptor="com.github.pagehelper.PageHelper"><!-- 设置数据库方言 --><property name="dialect" value="mysql"/></plugin></plugins></configuration>

beans.xml

<?xml version="1.0" encoding="UTF-8"?><beans xmlns="http://www.springframework.org/schema/beans"xmlns:aop="http://www.springframework.org/schema/aop"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xmlns:context="http://www.springframework.org/schema/context"xmlns:tx="http://www.springframework.org/schema/tx"xmlns:mvc="http://www.springframework.org/schema/mvc"xsi:schemaLocation="http://www.springframework.org/schema/contexthttp://www.springframework.org/schema/context/spring-context-4.3.xsdhttp://www.springframework.org/schema/beans                http://www.springframework.org/schema/beans/spring-beans-4.3.xsd                http://www.springframework.org/schema/tx                 http://www.springframework.org/schema/tx/spring-tx-4.3.xsd                http://www.springframework.org/schema/aop                http://www.springframework.org/schema/aop/spring-aop-4.3.xsd                http://www.springframework.org/schema/mvc                http://www.springframework.org/schema/mvc/spring-mvc-4.3.xsd">         <!-- 数据库连接池 -->       <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource" destroy-method="close"><property name="user" value="root"/><property name="password" value="root"/><property name="jdbcUrl" value="jdbc:mysql://localhost:3306/shop?useSSL=false&serverTimezone=UTC&characterEncoding=UTF-8"/><property name="driverClass" value="com.mysql.jdbc.Driver"/><property name="maxPoolSize" value="10"/><property name="minPoolSize" value="1"/></bean><!-- 配置sql会化工厂 --><bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"><property name="dataSource" ref="dataSource"/><property name="configLocation" value="classpath:mybatisConfig.xml"/> </bean><!-- 配置扫描包,加载mapper代理对象 --><bean class="org.mybatis.spring.mapper.MapperScannerConfigurer"><property name="basePackage" value="com.shop.mapper"/><property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/></bean><!-- 配置spring事务管理器 --><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.shop.service.*.*(..))"/>    </aop:config>    <!-- 实际开发中handler的配置通过扫描的方式配置 ,可以扫描Controller、Service--><context:component-scan base-package="com.shop.controller,com.shop.service"/><!-- 使用该标签可以替代上面两个注解标签的配置,而且默认加载很多实用的参数绑定器 --><mvc:annotation-driven><!-- json数据中文乱码问题 --><mvc:message-converters>        <bean class="org.springframework.http.converter.StringHttpMessageConverter">            <property name="supportedMediaTypes">                <list>                    <value>application/json;charset=UTF-8</value>                </list>            </property>        </bean>    </mvc:message-converters></mvc:annotation-driven><!-- 处理器适配器 --><bean class="org.springframework.web.servlet.mvc.SimpleControllerHandlerAdapter"/><!-- 视图解析器  --><bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"/><!-- 上传文件 --><bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"><property name="defaultEncoding" value="UTF-8"/><property name="maxUploadSize" value="5242880"/></bean><!-- 配置url拦截映射,防止资源文件请求被拦截--><mvc:resources location="/css/" mapping="css/**"/><mvc:resources location="/js/" mapping="js/**"/><mvc:resources location="/images/" mapping="images/**"/><!-- 配置基于注解的事务管理器 --><tx:annotation-driven transaction-manager="transactionManager" proxy-target-class="true"/></beans>
GoodsController.java

package com.shop.controller;import java.util.List;import javax.annotation.Resource;import org.springframework.stereotype.Controller;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.ResponseBody;import org.springframework.web.servlet.ModelAndView;import com.github.pagehelper.PageInfo;import com.shop.pojo.Goods;import com.shop.service.GoodsService;import com.shop.util.AjaxResult;@Controller()@RequestMapping("/goods/")public class GoodsController {@Resourceprivate GoodsService goodsService;@RequestMapping("manage")public String manage() {return "redirect:/goods/getGoodsList";}@RequestMapping("show")public String show() {return "redirect:/goods/showGoods";}@RequestMapping("showGoods")public ModelAndView showGoods(Integer page) {PageInfo pageInfo = goodsService.getGoodsList(page);ModelAndView model = new ModelAndView("/show.jsp", "goodsList", pageInfo.getList());model.addObject("pageInfo", pageInfo);return model;}// 用户验证成功,跳转到管理界面@RequestMapping("getGoodsList")public ModelAndView getGoodsList(Integer page) {PageInfo<Goods> pageInfo = goodsService.getGoodsList(page);ModelAndView model = new ModelAndView("/manage.jsp", "goodsList", pageInfo.getList());model.addObject("pageInfo", pageInfo);return model;}// 通过商品id号显示商品详细信息(购买界面)@RequestMapping("goodsInformation")public ModelAndView goodsInformation(Long id) {Goods goodsInformation = goodsService.getGoodsInformation(id);return new ModelAndView("/goods_information.jsp", "goodsInformation", goodsInformation);}// 得到最大商品编号,加1作为新加商品的id@RequestMapping("getNewGoodsId")@ResponseBodypublic AjaxResult getNewGoodsId() {Integer newId = goodsService.getNewGoodsId();return AjaxResult.build(200, String.valueOf(newId));}@RequestMapping("addGoods")public ModelAndView addGoods(String flag) {return new ModelAndView("/edit.jsp", "flag", flag);}@RequestMapping("saveGoods")@ResponseBodypublic AjaxResult saveGoods(Goods goods, String flag) {if (flag.equals("add")) {goodsService.addGoods(goods);} else if (flag.equals("edit")) {goodsService.updateGoods(goods);}return AjaxResult.ok();}@RequestMapping("editGoods")public ModelAndView editGoods(Long id, String flag) {Goods goods = goodsService.getGoodsById(id);ModelAndView model = new ModelAndView("/edit.jsp", "goods", goods);model.addObject("flag", flag);return model;}@RequestMapping("deleteGoods")public String deleteGoods(Long id) {goodsService.deleteGoodsById(id);return "redirect:/goods/getGoodsList";}// 通过用户搜索框内容查询商品@RequestMapping("queryGoodsByTitle")public ModelAndView queryGoodsByTitle(String title) {List<Goods> goodsList = goodsService.getGoodsListByTitle(title);ModelAndView model = new ModelAndView("/manage.jsp", "goodsList", goodsList);return model;}// 通过用户搜索框内容查询商品@RequestMapping("queryGoodsByTitleAtShowPage")public ModelAndView queryGoodsByTitleAtShowPage(String title) {List<Goods> goodsList = goodsService.getGoodsListByTitle(title);ModelAndView model = new ModelAndView("/show.jsp", "goodsList", goodsList);return model;}}
LoginController.java

package com.shop.controller;import javax.annotation.Resource;import javax.servlet.http.HttpServletRequest;import org.springframework.stereotype.Controller;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.ResponseBody;import com.shop.pojo.User;import com.shop.service.UserService;import com.shop.util.AjaxResult;//登录控制,将网站请求跳转到登录界面@Controller()@RequestMapping("/login/")public class LoginController {@Resource(name = "userService")private UserService userService;// 登录验证@RequestMapping("loginValidate")@ResponseBodypublic AjaxResult loginValidate(String username, String password, HttpServletRequest request) {User user = userService.getUserByUsername(username);if (user == null) {return AjaxResult.build(500, "用户不存在,请重新输入!");} else if (!user.getPassword().equals(password)) {return AjaxResult.build(400, "密码错误,请重新输入!");} else {request.getSession().setAttribute("user", user);return AjaxResult.ok();}}@RequestMapping("exitUser")@ResponseBody// 退出用户清空当前sessionpublic AjaxResult exitUser(HttpServletRequest request) {request.getSession().removeAttribute("user");return AjaxResult.ok();}// 跳转到登录界面@RequestMapping("login")public String login() {return "/login.jsp";}// 跳转到注册界面@RequestMapping("register")public String register() {return "/register.jsp";}// 用户注册验证@RequestMapping("registerValidate")@ResponseBodypublic AjaxResult registerValidate(User user,HttpServletRequest request) {User findUser = userService.getUserByUsername(user.getUsername());if (findUser == null) {user.setLevel(1);request.getSession().setAttribute("user", user);userService.addUser(user);return AjaxResult.ok();} else {return AjaxResult.build(400, "用户已存在");}}}
GoodsMapper.java

package com.shop.mapper;import com.shop.pojo.Goods;import com.shop.pojo.GoodsExample;import java.util.List;import org.apache.ibatis.annotations.Param;public interface GoodsMapper {    int countByExample(GoodsExample example);    int deleteByExample(GoodsExample example);    int deleteByPrimaryKey(Long id);    int insert(Goods record);    int insertSelective(Goods record);    List<Goods> selectByExample(GoodsExample example);    Goods selectByPrimaryKey(Long id);    int updateByExampleSelective(@Param("record") Goods record, @Param("example") GoodsExample example);    int updateByExample(@Param("record") Goods record, @Param("example") GoodsExample example);    int updateByPrimaryKeySelective(Goods record);    int updateByPrimaryKey(Goods record);        List<Goods> getGoodsList();        Integer getMaxNo();        List<Goods> getGoodsListByTitle(String title);}
package com.shop.mapper;import com.shop.pojo.User;import com.shop.pojo.UserExample;import java.util.List;import org.apache.ibatis.annotations.Param;public interface UserMapper {    int countByExample(UserExample example);    int deleteByExample(UserExample example);    int deleteByPrimaryKey(Integer id);    int insert(User record);    int insertSelective(User record);    List<User> selectByExample(UserExample example);    User selectByPrimaryKey(Integer id);    int updateByExampleSelective(@Param("record") User record, @Param("example") UserExample example);    int updateByExample(@Param("record") User record, @Param("example") UserExample example);    int updateByPrimaryKeySelective(User record);    int updateByPrimaryKey(User record);}

GoodsMapper.xml
<?xml version="1.0" encoding="UTF-8" ?><!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd" ><mapper namespace="com.shop.mapper.GoodsMapper" >  <resultMap id="BaseResultMap" type="com.shop.pojo.Goods" >    <id column="id" property="id" jdbcType="BIGINT" />    <result column="title" property="title" jdbcType="VARCHAR" />    <result column="price" property="price" jdbcType="REAL" />    <result column="number" property="number" jdbcType="INTEGER" />    <result column="sell_point" property="sellPoint" jdbcType="VARCHAR" />  </resultMap>  <sql id="Example_Where_Clause" >    <where >      <foreach collection="oredCriteria" item="criteria" separator="or" >        <if test="criteria.valid" >          <trim prefix="(" suffix=")" prefixOverrides="and" >            <foreach collection="criteria.criteria" item="criterion" >              <choose >                <when test="criterion.noValue" >                  and ${criterion.condition}                </when>                <when test="criterion.singleValue" >                  and ${criterion.condition} #{criterion.value}                </when>                <when test="criterion.betweenValue" >                  and ${criterion.condition} #{criterion.value} and #{criterion.secondValue}                </when>                <when test="criterion.listValue" >                  and ${criterion.condition}                  <foreach collection="criterion.value" item="listItem" open="(" close=")" separator="," >                    #{listItem}                  </foreach>                </when>              </choose>            </foreach>          </trim>        </if>      </foreach>    </where>  </sql>  <sql id="Update_By_Example_Where_Clause" >    <where >      <foreach collection="example.oredCriteria" item="criteria" separator="or" >        <if test="criteria.valid" >          <trim prefix="(" suffix=")" prefixOverrides="and" >            <foreach collection="criteria.criteria" item="criterion" >              <choose >                <when test="criterion.noValue" >                  and ${criterion.condition}                </when>                <when test="criterion.singleValue" >                  and ${criterion.condition} #{criterion.value}                </when>                <when test="criterion.betweenValue" >                  and ${criterion.condition} #{criterion.value} and #{criterion.secondValue}                </when>                <when test="criterion.listValue" >                  and ${criterion.condition}                  <foreach collection="criterion.value" item="listItem" open="(" close=")" separator="," >                    #{listItem}                  </foreach>                </when>              </choose>            </foreach>          </trim>        </if>      </foreach>    </where>  </sql>  <sql id="Base_Column_List" >    id, title, price, number, sell_point  </sql>  <select id="selectByExample" resultMap="BaseResultMap" parameterType="com.shop.pojo.GoodsExample" >    select    <if test="distinct" >      distinct    </if>    <include refid="Base_Column_List" />    from goods    <if test="_parameter != null" >      <include refid="Example_Where_Clause" />    </if>    <if test="orderByClause != null" >      order by ${orderByClause}    </if>  </select>  <select id="selectByPrimaryKey" resultMap="BaseResultMap" parameterType="java.lang.Long" >    select     <include refid="Base_Column_List" />    from goods    where id = #{id,jdbcType=BIGINT}  </select>  <delete id="deleteByPrimaryKey" parameterType="java.lang.Long" >    delete from goods    where id = #{id,jdbcType=BIGINT}  </delete>  <delete id="deleteByExample" parameterType="com.shop.pojo.GoodsExample" >    delete from goods    <if test="_parameter != null" >      <include refid="Example_Where_Clause" />    </if>  </delete>  <insert id="insert" parameterType="com.shop.pojo.Goods" >    insert into goods (id, title, price,       number, sell_point)    values (#{id,jdbcType=BIGINT}, #{title,jdbcType=VARCHAR}, #{price,jdbcType=REAL},       #{number,jdbcType=INTEGER}, #{sellPoint,jdbcType=VARCHAR})  </insert>  <insert id="insertSelective" parameterType="com.shop.pojo.Goods" >    insert into goods    <trim prefix="(" suffix=")" suffixOverrides="," >      <if test="id != null" >        id,      </if>      <if test="title != null" >        title,      </if>      <if test="price != null" >        price,      </if>      <if test="number != null" >        number,      </if>      <if test="sellPoint != null" >        sell_point,      </if>    </trim>    <trim prefix="values (" suffix=")" suffixOverrides="," >      <if test="id != null" >        #{id,jdbcType=BIGINT},      </if>      <if test="title != null" >        #{title,jdbcType=VARCHAR},      </if>      <if test="price != null" >        #{price,jdbcType=REAL},      </if>      <if test="number != null" >        #{number,jdbcType=INTEGER},      </if>      <if test="sellPoint != null" >        #{sellPoint,jdbcType=VARCHAR},      </if>    </trim>  </insert>  <select id="countByExample" parameterType="com.shop.pojo.GoodsExample" resultType="java.lang.Integer" >    select count(*) from goods    <if test="_parameter != null" >      <include refid="Example_Where_Clause" />    </if>  </select>  <update id="updateByExampleSelective" parameterType="map" >    update goods    <set >      <if test="record.id != null" >        id = #{record.id,jdbcType=BIGINT},      </if>      <if test="record.title != null" >        title = #{record.title,jdbcType=VARCHAR},      </if>      <if test="record.price != null" >        price = #{record.price,jdbcType=REAL},      </if>      <if test="record.number != null" >        number = #{record.number,jdbcType=INTEGER},      </if>      <if test="record.sellPoint != null" >        sell_point = #{record.sellPoint,jdbcType=VARCHAR},      </if>    </set>    <if test="_parameter != null" >      <include refid="Update_By_Example_Where_Clause" />    </if>  </update>  <update id="updateByExample" parameterType="map" >    update goods    set id = #{record.id,jdbcType=BIGINT},      title = #{record.title,jdbcType=VARCHAR},      price = #{record.price,jdbcType=REAL},      number = #{record.number,jdbcType=INTEGER},      sell_point = #{record.sellPoint,jdbcType=VARCHAR}    <if test="_parameter != null" >      <include refid="Update_By_Example_Where_Clause" />    </if>  </update>  <update id="updateByPrimaryKeySelective" parameterType="com.shop.pojo.Goods" >    update goods    <set >      <if test="title != null" >        title = #{title,jdbcType=VARCHAR},      </if>      <if test="price != null" >        price = #{price,jdbcType=REAL},      </if>      <if test="number != null" >        number = #{number,jdbcType=INTEGER},      </if>      <if test="sellPoint != null" >        sell_point = #{sellPoint,jdbcType=VARCHAR},      </if>    </set>    where id = #{id,jdbcType=BIGINT}  </update>  <update id="updateByPrimaryKey" parameterType="com.shop.pojo.Goods" >    update goods    set title = #{title,jdbcType=VARCHAR},      price = #{price,jdbcType=REAL},      number = #{number,jdbcType=INTEGER},      sell_point = #{sellPoint,jdbcType=VARCHAR}    where id = #{id,jdbcType=BIGINT}  </update>  <select id="getGoodsList" resultMap="BaseResultMap">  select * from goods  </select>  <select id="getMaxNo" resultType="Integer">  SELECT MAX(id) FROM goods  </select>  <!-- 通过标题查询商品列表 -->  <select id="getGoodsListByTitle" parameterType="String" resultMap="BaseResultMap">  SELECT * FROM goods WHERE title LIKE CONCAT('%',#{title},'%') LIMIT 0,8  </select></mapper>


如果需要源程序,请加我qq:3425385768





原创粉丝点击