IDEA上建立 Maven SpringBoot+mybatisplus+thymeleaf 項目

概述html

  在WEB領域,Java也是在不斷的探索和改進,從開始的JSP--->Struts1--->Struts2+Spring--->Spring MVC--->SpringBoot--->Spring Cloud。在WEB領域,Java框架不斷的變化與改進。Spring Boot將Spring MVC所須要的依賴包環境集成到一個大的包環境中,便於快速開發,特別適合構建微服務系統,另外給咱們封裝了各類常用的套件,好比mybatis、hibernate、redis、mongodb等。因爲Java沒有像其餘語言(C#)那也具備屬性的操做,Spring結合IOC與AOP等技術將POJO進行註解到上下文,沒有那麼繁瑣的XML配置,調用起來靈活方便。本文主要將本身搭建SpringBoot+mybatisplus+thymeleaf的過程記錄下來,便於之後學習使用。java

環境web

  IDEA 2017.02  + Maven +Jdk1.8+Oracle10gredis

  因爲SpringBoot集成Tomcat,這裏不須要配置Tomcat,直接調試使用便可。spring

操做sql

一、利用Maven搭建項目骨架mongodb

1.一、 打開新建項目頁面數據庫

1.二、選擇Create New Project,後打開響應的建立項目的頁面,選擇Maven,按下圖標準選擇響應的archetypeapache

1.三、輸入響應的項目名稱信息,點擊Next,爲了提升項目的構建速度,咱們能夠直接訪問http://repo1.maven.org/maven2/archetype-catalog.xml,把這個xml下載下來放到本地的maven目錄中,而後在添加一個參數    archetypeCatalog=internaljson

1.四、 點擊Next-->Finish,即完成項目的構建,Maven構造完成以後的項目結構以下

二、配置項目代碼結構

2.一、這個時候,咱們須要在main下面添加文件夾resources,右鍵單擊resources設置爲Resources Root

2.二、因爲是spring boot 項目,pom.xml的parent必須繼承spring-boot-starter-parent,同時須要引用spring-boot-starter-web包,裏面整合了Spring MVC依賴的包文件。另外因爲要使用mybatis訪問數據庫,因此這裏須要加入mybatis-spring-boot-starter和Mybatis-plus的包依賴。pom.xml配置以下

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>com.justin</groupId>
  <artifactId>htcspringboot</artifactId>
  <packaging>jar</packaging>
  <version>1.0-SNAPSHOT</version>
  <name>Maven Quick Start Archetype</name>
  <url>http://maven.apache.org</url>

  <parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>1.5.2.RELEASE</version>
    <relativePath />
  </parent>

  <properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <java.version>1.8</java.version>
    <mybatis-starter-version>1.2.0</mybatis-starter-version>
    <mybatis.plus.version>2.1.0</mybatis.plus.version>
    <ojdbc14.version>10.2.0.5.0</ojdbc14.version>
    <druid.version>1.0.28</druid.version>
    <spring.boot.version>1.5.2.RELEASE</spring.boot.version>
  </properties>

  <dependencies>
    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-web</artifactId>
    </dependency>

    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-thymeleaf</artifactId>
      <version>${spring.boot.version}</version>
    </dependency>

    <dependency>
      <groupId>org.mybatis.spring.boot</groupId>
      <artifactId>mybatis-spring-boot-starter</artifactId>
      <version>${mybatis-starter-version}</version>
    </dependency>

    <dependency>
      <groupId>com.baomidou</groupId>
      <artifactId>mybatis-plus</artifactId>
      <version>${mybatis.plus.version}</version>
    </dependency>

    <dependency>
      <groupId>com.oracle</groupId>
      <artifactId>ojdbc14</artifactId>
      <version>${ojdbc14.version}</version>
    </dependency>
    <dependency>
      <groupId>com.alibaba</groupId>
      <artifactId>druid</artifactId>
      <version>${druid.version}</version>
    </dependency>
  </dependencies>

  <build>
    <plugins>
      <plugin>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-maven-plugin</artifactId>
      </plugin>
    </plugins>
  </build>

</project>

 

2.三、下面咱們須要在Resources的目錄下面,添加application.properties文件,在SpringBoot項目中,系統默認讀取項目下的application.properties的文件,因此名稱不能名錯了;在application.properties添加以下內容

# Tomcat
server.tomcat.max-threads=1000
server.tomcat.min-spare-threads=30
server.port=812    #修改Tomcat端口
server.context-path=/htc #修改相對路徑

# 環境 dev|test|pro
spring.profiles.active=dev  

cxf.path=/soap

#spring.mvc.view.prefix=/WEB-INF/views/
#spring.mvc.view.suffix=.jsp

# Mybatis配置 
mybatis.mapperLocations=classpath:/mapper/*.xml  #Mybatis項目的映射,默認映射到Class下的mapper目錄下,尋找以Mapper.xml結尾的文件
#mybatis.mapper-locations=classpath:mybatis/mapper/*Mapper.xml
#mybatis.mapperLocations=classpath:/mapper/**/*.xml

# jackson時間格式化
spring.jackson.time-zone=GMT+8
spring.jackson.date-format=yyyy-MM-dd HH:mm:ss

#Spring.thymeleaf

#資源文件的約定目錄結構
#Maven的資源文件目錄:/src/java/resources
#spring-boot項目靜態文件目錄:/src/java/resources/static
#spring-boot項目模板文件目錄:/src/java/resources/templates

spring.thymeleaf.cache=false
spring.thymeleaf.mode=HTML5
spring.thymeleaf.content-type=text/html
spring.thymeleaf.prefix=classpath:/templates/
spring.thymeleaf.suffix=.html

 

 2.四、添加application-dev.properties文件,對照application.properties文件,裏面放置數據庫的配置信息

spring.datasource.url=jdbc:oracle:thin:@127.0.0.1:1521:LZSORCL
#spring.datasource.type=com.alibaba.druid.pool.DruidDataSource
spring.datasource.type=oracle.jdbc.pool.OracleDataSource
spring.datasource.driverClassName=oracle.jdbc.driver.OracleDriver
#db
spring.datasource.username=javaAcmemgr
spring.datasource.password=javaAcmemgr

# 下面爲鏈接池的補充設置,應用到上面全部數據源中
# 初始化大小,最小,最大
spring.datasource.initialSize=20
spring.datasource.minIdle=20
spring.datasource.maxActive=100
# 配置獲取鏈接等待超時的時間
spring.datasource.maxWait=60000
# 配置間隔多久才進行一次檢測,檢測須要關閉的空閒鏈接,單位是毫秒
spring.datasource.timeBetweenEvictionRunsMillis=60000
# 配置一個鏈接在池中最小生存的時間,單位是毫秒
spring.datasource.minEvictableIdleTimeMillis=300000
spring.datasource.validationQuery=SELECT 1 FROM DUAL
spring.datasource.testWhileIdle=true
spring.datasource.testOnBorrow=false
spring.datasource.testOnReturn=false
# 打開PSCache,而且指定每一個鏈接上PSCache的大小
spring.datasource.poolPreparedStatements=true
spring.datasource.maxPoolPreparedStatementPerConnectionSize=20
# 配置監控統計攔截的filters,去掉後監控界面sql沒法統計,'wall'用於防火牆
spring.datasource.filters=stat,wall,log4j
# 經過connectProperties屬性來打開mergeSql功能;慢SQL記錄
spring.datasource.connectionProperties=druid.stat.mergeSql=true;druid.stat.slowSqlMillis=5000
# 合併多個DruidDataSource的監控數據
#spring.datasource.useGlobalDataSourceStat=true

 

 2.五、如今添加修改Mybatis-plus的配置,裏面的具體內容不過解釋,能夠參考Mybatis-plus官網文檔

package com.justin.config;

import com.baomidou.mybatisplus.MybatisConfiguration;
import com.baomidou.mybatisplus.MybatisXMLLanguageDriver;
import com.baomidou.mybatisplus.entity.GlobalConfiguration;
import com.baomidou.mybatisplus.enums.DBType;
import com.baomidou.mybatisplus.plugins.PaginationInterceptor;
import com.baomidou.mybatisplus.spring.MybatisSqlSessionFactoryBean;
import org.apache.ibatis.mapping.DatabaseIdProvider;
import org.apache.ibatis.plugin.Interceptor;
import org.mybatis.spring.boot.autoconfigure.MybatisProperties;
import org.mybatis.spring.boot.autoconfigure.SpringBootVFS;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.core.io.DefaultResourceLoader;
import org.springframework.core.io.ResourceLoader;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;
import javax.sql.DataSource;

@Configuration
@EnableConfigurationProperties(MybatisProperties.class)
public class MybatisPlusConfig {
        @Autowired
        private DataSource dataSource;

        @Autowired
        private MybatisProperties properties;

        @Autowired
        private ResourceLoader resourceLoader = new DefaultResourceLoader();

        @Autowired(required = false)
        private Interceptor[] interceptors;

        @Autowired(required = false)
        private DatabaseIdProvider databaseIdProvider;

        /**
         * 配置事務管理器
         */
        @Bean("transactionManager")
        @Primary
        public DataSourceTransactionManager transactionManager() throws Exception{
            return new DataSourceTransactionManager(dataSource);
        }

        /**
         * mybatis-plus分頁插件
         */
        @Bean
        public PaginationInterceptor paginationInterceptor() {
            //CachePaginationInterceptor page = new CachePaginationInterceptor();
            PaginationInterceptor page = new PaginationInterceptor();
            page.setDialectType(DBType.ORACLE.getDb());
            return page;
        }


        /**
         * 查詢性能分析
         */
    /*@Bean
    public PerformanceInterceptor performanceInterceptor() {
        //CachePaginationInterceptor page = new CachePaginationInterceptor();
        PerformanceInterceptor performanceInterceptor = new PerformanceInterceptor();
        //PaginationInterceptor page = new PaginationInterceptor();
        return performanceInterceptor;
    }
*/

        /**
         * 這裏所有使用mybatis-autoconfigure 已經自動加載的資源。不手動指定
         * 配置文件和mybatis-boot的配置文件同步
         *
         * @return
         */
        @Bean
        public MybatisSqlSessionFactoryBean mybatisSqlSessionFactoryBean() {
            MybatisSqlSessionFactoryBean mybatisPlus = new MybatisSqlSessionFactoryBean();
            mybatisPlus.setDataSource(dataSource);
            mybatisPlus.setVfs(SpringBootVFS.class);
            if (StringUtils.hasText(this.properties.getConfigLocation())) {
                mybatisPlus.setConfigLocation(this.resourceLoader.getResource(this.properties.getConfigLocation()));
            }
            mybatisPlus.setConfiguration(properties.getConfiguration());
            if (!ObjectUtils.isEmpty(this.interceptors)) {
                mybatisPlus.setPlugins(this.interceptors);
            }
            // MP 全局配置,更多內容進入類看註釋
            GlobalConfiguration globalConfig = new GlobalConfiguration();
            globalConfig.setDbType(DBType.ORACLE.name());//數據庫類型
            // ID 策略 AUTO->`0`("數據庫ID自增") INPUT->`1`(用戶輸入ID") ID_WORKER->`2`("全局惟一ID") UUID->`3`("全局惟一ID")
            globalConfig.setIdType(2);
            //MP 屬性下劃線 轉 駝峯 , 若是原生配置 mc.setMapUnderscoreToCamelCase(true) 開啓,該配置能夠無。
            globalConfig.setDbColumnUnderline(true);
            mybatisPlus.setGlobalConfig(globalConfig);
            MybatisConfiguration mc = new MybatisConfiguration();
            // 對於徹底自定義的mapper須要加此項配置,才能實現下劃線轉駝峯
            //mc.setMapUnderscoreToCamelCase(true);
            mc.setDefaultScriptingLanguage(MybatisXMLLanguageDriver.class);
            mybatisPlus.setConfiguration(mc);
            if (this.databaseIdProvider != null) {
                mybatisPlus.setDatabaseIdProvider(this.databaseIdProvider);
            }
            if (StringUtils.hasLength(this.properties.getTypeAliasesPackage())) {
                mybatisPlus.setTypeAliasesPackage(this.properties.getTypeAliasesPackage());
            }
            if (StringUtils.hasLength(this.properties.getTypeHandlersPackage())) {
                mybatisPlus.setTypeHandlersPackage(this.properties.getTypeHandlersPackage());
            }
            if (!ObjectUtils.isEmpty(this.properties.resolveMapperLocations())) {
                mybatisPlus.setMapperLocations(this.properties.resolveMapperLocations());
            }
            return mybatisPlus;
        }
}

 

2.六、下面來配置數據庫DAO層和業務邏輯層;新建Pojo文件。這裏面用到了Mybatisplus的註解內容

package com.justin.model
import com.baomidou.mybatisplus.annotations.TableName;
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
import com.justin.com.LongSerializer;
import java.io.Serializable;

@TableName("TBL_EINVOICE")
public class Einvoice  implements Serializable {
    private static final long serialVersionUID = 1L;

    //id
    private Long id;

    public String getInvoicenum() {
        return invoicenum;
    }

    public void setInvoicenum(String invoicenum) {
        this.invoicenum = invoicenum;
    }

    public String getInvoicecode() {
        return invoicecode;
    }

    public void setInvoicecode(String invoicecode) {
        this.invoicecode = invoicecode;
    }

    private String invoicenum;

    private  String invoicecode;

    /**
     * 設置:id     */

    public void setId(Long id) {
        this.id = id;
    }
    /**
     * 獲取:id     */
    @JsonSerialize(using = LongSerializer.class)
    public Long getId() {
        return id;
    }
}
public class LongSerializer extends JsonSerializer {    
    @Override
    public void serialize(Object value, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) throws IOException, JsonProcessingException {
        jsonGenerator.writeString(value.toString());
    }
}

 

2.七、添加相應DAO,代碼以下,切記EInvoiceMapper要繼承BaseMapper<T>類型,這樣EInvoiceMapper便可實現裏面的諸多方法,好比CRUD

package com.justin.dao;

import com.baomidou.mybatisplus.mapper.BaseMapper;
import com.justin.model.Einvoice;
import org.apache.ibatis.annotations.Param;

public interface EInvoiceMapper extends BaseMapper<Einvoice> {
//    Integer countBy();
    void updatenum(@Param("INUM") String Invoicenum,@Param("ICODE") String Invoicecode);
}

 

同時咱們須要在Resources->Mapper目錄下,新建EInvoiceMapper.xml文件,固然Mapper裏面節點,能夠不用配置映射內容項;若是配置了則要和EInvoiceMapper.java保持一致;

<?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.justin.dao.EInvoiceMapper">
    <!--<select id="countBy"  resultType="int">-->
    <!--SELECT  count(ID) FROM TBL_EINVOICE-->
    <!--</select>-->
    <update id="updatenum">
        UPDATE  TBL_EINVOICE SET INVOICENUM=#{INUM} WHERE INVOICECODE=#{ICODE}
    </update>
</mapper>

 

2.八、如今配置業務邏輯層的Service代碼,新建EinvoiceService.java文件,內容以下,特別注意須要繼承由Mybatisplus提供的IService<T>接口

package com.justin.serviceapi;

import com.baomidou.mybatisplus.service.IService;
import com.justin.model.Einvoice;

public interface EinvoiceService extends IService<Einvoice>
{
    String GetInvoiceNUmByCode(String InvoiceCode);

    /**
     * 插入單個用戶信息
     * @param einvoice
     */
    void insertOne(Einvoice einvoice);

//    //修改代碼結構
   void ChangeCode(String num,String Code);
}

 

添加接口實現項EinvoiceServiceImpl,代碼內容以下。特別注意須要繼承由Mybatisplus提供的ServiceImpl類,同時也要實現EinvoiceService的接口

package com.justin.serviceapi.impl;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.justin.dao.EInvoiceMapper;
import com.justin.model.Einvoice;
import com.justin.serviceapi.EinvoiceService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service("einvoiceservice")
public class EinvoiceServiceImpl extends  ServiceImpl<EInvoiceMapper,Einvoice> implements EinvoiceService
{
    @Autowired
    private  EinvoiceService einvoiceservice;
    @Override
    public String GetInvoiceNUmByCode(String InvoiceCode)
    {

        EntityWrapper<Einvoice> ew = new EntityWrapper<>();
        ew.eq("INVOICECODE", InvoiceCode);
       Einvoice Result= einvoiceservice.selectOne(ew);
       if(Result== null){
           return  "Noting";
       }
       else
       {
           return  Result.getInvoicenum();

       }
    }
    @Override
    public void insertOne(Einvoice einvoice) {
        einvoiceservice.insert(einvoice);
        //baseMapper.SumitEinvocie(einvoice.get());
    }

    public void  ChangeCode(String num,String Code)
    {
//        baseMapper.countBy();
        baseMapper.updatenum(num,Code);
    }

}

 

完成以上配置以後,下面來看Web的入口程序代碼。這個沒什麼可說的,須要而別注意啓動程序類須要添加SpringBootApplication標明是springboot的主程序啓動類;添加ResutController註解是爲了將Body內容直接輸出到瀏覽器裏面;@ResutController和@Controller是有區別的;

package com.justin;
import com.justin.model.Einvoice;
import com.justin.serviceapi.EinvoiceService;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@SpringBootApplication
@RestController
@MapperScan("com.justin.dao")
public class Application
{
    @Autowired
    private EinvoiceService einvoiceservice;

    @RequestMapping("/")
    public  String Greeting()
    {
        return "Justin Say Hello WOrld!";
    }

    @RequestMapping("/Add")
    public  String AddEinvoice()
    {
        Einvoice Einv=new Einvoice();
        Einv.setInvoicecode("98234728");
        Einv.setInvoicenum("1111111");
        einvoiceservice.insertOne(Einv);
        return  "INser SUCC";
    }

    @RequestMapping("/check/{invoicecode}")
    public  String ShowInfo(@PathVariable("invoicecode") String invoicecode)
    {
        return einvoiceservice.GetInvoiceNUmByCode(invoicecode);
    }
    @RequestMapping("/Update/{invoicecode}/{invoicenum}")
    public  String UpInfo(@PathVariable("invoicecode") String invoicecode,@PathVariable("invoicenum") String invoicenum)
    {
        einvoiceservice.ChangeCode(invoicenum,invoicecode);
        return  "SUCC";
    }

    public static void main(String[] args)
    {
        SpringApplication.run(Application.class,args);
    }
}

 

三、thymeleaf使用

3.一、爲了使用thymeleaf提供的模板,咱們須要在pom.xml添加spring-boot-starter-thymeleaf依賴包文件,在Springboot中默認規定靜態文件目錄:/src/java/resources/static;模板文件目錄:/src/java/resources/templates目錄下。因此咱們在templates裏面新建模板文件Eindex.html,內容以下

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
    <title>Title</title>
</head>
<body>
<p th:text="${Message}"></p>
</body>
</html>

 

3.二、爲了使用這個模板,咱們新建一個控制器HelloController,代碼以下

package com.justin.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import java.util.Map;

@Controller
@RequestMapping("/HE")
public class HelloController {

    @RequestMapping("/CIndex")
    public  String HIndex(Map<String,Object> map){

        map.put("Message","from TemplateController.helloHtml");
        return  "Eindex";
    }
}

 

添加完成以後的,最終的項目結構以下

點擊Application運行以後,在瀏覽器裏面輸入 htpp://localhost:812/htc/HE/CIndex  便可預覽本身配置的網頁內容;

thymeleaf可以自動實現映射,可是有些狀況須要注意:

一、若是註解寫的@Controller,則能夠在RequestMapping對應方法返回String類型(也就是html對應名稱便可);

@Controller
@RequestMapping("msg")
public class MessageController {
@RequestMapping("/inTimeMsg/{startSendDate}")
    public String timelyMsg(Map<String, Object> map, @PathVariable("startSendDate") String startSendDate) {
        //消息日期
        if (CommonStringUtils.isNotEmpty(startSendDate)) {
            Map<String, Object> params = new HashMap<>();
            params.put("startSendDate", DateUtil.stringToDate(startSendDate,DateUtil.DF_DATE_TIME));
            params.put("recipientid", ContextHelper.getContext().getUserId());
            params.put("topnum", 15);
            params.put("msgtype", 20);
            List<Message> result = messageService.selectinTimeTopMsg(params);
            if(result.size()>0)
                map.put("msgdataList", result);
        }    
        return "messagelist";
    }
}

 

二、若是註解寫的@RestController,則能夠在RequestMapping對應方法返回ModelAndView類型(也就是html對應名稱和參數);

 

@RestController
@RequestMapping("msg")
public class MessageController {
@RequestMapping("/inTimeMsg/{startSendDate}")
    public ModelAndView timelyMsg(@PathVariable("startSendDate") String startSendDate) {
    Map<String, Object> map=new HashMap<>();
        //消息日期
        if (CommonStringUtils.isNotEmpty(startSendDate)) {
            Map<String, Object> params = new HashMap<>();
            params.put("startSendDate", DateUtil.stringToDate(startSendDate,DateUtil.DF_DATE_TIME));
            params.put("recipientid", ContextHelper.getContext().getUserId());
            params.put("topnum", 15);
            params.put("msgtype", 20);
            List<Message> result = messageService.selectinTimeTopMsg(params);
            if(result.size()>0)
                map.put("msgdataList", result);
        }
        ModelAndView modelAndView=new ModelAndView("messagelist",map);
        return modelAndView;
    }
}
相關文章
相關標籤/搜索