springboot+mybatis整合
今天將springboot和mybatis整合了一下,記錄一下自己的整合過程,都是在網上東拼西湊出來的東西,作為一個簡單的demo還是可以拿來用一用的,以前在2017年12月的時候也整合過一個的,但是年代久遠,而且這個期間也沒有使用springboot,所以一直還停留在入門的階段。
springboot快速的將一些常用的第三方依賴整合(原理:通過Maven子父工程的方式),簡化XML配置,全部採用註解形式,內建Http伺服器(Jetty和Tomcat)。
這個工程主架構是springboot+mybatis,解析頁面是freemark,並用了Generrator根據表名自動生成程式碼
工程目錄介面
pom.xml檔案
<?xml version="1.0" encoding="UTF-8"?>
<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/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.1.6.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>study.springboot</groupId>
<artifactId>demo</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>demo</name>
<description>Demo project for Spring Boot</description>
<properties>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
<version>RELEASE</version>
<scope>compile</scope>
</dependency>
<!-- 引入 freemarker 模板依賴 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-freemarker</artifactId>
</dependency>
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>1.3.2</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.1.10</version>
</dependency>
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.17</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.mybatis.generator/mybatis-generator-core 程式碼生成器-->
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>2.3</version>
</dependency>
<!-- 模板引擎 -->
<dependency>
<groupId>org.apache.velocity</groupId>
<artifactId>velocity-engine-core</artifactId>
<version>2.0</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
application.properties配置檔案
############################################################
#
# freemarker配置
#
############################################################
#模板檔案路徑(不推薦使用)
spring.freemarker.template-loader-path=classpath:/templates
#關閉快取即時重新整理,生產環境需要改成true;
spring.freemarker.cache=false
spring.freemarker.charset=UTF-8
spring.freemarker.check-template-location=true
spring.freemarker.content-type=text/html
spring.freemarker.expose-request-attributes=true
spring.freemarker.expose-session-attributes=true
spring.freemarker.request-context-attribute=request
spring.freemarker.suffix=.html
############################################################
#
# 資料庫 druid配置
#
############################################################
# 資料庫訪問配置
spring.datasource.type=com.alibaba.druid.pool.DruidDataSource
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=gbk&zeroDateTimeBehavior=convertToNull&useSSL=false
spring.datasource.username=root
spring.datasource.password=123456
# 下面為連線池的補充設定,應用到上面所有資料來源中
spring.datasource.initialSize=5
spring.datasource.minIdle=5
spring.datasource.maxActive=20
# 配置獲取連線等待超時的時間
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
# 配置監控統計攔截的filters,去掉後監控介面sql無法統計,'wall'用於防火牆
spring.datasource.filters=stat,wall,log4j
spring.datasource.logSlowSql=true
# 注意:對應實體類的路徑,多個package之間可以用逗號
mybatis.type-aliases-package=study.springboot.demo.bean
#注意:一定要對應mapper對映xml檔案的所在路徑
mybatis.mapper-locations=classpath:mapper/*.xml
#sql日誌輸出
logging.level.study.springboot.demo.dao=debug
controller
package study.springboot.demo.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.stereotype.Controller;
import study.springboot.demo.entity.NovelMain;
import study.springboot.demo.service.NovelMainService;
import java.util.List;
/**
* <p>
* 前端控制器
* </p>
*
* @author wangbiao
* @since 2019-07-25
*/
@Controller
@RequestMapping("/novelMain")
public class NovelMainController {
@Autowired
private NovelMainService novelMainService;
@RequestMapping("/selectNovelList")
public String selectNovelList(Model model){
List<NovelMain> novelMainList = novelMainService.selectNovelList();
model.addAttribute("novelList",novelMainList);
return "novel/novelList";
}
}
service介面
package study.springboot.demo.service;
import study.springboot.demo.entity.NovelMain;
import com.baomidou.mybatisplus.service.IService;
import java.util.List;
/**
* <p>
* 服務類
* </p>
*
* @author wangbiao
* @since 2019-07-25
*/
public interface NovelMainService extends IService<NovelMain> {
List<NovelMain> selectNovelList();
}
service實現類
package study.springboot.demo.service.impl;
import org.springframework.beans.factory.annotation.Autowired;
import study.springboot.demo.entity.NovelMain;
import study.springboot.demo.dao.NovelMainMapper;
import study.springboot.demo.service.NovelMainService;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
import java.util.List;
/**
* <p>
* 服務實現類
* </p>
*
* @author wangbiao
* @since 2019-07-25
*/
@Service
public class NovelMainServiceImpl extends ServiceImpl<NovelMainMapper, NovelMain> implements NovelMainService {
@Autowired
private NovelMainMapper novelMainMapper;
public List<NovelMain> selectNovelList(){
return novelMainMapper.selectList(null);
}
}
dao層
package study.springboot.demo.dao;
import org.springframework.stereotype.Repository;
import study.springboot.demo.entity.NovelMain;
import com.baomidou.mybatisplus.mapper.BaseMapper;
/**
* <p>
* Mapper 介面
* </p>
*
* @author wangbiao
* @since 2019-07-25
*/
@Repository
public interface NovelMainMapper extends BaseMapper<NovelMain> {
}
mybatis map.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="study.springboot.demo.mapper.NovelMainMapper">
<!-- 通用查詢對映結果 -->
<resultMap id="BaseResultMap" type="study.springboot.demo.entity.NovelMain">
<id column="id" property="id" />
<result column="novel_name" property="novelName" />
<result column="author" property="author" />
<result column="novel_type" property="novelType" />
<result column="novel_start_time" property="novelStartTime" />
<result column="word_count" property="wordCount" />
<result column="novel_status" property="novelStatus" />
<result column="create_time" property="createTime" />
<result column="update_time" property="updateTime" />
<result column="novel_pic" property="novelPic" />
</resultMap>
<!-- 通用查詢結果列 -->
<sql id="Base_Column_List">
id, novel_name, author, novel_type, novel_start_time, word_count, novel_status, create_time, update_time, novel_pic
</sql>
</mapper>
前端頁面
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<table border="1" cellspacing="0" cellpadding="0">
<tr>
<td>名稱</td><td>作者</td><td>型別</td><td>開寫時間</td>
</tr>
<#list novelList as novel>
<tr>
<td>${novel.novelName}</td>
<td>${novel.author}</td>
<td>${novel.novelType}</td>
<td>${novel.novelStartTime?string('yyyy-MM-dd HH:mm:ss')}</td>
</tr>
</#list>
</table>
</body>
</html>
程式碼生成器,這個地方生成map.xml檔案不在resources資料夾下的mapper檔案裡,是在study.springboot.demo包下面的mapper資料夾裡,所以生成後,還得將mapper.xml移到resources下面
package study.springboot.demo.main;
import com.baomidou.mybatisplus.enums.IdType;
import com.baomidou.mybatisplus.generator.AutoGenerator;
import com.baomidou.mybatisplus.generator.config.DataSourceConfig;
import com.baomidou.mybatisplus.generator.config.GlobalConfig;
import com.baomidou.mybatisplus.generator.config.PackageConfig;
import com.baomidou.mybatisplus.generator.config.StrategyConfig;
import com.baomidou.mybatisplus.generator.config.rules.DbType;
import com.baomidou.mybatisplus.generator.config.rules.NamingStrategy;
import java.sql.SQLException;
/**
* 程式碼生成器
*/
public class MyBatisPlusGenerator {
public static void main(String[] args) throws SQLException {
//1. 全域性配置
GlobalConfig config = new GlobalConfig();
config.setActiveRecord(true) // 是否支援AR模式
.setAuthor("wangbiao") // 作者
.setOutputDir("/Users/wangbiao/Documents/core/test/springbootstudy/src/main/java") // 生成路徑
.setFileOverride(true) // 檔案覆蓋
.setEnableCache(false) //不要生成二級快取
.setIdType(IdType.AUTO) // 主鍵策略
.setServiceName("%sService") // 設定生成的service介面的名字的首字母是否為I
// IEmployeeService
.setBaseResultMap(true)//生成基本的resultMap
.setBaseColumnList(true);//生成基本的SQL片段
//2. 資料來源配置
DataSourceConfig dsConfig = new DataSourceConfig();
dsConfig.setDbType(DbType.MYSQL) // 設定資料庫型別
.setDriverName("com.mysql.jdbc.Driver")
.setUrl("jdbc:mysql://127.0.0.1:3306/test")
.setUsername("root")
.setPassword("123456");
//3. 策略配置globalConfiguration中
StrategyConfig stConfig = new StrategyConfig();
stConfig.setCapitalMode(true) //全域性大寫命名
.setDbColumnUnderline(true) // 指定表名 欄位名是否使用下劃線
.setNaming(NamingStrategy.underline_to_camel) // 資料庫表對映到實體的命名策略
.setTablePrefix("t_")
.setInclude("t_novel_main"); // 生成的表
//4. 包名策略配置
PackageConfig pkConfig = new PackageConfig();
pkConfig.setParent("study.springboot.demo")
.setMapper("dao")//dao
.setService("service")//servcie
.setController("controller")//controller
.setEntity("entity")//entity
.setXml("mapper");//mapper.xml
//5. 整合配置
AutoGenerator ag = new AutoGenerator();
ag.setGlobalConfig(config)
.setDataSource(dsConfig)
.setStrategy(stConfig)
.setPackageInfo(pkConfig);
//6. 執行
ag.execute();
}
}
啟動工程後控制檯的輸出
用http://localhost:8080/novelMain/selectNovelList訪問頁面
建立表的sql語句
CREATE TABLE `t_novel_main` (
`id` int(11) unsigned NOT NULL AUTO_INCREMENT,
`novel_name` varchar(30) DEFAULT NULL COMMENT '小說名稱',
`author` varchar(30) DEFAULT NULL COMMENT '作者',
`novel_type` varchar(11) DEFAULT NULL COMMENT '小說型別',
`novel_start_time` datetime DEFAULT NULL COMMENT '小說開始時間',
`word_count` int(11) DEFAULT NULL COMMENT '小說字數',
`novel_status` int(11) DEFAULT NULL COMMENT '小說狀態,1:連載,2:完結',
`create_time` datetime DEFAULT NULL,
`update_time` datetime DEFAULT NULL,
`novel_pic` varchar(200) DEFAULT NULL COMMENT '小說圖片',
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8;
下面是工程的下載地址:https://download.csdn.net/download/wangbiao007/11431398
我想將它設成0分下載的,但是沒有看到設定的地方,要下載的小夥伴對不起啦
相關文章
- Springboot+mybatis 整合Spring BootMyBatis
- 基於SpringBoot2.0+優雅整合SpringBoot+MybatisSpring BootMyBatis
- 基於 SpringBoot2.0+優雅整合 SpringBoot+MybatisSpring BootMyBatis
- springboot+mybatisSpring BootMyBatis
- Druid資料來源使用(一)---單獨使用與整合springboot+mybatisUISpring BootMyBatis
- 初學事務管理:SpringBoot+MybatisSpring BootMyBatis
- SpringBoot+Mybatis增刪改查實戰Spring BootMyBatis
- springboot(七):springboot+mybatis多資料Spring BootMyBatis
- springboot+mybatis實現登入功能,返回jsonSpring BootMyBatisJSON
- 基於SpirngBoot2.0+ 的 SpringBoot+Mybatis 多資料來源配置Spring BootMyBatis
- springboot(七):springboot+mybatis多資料來源最簡解決方案Spring BootMyBatis
- 基於註解的springboot+mybatis的多資料來源元件的實現Spring BootMyBatis元件
- 整合持續整合工具
- springboot+mybatis,mapper呼叫查詢的資料為空,報空指標異常Spring BootMyBatisAPP指標
- 【springboot】學習4:整合JDBC、整合druid、整合mybatis、整合 SpringSecuritySpring BootJDBCUIMyBatisGse
- 基於SpringBoot+Mybatis plus+React.js實現條件選擇切換搜尋功能Spring BootMyBatisReactJS
- 基於springboot+mybatis的微信公眾號開發第一篇-基本架構Spring BootMyBatis架構
- SpringBoot整合系列-整合JPASpring Boot
- MyBatis(九) 整合Spring、整合SpringMVCMyBatisSpringMVC
- SSM整合之CRUD環境搭建整合SSM
- ssm整合SSM
- SpringBoot整合系列-整合H2Spring Boot
- RestCloud iPaaS混合整合平臺,資料整合RESTCloud
- SpringBoot整合系列–整合MyBatis-plusSpring BootMyBatis
- 整合學習(一):簡述整合學習
- SSH框架整合配置所需JAR包(SSH整合)框架JAR
- 自動化整合:Pipeline整合Docker容器Docker
- ETL資料整合,RestCloud資料整合平臺RESTCloud
- Win10整合Cortana,Mac何時整合Siri?Win10Mac
- Spring AI與大模型Ollama如何整合整合?SpringAI大模型
- Vue整合UeditorVue
- SSM框架整合SSM框架
- Vuex之整合Vue
- CodePush整合
- 整合SSM框架SSM框架
- Spark整合hiveSparkHive
- Vitis AI 整合AI
- SSH框架整合框架