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的简单操作,本身还是存在很多不足,希望各位朋友提出改进意见和建议,大家一起学习一起进步!!!

附:demo下载地址

猜你喜欢

转载自blog.csdn.net/u010318474/article/details/81143594