用MyBatis三剑客实现一个简单的电商信息管理系统

4 篇文章 0 订阅
1 篇文章 0 订阅

一、主要功能

本次任务主要是使用MyBatis实现一个简单的电商信息管理系统,主要功能为:
1.显示所有商品的信息(默认为20个)
2. 点击按钮,显示出商品详情页的信息
3. 增加商品信息
4. 使用MyBatis配置pagehelper高效准确实现分页和动态排序

二、实现思路

1.数据管理:对于创建时间和更新时间不在业务代码中控制,通过DB的内置函数进行填写
2.通过LP的方式,执行数据SQL后面写上分页处理
3.mybatis pager监听到变化,mybatis pager通过LP自动把分页需要的LP再次执行
4.使用 pagehelper动态排序 把符合筛选条件的商品信息显示在主页上

三、代码实现

1、在prom.xml中配置mybatis-generator

 <plugin>
        <groupId>org.mybatis.generator</groupId>
        <artifactId>mybatis-generator-maven-plugin</artifactId>
        <version>1.3.2</version>
        <configuration>
          <verbose>true</verbose>
          <overwrite>true</overwrite>
        </configuration>
      </plugin>

mybatis插件需要的jar包自动加载
2、配置mybatis-generator

<generatorConfiguration>
    <!--导入属性配置-->
    <properties resource="datasource.properties"></properties>
创建datasource.properties,根据数据库配置参数
db.driverLocation=/Users/mysql-connector-java-5.1.6-bin.jar
db.driverClassName=com.mysql.jdbc.Driver

db.url=jdbc:mysql://192.1.1.1:3306/mall?characterEncoding=utf-8
#db.url=jdbc:mysql://数据库IP:数据库Port/你的database?characterEncoding=utf-8
db.username=mall
db.password=password


db.initialSize = 20
db.maxActive = 50
db.maxIdle = 20
db.minIdle = 10
db.maxWait = 10
db.defaultAutoCommit = true
db.minEvictableIdleTimeMillis = 3600000

3、根据数据库的表配置映射

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE generatorConfiguration
        PUBLIC "-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN"
        "http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd">

<generatorConfiguration>
    <!--导入属性配置-->
    <properties resource="datasource.properties"></properties>

    <!--指定特定数据库的jdbc驱动jar包的位置-->
    <classPathEntry location="${db.driverLocation}"/>

    <context id="default" targetRuntime="MyBatis3">

        <!-- optional,旨在创建class时,对注释进行控制 -->
        <commentGenerator>
            <property name="suppressDate" value="true"/>
            <property name="suppressAllComments" value="true"/>
        </commentGenerator>

        <!--jdbc的数据库连接 -->
        <jdbcConnection
                driverClass="${db.driverClassName}"
                connectionURL="${db.url}"
                userId="${db.username}"
                password="${db.password}">
        </jdbcConnection>


        <!-- 非必需,类型处理器,在数据库类型和java类型之间的转换控制-->
        <javaTypeResolver>
            <property name="forceBigDecimals" value="false"/>
        </javaTypeResolver>


        <!-- Model模型生成器,用来生成含有主键key的类,记录类 以及查询Example类
            targetPackage     指定生成的model生成所在的包名
            targetProject     指定在该项目下所在的路径
        -->
        <!--<javaModelGenerator targetPackage="com.mall.pojo" targetProject=".\src\main\java">-->
        <javaModelGenerator targetPackage="com.mall.pojo" targetProject="./src/main/java">
            <!-- 是否允许子包,即targetPackage.schemaName.tableName -->
            <property name="enableSubPackages" value="false"/>
            <!-- 是否对model添加 构造函数 -->
            <property name="constructorBased" value="true"/>
            <!-- 是否对类CHAR类型的列的数据进行trim操作 -->
            <property name="trimStrings" value="true"/>
            <!-- 建立的Model对象是否 不可改变  即生成的Model对象不会有 setter方法,只有构造方法 -->
            <property name="immutable" value="false"/>
        </javaModelGenerator>

        <!--mapper映射文件生成所在的目录 为每一个数据库的表生成对应的SqlMap文件 -->
        <!--<sqlMapGenerator targetPackage="mappers" targetProject=".\src\main\resources">-->
        <sqlMapGenerator targetPackage="mappers" targetProject="./src/main/resources">
            <property name="enableSubPackages" value="false"/>
        </sqlMapGenerator>

        <!-- 客户端代码,生成易于使用的针对Model对象和XML配置文件 的代码
                type="ANNOTATEDMAPPER",生成Java Model 和基于注解的Mapper对象
                type="MIXEDMAPPER",生成基于注解的Java Model 和相应的Mapper对象
                type="XMLMAPPER",生成SQLMap XML文件和独立的Mapper接口
        -->

        <!-- targetPackage:mapper接口dao生成的位置 -->
        <!--<javaClientGenerator type="XMLMAPPER" targetPackage="com.mall.dao" targetProject=".\src\main\java">-->
        <javaClientGenerator type="XMLMAPPER" targetPackage="com.mall.dao" targetProject="./src/main/java">
            <!-- enableSubPackages:是否让schema作为包的后缀 -->
            <property name="enableSubPackages" value="false" />
        </javaClientGenerator>


        <table tableName="mall_shipping" domainObjectName="Shipping" enableCountByExample="false" enableUpdateByExample="false" enableDeleteByExample="false" enableSelectByExample="false" selectByExampleQueryId="false"></table>
        <table tableName="mall_cart" domainObjectName="Cart" enableCountByExample="false" enableUpdateByExample="false" enableDeleteByExample="false" enableSelectByExample="false" selectByExampleQueryId="false"></table>
        <table tableName="mall_cart_item" domainObjectName="CartItem" enableCountByExample="false" enableUpdateByExample="false" enableDeleteByExample="false" enableSelectByExample="false" selectByExampleQueryId="false"></table>
        <table tableName="mall_category" domainObjectName="Category" enableCountByExample="false" enableUpdateByExample="false" enableDeleteByExample="false" enableSelectByExample="false" selectByExampleQueryId="false"></table>
        <table tableName="mall_order" domainObjectName="Order" enableCountByExample="false" enableUpdateByExample="false" enableDeleteByExample="false" enableSelectByExample="false" selectByExampleQueryId="false"></table>
        <table tableName="mall_order_item" domainObjectName="OrderItem" enableCountByExample="false" enableUpdateByExample="false" enableDeleteByExample="false" enableSelectByExample="false" selectByExampleQueryId="false"></table>
        <table tableName="mall_pay_info" domainObjectName="PayInfo" enableCountByExample="false" enableUpdateByExample="false" enableDeleteByExample="false" enableSelectByExample="false" selectByExampleQueryId="false"></table>
        <table tableName="mall_product" domainObjectName="Product" enableCountByExample="false" enableUpdateByExample="false" enableDeleteByExample="false" enableSelectByExample="false" selectByExampleQueryId="false">
            <columnOverride column="detail" jdbcType="VARCHAR" />
            <columnOverride column="sub_images" jdbcType="VARCHAR" />
        </table>
        <table tableName="mall_user" domainObjectName="User" enableCountByExample="false" enableUpdateByExample="false" enableDeleteByExample="false" enableSelectByExample="false" selectByExampleQueryId="false"></table>


        <!-- geekfanrnote mybatis插件的搭建 -->
    </context>
</generatorConfiguration>

4、使用mybatis-generator生成数据对象
在Maven下找到mybatis-generator双击,自动生成dao层、pojo层、mappers层
create_time字段记录数据创建的时间
update_time字段记录数据更新的时间
在查一些线上逻辑业务问题时,这两个字段至关重要

<arg column="create_time" jdbcType="TIMESTAMP" javaType="java.util.Date" />
<arg column="update_time" jdbcType="TIMESTAMP" javaType="java.util.Date" />

5.时间戳优化
对于创建时间和更新时间不在业务代码中控制,通过DB的内置函数进行填写,改变每个Mapper.xml中create_time、update_time属性,让他们由数据库完成

#{createTime,jdbc=TIMESTAMP},#{updateTime,jdbc=TIMESTAMP},

更改value属性为mysql内置函数now()

<insert id="insert" parameterType="com.mall.pojo.Cart" >
    insert into mall_cart (id, user_id, product_id, 
      quantity, checked, create_time, 
      update_time)
    values (#{id,jdbcType=INTEGER}, #{userId,jdbcType=INTEGER}, #{productId,jdbcType=INTEGER}, 
      #{quantity,jdbcType=INTEGER}, #{checked,jdbcType=INTEGER}, now(),
      now())
  </insert>
更新操作中create_time属性不作处理、update_time属性更改为now()
 <update id="updateByPrimaryKeySelective" parameterType="com.mall.pojo.Cart" >
    update mall_cart
    <set >
      <if test="userId != null" >
        user_id = #{userId,jdbcType=INTEGER},
      </if>
      <if test="productId != null" >
        product_id = #{productId,jdbcType=INTEGER},
      </if>
      <if test="quantity != null" >
        quantity = #{quantity,jdbcType=INTEGER},
      </if>
      <if test="checked != null" >
        checked = #{checked,jdbcType=INTEGER},
      </if>
      <if test="createTime != null" >
        create_time = #{createTime,jdbcType=TIMESTAMP},
      </if>
      <if test="updateTime != null" >
        update_time = now(),
      </if>
    </set>
    where id = #{id,jdbcType=INTEGER}
  </update>

5.安装mybatis-plugin
对于跟踪DAO层,通过mybatis-plugin插件找到对应的xml,方便跳转
6.安装mybatis-pagehelper分页插件
在porm.xml中引入mybatis-pagehelper分页插件

   <!-- mybatis pager -->

    <dependency>
      <groupId>com.github.pagehelper</groupId>
      <artifactId>pagehelper</artifactId>
      <version>4.1.0</version>
    </dependency>

    <dependency>
      <groupId>com.github.miemiedev</groupId>
      <artifactId>mybatis-paginator</artifactId>
      <version>1.2.17</version>
    </dependency>

    <dependency>
      <groupId>com.github.jsqlparser</groupId>
      <artifactId>jsqlparser</artifactId>
      <version>0.9.4</version>
    </dependency>

7.执行分页查询部分数据,分页查询总数量,根据pagesize页面容量进行分页,对分页数量进行返回
利用 mybatis RequestParam 设置 默认值

@RequestParam(value = "pageNum", defaultValue = "1") int pageNum, @RequestParam(value = "pageSize", defaultValue = "10") int pageSize
 

8.高效准确地分页及动态排序

public ServerResponse getProductList(int pageNum, int pageSize) {
  
    PageHelper.startPage(pageNum, pageSize);    // PageHelper 加载
    List<Product> productList = productMapper.selectList();
 
    List<ProductListVo> productListVoList = Lists.newArrayList();    // vo
    for (Product productItem : productList) {
        ProductListVo productListVo = assembleProductListVo(productItem);
        productListVoList.add(productListVo);
    }

    //根据productList生成PageInfo对象,会根据productList 各种计算页面参数
    PageInfo pageResult = new PageInfo(productList);    
    //但是给前端展示的不是整个 productList,而是productVoList 所以需要重置一下 setList
    pageResult.setList(productListVoList);
    return ServerResponse.createBySuccess(pageResult);
}

9.pageHelper 分页插件还会自动加 limit 等语句,mapper中写sql的时候,末尾加 “;” 会出现语法错误

<select id="selectList" resultMap="BaseResultMap">
    select
    <include refid="Base_Column_List"/>
    from immall_product
    order by id asc
</select>

四、效果展示

商品管理-001
品类管理-002
订单管理-003

五、总结

mybatis-generator是很好用的mybatis自动代码生成工具。手动写一个个实体类和mapper还有xml配置文件会很麻烦,使用mybatis-generator只需要简单的配置就能完成。在mapper中定义的方法不能通过ctrl+鼠标右键找到对应的xml实现语句中,对代码的编写效率大打折扣,使用mybatis-plugin跳转插件提高效率。mybatis-pagehelper分页插件可以高效准确实现分页和动态排序,无需去封装以及关心sql分页等问题,使用很方便,前端取数据也很方便。

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

极客范儿

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值