Springboot整合mybatis註解版實現
一、前言
Springboot的使用極大程度上減少了相關檔案的配置,將繁瑣的類似於spring+mybatis+spring mvc的配置簡化到只需要一些簡單的資料庫資源連結資源配置,剩下的相關配置都交給了maven和spring initializr完成。本文在給予Springboot的mybatis平臺下加入了郵件傳送。本文在intellij idea2017、jdk1.8環境下完成。
二、專案具體建立
1.建立springboot專案
這裡建立好了專案demo之後就開始建立檔案的目錄,瞭解專案結構。
2.整個專案結果如下:
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> <groupId>com.springboot</groupId> <artifactId>mysql</artifactId> <version>0.0.1-SNAPSHOT</version> <packaging>war</packaging> <name>mysql</name> <description>Demo project for Spring Boot</description> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>2.0.2.RELEASE</version> <relativePath/> <!-- lookup parent from repository --> </parent> <properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding> <java.version>1.8</java.version> </properties> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-redis</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-jdbc</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-thymeleaf</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.mybatis.spring.boot</groupId> <artifactId>mybatis-spring-boot-starter</artifactId> <version>1.3.2</version> </dependency> <dependency> <groupId>org.springframework.kafka</groupId> <artifactId>spring-kafka</artifactId> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <scope>runtime</scope> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-tomcat</artifactId> <scope>provided</scope> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> <!-- 新增JSP依賴 --> <!--<dependency> <groupId>org.apache.tomcat.embed</groupId> <artifactId>tomcat-embed-jasper</artifactId> <scope>provided</scope> </dependency> <dependency> <groupId>javax.servlet</groupId> <artifactId>jstl</artifactId> </dependency>--> <dependency> <groupId>redis.clients</groupId> <artifactId>jedis</artifactId> <version>2.9.0</version> </dependency> <!-- spring boot for mail --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-mail</artifactId> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> </plugins> </build> </project>
專案資源配置檔案application.properties
#mysql資料庫配置(資料庫相關配置很重要,密碼、地址、使用者名稱都需要在正確的情況下使用) spring.datasource.url=jdbc:mysql://localhost:3306/springboot spring.datasource.username=root spring.datasource.password=root spring.datasource.driver-class-name=com.mysql.jdbc.Driver # 配置列印SQL語句日誌 logging.pattern.level=%5p logging.level.com.springboot.dao.UserMapper=DEBUG logging.level.org.springframework=WARN logging.file=D:/logs/log.log # 配置redis快取資料庫 spring.redis.database=0 spring.redis.host=localhost spring.redis.port=6379 spring.redis.password=your password # redis預設密碼為空 spring.redis.jedis.pool.max-idle=10 spring.redis.jedis.pool.min-idle=0 spring.redis.jedis.pool.max-active=8 spring.redis.jedis.pool.max-wait=-1 spring.redis.timeout=0 # spring boot整合郵件mail spring.mail.host=smtp.qq.com spring.mail.port=587 spring.mail.username=your mail address # 此處的密碼就是QQ郵箱的授權碼,不是登入密碼 spring.mail.password=授權碼 spring.mail.properties.mail.smtp.auth=true #spring.mail.password=郵箱登入密碼 spring.mail.default-encoding=UTF-8
3.建立service、dao、domain、web、config相關介面與實現類
UserService.java
package com.springboot.service;
import com.springboot.dao.UserMapper;
import com.springboot.domain.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
@Service
public class UserService {
@Autowired
private UserMapper userMapper;
public User findById(String id) {
return userMapper.findById(id);
}
public int addUser(String name, String age) {
return userMapper.addUser(name, age);
}
public void updataById(String id, String name) {
userMapper.updataById(id, name);
}
public void deleteById(String id) {
userMapper.deleteById(id);
}
public List<User> findAllUser() {
return userMapper.findAllUser();
}
}
UserMapper.java
package com.springboot.dao;
import com.springboot.domain.User;
import org.apache.ibatis.annotations.*;
import java.util.List;
@Mapper
public interface UserMapper {
@Insert("insert into user(name,age) values(#{name},#{age})")
int addUser(@Param("name") String name, @Param("age") String age);
@Select("select * from user where id =#{id}")
User findById(@Param("id") String id);
@Update("update user set name=#{name} where id=#{id}")
void updataById(@Param("id") String id, @Param("name") String name);
@Delete("delete from user where id=#{id}")
void deleteById(@Param("id") String id);
@Select("select * from user")
List<User> findAllUser();
}
User.java
package com.springboot.domain;
public class User {
private String id;
private String name;
private String age;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAge() {
return age;
}
public void setAge(String age) {
this.age = age;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
@Override
public String toString() {
StringBuilder builder = new StringBuilder();
builder.append("序號:").append(id)
.append(";姓名:").append(name)
.append(";年齡:").append(age);
return builder.toString();
}
}
UserController.java
package com.springboot.web;
import com.springboot.domain.User;
import com.springboot.service.MailService;
import com.springboot.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import java.util.List;
@Controller
public class UserController {
@Autowired
private UserService userService;
@Autowired
private MailService mailService;
@RequestMapping(value = "/addUser")
public String addUser(@RequestParam("name") String name, @RequestParam("age") String age) {
int num = userService.addUser(name, age);
if (num == 1)
return "redirect:/allUser";
else
return "Insert Error";
}
@RequestMapping(value = "/findUser")
public String findUser(Model model, @RequestParam("id") String id) {
User user = userService.findById(id);
model.addAttribute("userList", user);
return "index";
}
@RequestMapping(value = "/updateById")
public String updateById(@RequestParam("id") String id, @RequestParam("name") String name) {
try {
userService.updataById(id, name);
} catch (Exception e) {
return "error";
}
return "redirect:/allUser";
}
@RequestMapping(value = "/deleteById")
public String deleteById(@RequestParam("id") String id) {
try {
userService.deleteById(id);
} catch (Exception e) {
return "error";
}
return "redirect:/allUser";
}
@RequestMapping(value = "/allUser")
public String findAllUser(Model model) {
List<User> userList = userService.findAllUser();
model.addAttribute("userList", userList);
StringBuilder builder = new StringBuilder();
for (User user : userList) {
if (user != null) {
builder.append(user.toString()).append("<br>");
}
}
String content = builder.toString();
// sendMail(content);
return "index";
}
public void sendMail(String content) {
String mailTo = "[email protected]";
String subject = "springboot測試郵件傳送!";
mailService.sendHtmlMail(mailTo, subject, content);
}
}
關於郵件傳送相關介面和實現類如下:
MailService.java
package com.springboot.service;
public interface MailService {
/**
* 傳送簡單郵件
*
* @param to
* @param subject
* @param content
*/
void sendSimpleEmail(String to, String subject, String content);
/**
* 傳送html郵件
*
* @param to
* @param subject
* @param content
*/
void sendHtmlMail(String to, String subject, String content);
/**
* 傳送帶附件的郵件
*
* @param to
* @param subject
* @param content
* @param filepath
*/
void sendFileMail(String to, String subject, String content, String filepath);
/**
* 使用模板來發送郵件
*
* @param to
* @param subject
*/
void sendTemplateMail(String to, String subject);
}
MailServiceImpl.java
package com.springboot.service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.FileSystemResource;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Component;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;
import javax.annotation.Resource;
import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import java.io.File;
@Component
public class MailServiceImpl implements MailService {
@Autowired
private JavaMailSender mailSender;
@Resource
private TemplateEngine templateEngine;
@Value("${spring.mail.username}")
private String mailFrom;
/**
* 傳送簡單郵件
*
* @param to
* @param subject
* @param content
*/
@Override
public void sendSimpleEmail(String to, String subject, String content) {
SimpleMailMessage message = new SimpleMailMessage();
message.setFrom(mailFrom);
message.setTo(to);
message.setSubject(subject);
message.setText(content);
mailSender.send(message);
}
/**
* 傳送html郵件
*
* @param to
* @param subject
* @param content
*/
@Override
public void sendHtmlMail(String to, String subject, String content) {
MimeMessage mimeMessage = mailSender.createMimeMessage();
try {
//true表示需要建立一個multipart message
MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true);
helper.setFrom(mailFrom);
helper.setTo(to);
helper.setSubject(subject);
helper.setText(content, true);
mailSender.send(mimeMessage);
} catch (MessagingException e) {
e.printStackTrace();
}
}
/**
* 傳送帶附件的郵件
*
* @param to
* @param subject
* @param content
* @param filepath
*/
@Override
public void sendFileMail(String to, String subject, String content, String filepath) {
MimeMessage mimeMessage = mailSender.createMimeMessage();
try {
MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true);
helper.setFrom(mailFrom);
helper.setTo(to);
helper.setSubject(subject);
helper.setText(content, true);
FileSystemResource file = new FileSystemResource(new File(filepath));
String fileName = filepath.substring(filepath.lastIndexOf(File.separator));
helper.addAttachment(fileName, file);
mailSender.send(mimeMessage);
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 使用模板來發送郵件
*
* @param to
* @param subject
*/
@Override
public void sendTemplateMail(String to, String subject) {
Context context = new Context();
context.setVariable("username", "jantent");
String mailHtml = templateEngine.process("mail", context);
sendHtmlMail(to, subject, mailHtml);
}
}
然而最核心的類就是xxApplication.java類,如下MySQLApplication.java:
package com.springboot;
import com.springboot.utils.LoggerUtils;
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;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import java.util.logging.Level;
@RestController
@SpringBootApplication
public class MysqlApplication {
@Autowired
private JedisPool jedisPool;
public static void main(String[] args) {
SpringApplication.run(MysqlApplication.class, args);
}
@RequestMapping(value = "/", produces = "text/plain;charset=UTF-8")
String index() {
LoggerUtils loggerUtils = new LoggerUtils(Level.INFO, MysqlApplication.class.getName(), "專案已經啟動了,這是列印的Logging...");
loggerUtils.loggerOutput();
return "Hello Spring boot!\n";
}
@RequestMapping(value = "/redis/{key}")
public String testRedis(@PathVariable("key") String key) {
Jedis jedis = jedisPool.getResource();
return jedis.get(key);
}
}
簡單實用thymeleaf模板的html5
index.html
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:th="http://www.thymeleaf.org">
<head>
<meta datatype="application/json">
<title>Springboot使用者</title>
</head>
<body>
<h1 th:inline="text">第一個SpringBoot靜態介面</h1>
<table border="1" bordercolor="#a0c6e5" style="border-collapse:collapse;">
<thead>
<tr>
<th>id序號</th>
<th>姓名</th>
<th>年齡</th>
<th>操作</th>
</tr>
</thead>
<tbody th:each="user:${userList}">
<tr th:id="${user.id}">
<td th:text="${user.id}"></td>
<td th:text="${user.name}"></td>
<td th:text="${user.age}"></td>
<td><a th:href="@{/deleteById(id=${user.id})}">刪除</a></td>
</tr>
</tbody>
</table>
<br>
</body>
</html>
三、執行結果簡單展示
這裡介面就僅僅只展示幾個簡單的初始介面,後期像豐富實現不同業務再做補充。
四、總結
本文主要目的就是記錄Springboot整合mybatis實現簡單的一些業務操作,後期根據需求豐富;記錄專案的建立以及整個流程的走通,僅供自己以後複習和各位有需要的朋友參考。本文在springboot和mybatis的基礎下加入了redis的操作,使用了thymeleaf模板,郵件mail的簡單操作,本身還是存在很多不足,希望各位朋友提出改進意見和建議,大家一起學習一起進步!!!
相關推薦
Springboot整合mybatis註解版實現
一、前言 Springboot的使用極大程度上減少了相關檔案的配置,將繁瑣的類似於spring+mybatis+spring mvc的配置簡化到只需要一些簡單的資料庫資源連結資源配置,剩下的相關配置都交給了maven和spring initializr完成。本文在給予Spr
SpringBoot整合Mybatis註解版---update出現org.apache.ibatis.binding.BindingException: Parameter 'XXX' not found. Available parameters are [arg1, arg0,
SpringBoot整合Mybatis註解版---update時出現的問題 問題描述: 1、sql建表語句 DROP TABLE IF EXISTS `department`; CREATE TABLE `department` ( `id` int(11) NOT NULL AUTO_I
SpringBoot整合Mybatis註解版---update出現org.apache.ibatis.binding.BindingException: Parameter 'XXX' not found. Available parameters are
SpringBoot整合Mybatis註解版---update時出現的問題 問題描述: 1、sql建表語句 DROP TABLE IF EXISTS `department`; CREATE TABLE `department` ( `id` int(11) NOT NULL AUTO_INCREMEN
SpringBoot整合MyBatis(註解版+XML配置版)
一.公共部分 1.建立SpringBoot專案,加入依賴 <?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xs
springboot整合mybatis註解開發,thymeleaf的簡單使用
1、前言 之前玩過使用xml配置檔案整合mybatis,這次為了整合thymeleaf模板,選用簡單的註解完成資料庫的查詢。整合工具無非是引入依賴,新增配置完成此相關功能。玩過之後,記錄一下學習的過程,以備後續使用。 2、依賴引入 使用springboot開發,建議裝上springboo
SpringBoot整合Mybatis【註解版】
一、專案建立 新建一個工程 選擇Spring Initializr,配置JDK版本 輸入專案名 選擇構建web專案所需的staters(啟動器) 選擇與資料庫相關的元件 分
SpringBoot整合Mybatis【非註解版】
接上文:SpringBoot整合Mybatis【註解版】 一、專案建立 新建一個工程 選擇Spring Initializr,配置JDK版本 輸入專案名 選擇構建web專案所需的
SpringBoot整合Mybatis的簡單例子(註解版)
1. 資料庫準備 a.建立資料庫 CREATE DATABASE test_logistics; b.建立表 create table wh_user ( userId int auto_increment primary key com
SpringBoot 整合使用MyBatis註解版
一、簡介 自從 Java 1.5 開始引入了註解,註解便被廣泛地應用在了各種開源軟體中,使用註解大大地降低了系統中的配置項,讓程
SpringBoot整合Mybatis實現增刪改查的功能
ger 開始 pan ble img 映射 講師 -name date SpringBoot框架作為現在主流框架之一,好多框架都漸漸的移植到SpringBoot中來。前面我給大家介紹過redis,jpa等等的的整合,今天在這裏給大家介紹一下Mybatis的整合過程。 S
springboot整合mybatis(映射文件方式和註解方式)
分頁 character 訪問 runt mod tis 1.2 req arch springboot作為一個微服務框架,給我們開發人員提供極大的便利,秉著約定大於配置的原則,通過starter包的形式為我們做了許多默認的配置,在進行數據持久化到關系型數據庫時,我們一
SpringBoot整合Mybatis實現簡單的CRUD(2)
思考 看了上面一步步的講解。你應該明白了,其實和SSM階段的CRUD基本相同,這裡我就不再舉例其他方法。 下面我們講解一下不同的地方: 實現頁面跳轉 因為Thymeleaf指定的目錄src/main/resources/templates/是受保護的目錄,其下的資源不能直接通過瀏
springboot整合mybatis實現增刪改查流程以及易錯點
Springboot+mybatis+mysql實現增刪改查操作。 在昨天學習的springboot的入門程式上進行擴充套件開發。首先建立好專案目錄結構,如圖: 整個流程類似ssm整合,controller—》service—》dao ,介面訪問xml。這個寫完的結構
Springboot整合mybatis實現多資料來源
1:SpringBoot整合mybatis實現多資料來源有兩種方法 1:靜態方式 將每個資料來源都實現一個mybatis的sqlSessionFactory中,但是這種方法,缺點在於:你有幾個資料來源都會有幾個mybatis的配置類;對於資料來源的事務也不是很
SpringBoot-15-之整合MyBatis-註解篇+分頁
0.相關配置 pom.xml <!--mysql依賴--> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java&
SpringBoot整合mybatis、shiro、redis實現基於資料庫的細粒度動態許可權管理系統例項
1.前言 本文主要介紹使用SpringBoot與shiro實現基於資料庫的細粒度動態許可權管理系統例項。 使用技術:SpringBoot、mybatis、shiro、thymeleaf、pagehelper、Mapper外掛、druid、dataTables
SpringBoot整合Mybatis自定義攔截器,實現拼接sql和修改
一、應用場景 1.分頁,如com.github.pagehelper的分頁外掛實現; 2.攔截sql做日誌監控; 3.統一對某些sql進行統一條件拼接,類似於分頁。 二、MyBatis的攔截器簡介 然後我們要知道攔截器攔截什麼樣的物件,攔截物件的什麼行為,什麼時候攔截? &n
Spring boot+ Mybatis 完美整合之註解版
開發環境: 開發工具:Intellij IDEA 2017.1.3JDK : 1.8.0_101spring boot 版本 : 1.5.8.RELEASEmaven : 3.3.9 拓展: springboot 整合 Mybatis 事務管理 開始 1.新建一個spr
SpringBoot實現Redis(非註解版實現,註解在有些地方使用不了)
Springboot整合redis非常簡單,如下,作者指出一種簡單的實現方式 import com.fasterxml.jackson.annotation.JsonAutoDetect; import com.fasterxml.jackson.annotation.P