spring boot + mybatis + maven 构建新工程

31 篇文章 3 订阅

前言

        公司转型,新项目需要用java作为老员工,也只能转型了 ,最近开始重新捡起java 多年不碰了新构架新的开始。至少 jdbc hss  还会  学一下新框架 spring boot, mybatis 吧, maven 是真好用啊。

一.工程建立。

使用 Spring Initializr工具直接建立。

 springboot 依赖库 我选择Lombok ,DevTools,SpringWeb,MybatisFrameWork,MS SQL Server。等

Lombok 可以减少 beans  的 代码量。数据库持久层 用Mybatis 没用 Hibernate, 尝尝鲜, 电脑上装了MSSQLServer 就用这吧 懒得装mysql 了 而且说实话 sqlserver 确实比 mysql 效率高。数据量超过千万量级后 mysql 明显比不过 mssqlserver了 不知道是不是我 mysql 理解的不够透彻导致的。

三.框架目录结构

这里包括了 控制层controller,持久层pojo,dao层mapper,业务逻辑层service,通用工具utils

四.pom文件中添加依赖和插件。

添加一下 mybatis 的驱动依赖

        <!--  mybatis 驱动  -->
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.5.9</version>
        </dependency>

既然使用了mybatis 那就直接添加 mybatis.generator 这个插件 可以自动生成相关映射文件。化繁为简吗,手撕代码很烦的。当然生成后可以加工美化一下。自动生成的代码有点冗长。

      <build>
        <plugins>     
            <plugin>
                <groupId>org.mybatis.generator</groupId>
                <artifactId>mybatis-generator-maven-plugin</artifactId>
                <version>1.3.5</version>

                <dependencies>
                    <dependency>
                        <groupId>com.microsoft.sqlserver</groupId>
                        <artifactId>mssql-jdbc</artifactId>
                        <version>10.2.1.jre8</version>
                    </dependency>
                </dependencies>
                <!--指定配置文件位置-->
                <configuration>
                    <configurationFile>./src/main/resources/generatorConfig.xml</configurationFile>
                    <verbose>true</verbose>
                    <overwrite>true</overwrite>
                </configuration>
            </plugin>
        </plugins>
    </build>

这里可以在configuration标签里指定一下 generator配置文件位置。否则无法使用插件

下面配置一下 generatorConfig.xml

<?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>
    <context id="MysqlTables" targetRuntime="MyBatis3"  defaultModelType="flat">
        <!-- 生成的Java文件的编码 -->
        <property name="javaFileEncoding" value="UTF-8" />
        <!-- 格式化java代码 -->
        <property name="javaFormatter" value="org.mybatis.generator.api.dom.DefaultJavaFormatter" />
        <!-- 格式化XML代码 -->
        <property name="xmlFormatter" value="org.mybatis.generator.api.dom.DefaultXmlFormatter" />
        <!--beginningDelimiter和endingDelimiter:指明数据库的用于标记数据库对象名的符号,例如:ORACLE使用双引号,MYSQL默认是`反引号; -->
        <property name="beginningDelimiter" value="`" />
        <property name="endingDelimiter" value="`" />
        <!-- lombok插件,減少生成代碼 -->

        <!-- 使用自带序列化插件 -->
        <plugin type="org.mybatis.generator.plugins.SerializablePlugin"/>
        <!-- 注释 -->
        <commentGenerator>
            <property name="suppressDate" value="true" />
            <!-- 是否去除自动生成的注释 true:是 : false:否 -->
            <property name="suppressAllComments" value="true" />
        </commentGenerator>
        <!-- 数据库链接配置 -->
        <jdbcConnection driverClass="com.microsoft.sqlserver.jdbc.SQLServerDriver"
                        connectionURL="jdbc:sqlserver://192.168.8.66:1433;DatabaseName=IotCard;integratedSecurity=false;encrypt=false;trustServerCertificate=false"
                        userId="sa" password="******">
        </jdbcConnection>

        <!-- 实体类生成未知 -->
        <javaModelGenerator
                targetPackage="com.cliot.pojo" targetProject="./src/main/java/">
            <property name="enableSubPackages" value="true" />
            <property name="trimStrings" value="true" />
        </javaModelGenerator>
        <!-- mapping文件生成位置 -->
        <sqlMapGenerator targetPackage="mapper" targetProject="./src/main/resources/">
            <property name="enableSubPackages" value="true" />
        </sqlMapGenerator>

        <!-- dao接口生成位置 -->
        <javaClientGenerator type="XMLMAPPER"
                             targetPackage="com.cliot.mapper" targetProject="./src/main/java/">
            <property name="enableSubPackages" value="true" />
        </javaClientGenerator>
        <!-- 表配置 tableName 表名 domainObjectName java类名,首字母必须大写,否则报字符串越界错误 -->
        <table tableName="cardinfo" domainObjectName="CardInfo"
               enableCountByExample="false" enableUpdateByExample="false"
               enableDeleteByExample="false" enableSelectByExample="false"
               selectByExampleQueryId="false">
        </table>
        <table tableName="card_pooled_monthly_usage" domainObjectName="CardPooledMonthlyUsage"
               enableCountByExample="false" enableUpdateByExample="false"
               enableDeleteByExample="false" enableSelectByExample="false"
               selectByExampleQueryId="false">
        </table>
        <table tableName="card_pooled_12month_usage" domainObjectName="CardPooled12MonthUsage"
               enableCountByExample="false" enableUpdateByExample="false"
               enableDeleteByExample="false" enableSelectByExample="false"
               selectByExampleQueryId="false">
        </table>
    </context>
</generatorConfiguration>

配置一下数据库驱动,连接字符串 用户名密码等,配置一下 mapper dao接口生成路径,mapper.xml文件生成路劲 pojo 映射文件生成路劲等 ,根据自己的时间需求配置把。

然后配置一下 数据库表的信息,完成

五. 生成mybatis映射文件。

点击生成文件 

 

 啊文件生成了

我们来看看

不错不错方便 真想。 看看代码吧

 不看了 反正能用就行,为了避坑 我们还是需要对代码加工一下。就是加几个注释。

 

package com.cliot.mapper;

import com.cliot.pojo.CardInfo;
import org.apache.ibatis.annotations.Mapper;
import org.springframework.stereotype.Repository;

@Repository
@Mapper
public interface CardInfoMapper {
    int deleteByPrimaryKey(Long cardId);

    int insert(CardInfo record);

    int insertSelective(CardInfo record);

    CardInfo selectByPrimaryKey(Long cardId);

    int updateByPrimaryKeySelective(CardInfo record);

    int updateByPrimaryKey(CardInfo record);
}

 在 mapper接口文件上加入 @Repository 和@Mapper  可以让springboot方便扫描到映射文件可以自动装载。踩过的坑还是要提一嘴。

哦 还有要在启动函数上加注释  ,@Mapperscan(“******”) ,可以让容器自动注入 mapper免得后面报红 说找不到 映射文件。

 六.配置springboot 配置文件

不多说了直接上文件了。大家都看得懂。

spring.datasource.driver-class-name=com.microsoft.sqlserver.jdbc.SQLServerDriver
spring.datasource.username=sa
spring.datasource.password=******
spring.datasource.url=jdbc:sqlserver://192.168.8.66:1433;DatabaseName=IotCard;integratedSecurity=false;encrypt=false;trustServerCertificate=false

spring.datasource.hikari.minimum-idle=5
spring.datasource.hikari.maximum-pool-size=60
spring.datasource.hikari.auto-commit=true
spring.datasource.hikari.idle-timeout=30000
spring.datasource.hikari.pool-name= DatebookHikariCP
spring.datasource.hikari.max-lifetime=900000
spring.datasource.hikari.connection-timeout= 15000
spring.datasource.hikari.connection-test-query: SELECT 1

mybatis.mapper-locations= classpath:mapper/*.xml
mybatis.type-aliases-package=com.cliot.pojo

这里设置了 数据源参数,连接池参数 ,持久层mapper的存放地址 映射文件pojo的映射文件等

懂得都懂 不懂得 度娘一下都懂了 就不一一赘述了。

七.测试是否成功

建立测试的controller类

package com.cliot.controller;

import com.cliot.pojo.CardPooledMonthlyUsage;
import com.cliot.service.TestService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;

@Controller
public class TestController {
    @Autowired
    TestService testService;
    @RequestMapping("/")
    @ResponseBody
    public List<CardPooledMonthlyUsage> test() throws Exception {
        List<CardPooledMonthlyUsage> cards=testService.queryCard();
        return cards;
    }
}

 建立service类处理业务逻辑

package com.cliot.service;

import com.cliot.mapper.CardPooledMonthlyUsageMapper;
import com.cliot.pojo.CardPooledMonthlyUsage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class TestService {

    @Autowired
    CardPooledMonthlyUsageMapper monthlyUsageMapper;

    public List<CardPooledMonthlyUsage> queryCard() {
        return monthlyUsageMapper.queryAll();
    }

}

修改 dao层 mapper文件 增加测试 的sql 处理语句。

 

<?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.cliot.mapper.CardPooledMonthlyUsageMapper">
  <resultMap id="BaseResultMap" type="com.cliot.pojo.CardPooledMonthlyUsage">
    <id column="usage_id" jdbcType="BIGINT" property="usageId" />
    <result column="card_id" jdbcType="BIGINT" property="cardId" />
    <result column="iccid" jdbcType="NVARCHAR" property="iccid" />
    <result column="used_flow" jdbcType="DOUBLE" property="usedFlow" />
    <result column="usage_month" jdbcType="NVARCHAR" property="usageMonth" />
    <result column="DESC_CNT" jdbcType="NVARCHAR" property="descCnt" />
  </resultMap>
  <sql id="Base_Column_List">
    usage_id, card_id, iccid, used_flow, usage_month, DESC_CNT
  </sql>
  <select id="selectByPrimaryKey" parameterType="java.lang.Long" resultMap="BaseResultMap">
    select 
    <include refid="Base_Column_List" />
    from card_pooled_monthly_usage
    where usage_id = #{usageId,jdbcType=BIGINT}
  </select>
  <delete id="deleteByPrimaryKey" parameterType="java.lang.Long">
    delete from card_pooled_monthly_usage
    where usage_id = #{usageId,jdbcType=BIGINT}
  </delete>
  <insert id="insert" parameterType="com.cliot.pojo.CardPooledMonthlyUsage">
    insert into card_pooled_monthly_usage (usage_id, card_id, iccid, 
      used_flow, usage_month, DESC_CNT
      )
    values (#{usageId,jdbcType=BIGINT}, #{cardId,jdbcType=BIGINT}, #{iccid,jdbcType=NVARCHAR}, 
      #{usedFlow,jdbcType=DOUBLE}, #{usageMonth,jdbcType=NVARCHAR}, #{descCnt,jdbcType=NVARCHAR}
      )
  </insert>
  <insert id="insertSelective" parameterType="com.cliot.pojo.CardPooledMonthlyUsage">
    insert into card_pooled_monthly_usage
    <trim prefix="(" suffix=")" suffixOverrides=",">
      <if test="usageId != null">
        usage_id,
      </if>
      <if test="cardId != null">
        card_id,
      </if>
      <if test="iccid != null">
        iccid,
      </if>
      <if test="usedFlow != null">
        used_flow,
      </if>
      <if test="usageMonth != null">
        usage_month,
      </if>
      <if test="descCnt != null">
        DESC_CNT,
      </if>
    </trim>
    <trim prefix="values (" suffix=")" suffixOverrides=",">
      <if test="usageId != null">
        #{usageId,jdbcType=BIGINT},
      </if>
      <if test="cardId != null">
        #{cardId,jdbcType=BIGINT},
      </if>
      <if test="iccid != null">
        #{iccid,jdbcType=NVARCHAR},
      </if>
      <if test="usedFlow != null">
        #{usedFlow,jdbcType=DOUBLE},
      </if>
      <if test="usageMonth != null">
        #{usageMonth,jdbcType=NVARCHAR},
      </if>
      <if test="descCnt != null">
        #{descCnt,jdbcType=NVARCHAR},
      </if>
    </trim>
  </insert>
  <update id="updateByPrimaryKeySelective" parameterType="com.cliot.pojo.CardPooledMonthlyUsage">
    update card_pooled_monthly_usage
    <set>
      <if test="cardId != null">
        card_id = #{cardId,jdbcType=BIGINT},
      </if>
      <if test="iccid != null">
        iccid = #{iccid,jdbcType=NVARCHAR},
      </if>
      <if test="usedFlow != null">
        used_flow = #{usedFlow,jdbcType=DOUBLE},
      </if>
      <if test="usageMonth != null">
        usage_month = #{usageMonth,jdbcType=NVARCHAR},
      </if>
      <if test="descCnt != null">
        DESC_CNT = #{descCnt,jdbcType=NVARCHAR},
      </if>
    </set>
    where usage_id = #{usageId,jdbcType=BIGINT}
  </update>
  <update id="updateByPrimaryKey" parameterType="com.cliot.pojo.CardPooledMonthlyUsage">
    update card_pooled_monthly_usage
    set card_id = #{cardId,jdbcType=BIGINT},
      iccid = #{iccid,jdbcType=NVARCHAR},
      used_flow = #{usedFlow,jdbcType=DOUBLE},
      usage_month = #{usageMonth,jdbcType=NVARCHAR},
      DESC_CNT = #{descCnt,jdbcType=NVARCHAR}
    where usage_id = #{usageId,jdbcType=BIGINT}
  </update>
  <update id="updateTest">
    BEGIN TRANSACTION
    select iccid from card_pooled_monthly_usage  WITH (UPDLOCK, READPAST) where usage_month = #{usageMonth} and iccid=#{iccid}
    update card_pooled_monthly_usage set DESC_CNT='2' where usage_month = #{usageMonth} and iccid=#{iccid}
    COMMIT TRANSACTION
  </update>
  <select id="queryAll" resultMap="BaseResultMap">
    select  distinct top 10  iccid,min(usage_month) as usage_month from card_pooled_monthly_usage where usage_month >'202107' group by iccid
  </select>
</mapper>

自动生成的代码好多啊,乱七八糟的 难受。我们只看最后的 queryAll 这个标记。 要添加否则mapper接口映射不到会报错。

好了 构架做完了 可以开始测试了

运行启动程序

程序启动 运行在 8080端口 我们访问一下看

 运行成功 ,工程建立完成。

总结

        新构架 在磕磕绊绊中基本入门了。时间有限就不深入研究了。等有空了去看看构架的文档吧,反正常用的功能都能用了 可以开始开发 web 项目了。开工咯。遇到坑在学校总结吧。

 

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值