java实训笔记_SpringBoot整合MyBatis(含逆向工程)

1 前言

上一篇介绍了 SpringBoot的一点知识
这一篇介绍SpringBoot整合MyBatis。
注:mysql版本为5.5.40

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 https://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.3.1.RELEASE</version>
		<relativePath /> <!-- lookup parent from repository -->
	</parent>
	<groupId>net.seehope</groupId>
	<artifactId>springboot-hello</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<name>springboot-hello</name>
	<description>Demo project for Spring Boot</description>

	<properties>
		<java.version>1.8</java.version>
	</properties>

	<dependencies>
		<!--springboot开发web项目的起步依赖 -->
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-web</artifactId>
		</dependency>
		<!-- mybatis依赖 -->
		<dependency>
			<groupId>org.mybatis.spring.boot</groupId>
			<artifactId>mybatis-spring-boot-starter</artifactId>
			<version>1.3.1</version>
		</dependency>
		<!-- mysql依赖 -->
		<dependency>
			<groupId>mysql</groupId>
			<artifactId>mysql-connector-java</artifactId>
			<version>5.1.28</version>
		</dependency>
		<!-- mybatis逆向工程 -->
		<dependency>
			<groupId>org.mybatis.generator</groupId>
			<artifactId>mybatis-generator-core</artifactId>
			<version>1.3.2</version>
			<scope>compile</scope>
			<optional>true</optional>
		</dependency>
		<dependency>
			<groupId>tk.mybatis</groupId>
			<artifactId>mapper-spring-boot-starter</artifactId>
			<version>1.2.4</version>
		</dependency>
		<dependency>
			<groupId>org.mybatis.generator</groupId>
			<artifactId>mybatis-generator-core</artifactId>
			<version>1.3.7</version>
		</dependency>
		<dependency>
			<groupId>org.freemarker</groupId>
			<artifactId>freemarker</artifactId>
			<version>2.3.28</version><!--$NO-MVN-MAN-VER$ -->
		</dependency>
		<!-- 开启springboot的tomcat热部署 true就是开启 -->
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-devtools</artifactId>
			<optional>true</optional>
		</dependency>

		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-test</artifactId>
			<scope>test</scope>
			<exclusions>
				<exclusion>
					<groupId>org.junit.vintage</groupId>
					<artifactId>junit-vintage-engine</artifactId>
				</exclusion>
			</exclusions>
		</dependency>

	</dependencies>

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

3 配置文件

3.1 jdbc.properties

jdbc.username=root
jdbc.password=
jdbc.url=jdbc:mysql://localhost:3306/myssm?useUnicode=true&characterEncoding=utf-8&serverTimezone=UTC
jdbc.driverClassName=com.mysql.jdbc.Driver

3.2 application.yml

spring:
  datasource:
    url: jdbc:mysql://localhost:3306/myssm?useUnicode=true&characterEncoding=utf-8&serverTimezone=UTC
    username: root
    password:
    driver-class-name: com.mysql.jdbc.Driver
    druid:
      initial-size: 1
      min-idle: 1
      max-active: 20
      test-on-borrow: true
      stat-view-servlet:
        allow: true

3.3 mybatis-generator-config.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>
	<properties resource="jdbc.properties" />

	<context id="Mysql" targetRuntime="MyBatis3Simple"
		defaultModelType="flat">
		<property name="javaFileEncoding" value="UTF-8" />
		<!--配置是否使用通用 Mapper 自带的注释扩展,默认 true -->
		<!--<property name="useMapperCommentGenerator" value="false"/> -->

		<!-- 生成的pojo类自带序列化接口 -->
		<plugin type="org.mybatis.generator.plugins.SerializablePlugin"></plugin>

		<!--通用 Mapper 插件,可以生成带注解的实体类 -->
		<plugin type="tk.mybatis.mapper.generator.MapperPlugin">
			<property name="mappers"
				value="tk.mybatis.mapper.common.Mapper,tk.mybatis.mapper.hsqldb.HsqldbMapper" />
			<property name="caseSensitive" value="true" />
			<property name="forceAnnotation" value="true" />
			<property name="beginningDelimiter" value="`" />
			<property name="endingDelimiter" value="`" />
		</plugin>

		<!--通用代码生成器插件 -->
		<!--mapper接口 -->
		<!-- ../maker-assistant-service/src/test/java -->
		<plugin type="tk.mybatis.mapper.generator.TemplateFilePlugin">
			<property name="targetProject" value="src/test/java" />
			<property name="targetPackage"
				value="com.example.demo.mapper" />
			<property name="templatePath" value="generator/mapper.ftl" />
			<property name="mapperSuffix" value="Mapper" />
			<property name="fileName"
				value="${tableClass.shortClassName}${mapperSuffix}.java" />
		</plugin>
		<!--mapper.xml -->
		<plugin type="tk.mybatis.mapper.generator.TemplateFilePlugin">
			<property name="targetProject" value="src/test/java" />
			<property name="targetPackage" value="com.example.demo.mapper" />
			<property name="mapperPackage"
				value="com.example.demo.mapper" />
			<property name="templatePath"
				value="generator/mapperXml.ftl" />
			<property name="mapperSuffix" value="Mapper" />
			<property name="fileName"
				value="${tableClass.shortClassName}${mapperSuffix}.xml" />
		</plugin>
		<!--测试输出单个文件,每个表都会生成一个对应的文件 -->
		<plugin type="tk.mybatis.mapper.generator.TemplateFilePlugin">
			<property name="targetProject" value="src/test/resources" />
			<property name="targetPackage" value="generator.one" />
			<property name="templatePath" value="generator/test-one.ftl" />
			<property name="fileName"
				value="${tableClass.shortClassName}Test.txt" />
			<!--默认值是下面这个,可以不配置 -->
			<property name="templateFormatter"
				value="tk.mybatis.mapper.generator.formatter.FreemarkerTemplateFormatter" />
		</plugin>
		<!--测试输出整个文件,所有表都可用,一次只生成一个文件,用于聚合所有表使用 -->
		<plugin type="tk.mybatis.mapper.generator.TemplateFilePlugin">
			<property name="singleMode" value="false" />
			<property name="targetProject" value="src/test/resources" />
			<property name="targetPackage" value="generator" />
			<property name="templatePath" value="generator/test-all.ftl" />
			<property name="fileName" value="TestAll.txt" />
		</plugin>

		<jdbcConnection driverClass="${jdbc.driverClassName}"
			connectionURL="${jdbc.url}" userId="${jdbc.username}"
			password="${jdbc.password}">
			<property name="nullCatalogMeansCurrent" value="true" />
		</jdbcConnection>

		<!--MyBatis 生成器只需要生成 Model -->
		<javaModelGenerator
			targetPackage="com.example.demo.pojo"
			targetProject="./src/test/java" />

		<table tableName="admin">
		</table>
		<table tableName="user">
		</table>
	</context>
</generatorConfiguration>

4 运行

4.1 MybatisGenerator.java

运行此类以生成mybatis的mapper和pojo

import java.util.ArrayList;
import java.util.List;

import org.apache.ibatis.io.Resources;
import org.mybatis.generator.api.MyBatisGenerator;
import org.mybatis.generator.config.Configuration;
import org.mybatis.generator.config.xml.ConfigurationParser;
import org.mybatis.generator.internal.DefaultShellCallback;

/**
 * <b>Description:</b><br>
 * 
 * @author <a href="www.mtproject.cn" target="_blank">Monty</a>
 * @version 1.0
 * @Note <b>ProjectName:</b> mybatis-generator <br>
 *       <b>PackageName:</b> net.seehope.util <br>
 *       <b>ClassName:</b> MybatisGenerator <br>
 *       <b>Date:</b> Jul 1, 2019 11:05:09 AM
 */
public class MybatisGenerator {
	public static void main(String[] args) {
		try {
			generate();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	public static void generate() throws Exception {
		List<String> warnings = new ArrayList<String>();
		boolean overwrite = true;
		ConfigurationParser cp = new ConfigurationParser(warnings);
		Configuration config = cp.parseConfiguration(Resources.getResourceAsStream("mybatis-generator-config.xml"));
		DefaultShellCallback callback = new DefaultShellCallback(overwrite);
		MyBatisGenerator myBatisGenerator = new MyBatisGenerator(config, callback, warnings);
		myBatisGenerator.generate(null);
		for (String warning : warnings) {
			System.out.println(warning);
		}
	}

	public static void generate(String configPath) throws Exception {
		List<String> warnings = new ArrayList<String>();
		boolean overwrite = true;
		ConfigurationParser cp = new ConfigurationParser(warnings);
		Configuration config = cp.parseConfiguration(Resources.getResourceAsStream(configPath));
		DefaultShellCallback callback = new DefaultShellCallback(overwrite);
		MyBatisGenerator myBatisGenerator = new MyBatisGenerator(config, callback, warnings);
		myBatisGenerator.generate(null);
		for (String warning : warnings) {
			System.out.println(warning);
		}
	}
}

4.2 DemoApplication.java

运行此类以启动SpringBoot

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

import tk.mybatis.spring.annotation.MapperScan;

@SpringBootApplication
@MapperScan("com.example.demo.mapper")
public class DemoApplication {

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

}

4.3 UserService接口

import com.example.demo.pojo.User;

public interface UserService {
	public User findUserById(int id);
}

4.4 UserServiceImpl.java

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.example.demo.mapper.UserMapper;
import com.example.demo.pojo.User;
import com.example.demo.service.UserService;
@Service
public class UserServiceImpl implements UserService{
	@Autowired
	UserMapper userMapper;

	@Override
	public User findUserById(int id) {
		return userMapper.selectByPrimaryKey(String.valueOf(id));
	}
}

4.5 HelloController.java

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import com.example.demo.service.UserService;

@Controller
public class HelloController {
	@Autowired
	UserService userService;
	
	@RequestMapping("hello")
	public String hello() {
		System.out.println(userService.findUserById(1).getUsername());
		return "index.html";
	}
}

4.6 浏览器访问结果

在这里插入图片描述

4.7 控制台输出

在这里插入图片描述
上面是SpringBoot启动时的提示信息,最后一行是查询结果。

5 项目结构

在这里插入图片描述
test中的包用于存放逆向工程生成的文件,生成后手动拷贝至main中。

6 结语

使用SpringBoot极大地简化了配置文件的书写,非常方便,但是如果使用HBuilder写网页,RapidClipse写后台的话,单独更改网页内容不会触发Spring Boot的热部署,需要更改RapidClipse中的内容触发或者直接重新运行DemoApplication。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值