SpringBoot+MyBatis+Generator整合框架案例
简介
Spring Boot建立在现有spring框架之上,整合了很多优秀的框架,不再需要定义样板化的配置,简化了新Spring应用的初始搭建以及开发过程。它不需要添加各种依赖,通过起步依赖就能直接引入需要的库,也不需要配置繁杂的xml文件,直接使用各种控制层注解。
MyBatis 是一款优秀的持久层框架,它支持定制化 SQL、存储过程以及高级映射。MyBatis 避免了几乎所有的 JDBC 代码和手动设置参数以及获取结果集。MyBatis 可以使用简单的 XML 或注解来配置和映射原生信息,将接口和 Java 的 POJOs(Plain Old Java Objects,普通的 Java对象)映射成数据库中的记录。
mybatis-generator是一款在使用mybatis框架时,自动生成model,dao和mapper的工具,可以减少开发人员的手动编码时间。
开发环境
数据库:Navicat Premium_11.2.7
编译器:IntelliJ IDEA 2018.3.5
Java环境:Jdk1.8.0_201
Maven工具:apache-maven-3.3.9
MySQL驱动:mysql-connector-java-5.1.47.jar (用于逆向工程使用)
Genarator 插件:mybatis-generator-maven-plugin
测试工具:Postman
generator逆向工程
一、 创建项目
使用IDEA创建Project。打开IDEA,选择File→New→Project→Spring Initializr。然后Next下一步。
填写坐标信息,Group可填你所在公司名,Artifact为项目名。然后Next下一步。
在Web项选择Spring Web Starter,在SQL项选择MyBatis Framework、MySQL Driver。然后Next下一步。
填写项目存放路径,然后选择Finish结束。
二、创建需要自动生成的测试表
打开Navicat ,新建数据库并创建user表,然后给user表插入测试数据。
1、新建数据库
create database example;
2、创建user表
CREATE TABLE `user`(
`user_id` int(11) NOT NULL auto_increment,
`user_name` varchar(255) NOT NULL,
`user_age` varchar(255) default NULL,
`user_address` varchar(255) default NULL,
PRIMARY KEY (`user_id`)
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8;
3、user表插入数据
三、使用mybatis-generator自动生成代码
1、添加Generator插件
修改项目的pom.xml文件,添加Generator插件
具体代码如下:
<!-- 添加generator插件 -->
<plugin>
<groupId>org.mybatis.generator</groupId>
<artifactId>mybatis-generator-maven-plugin</artifactId>
<configuration>
<configurationFile>${basedir}/src/main/resources/generatorConfig.xml</configurationFile>
<overwrite>true</overwrite>
<verbose>true</verbose>
</configuration>
</plugin>
2、添加mysql驱动器版本
在pom.xml文件中找到mysql驱动器的位置,并添加版本信息。
3、配置application.properties
在src/main/resource下找到application.properties文件,并在里面添加配置
具体配置如下:
#修改Tomcat的端口配置:
server.port=8711
#mysql驱动类
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
#连接数据库
spring.datasource.url=jdbc:mysql://localhost:3306/example?useUnicode=true&characterEncoding=UTF-8&autoReconnect=true&useSSL=false&zeroDateTimeBehavior=convertToNull
spring.datasource.username=root
spring.datasource.password=
#通过配置mapperLocations指定mapper.xml的位置,扫描mapper.xml文件
mybatis.mapperLocations=classpath:mapper/*.xml
4、创建generatorConfig.xml
在resource目录下新建File文件,并命名为generatorConfig.xml,配置
generatorConfig.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>
<!-- 数据库驱动:换成你本地的驱动包位置-->
<classPathEntry location="C:/Users/LT-0167/.IntelliJIdea2018.3/config/jdbc-drivers/MySQL Connector/J/5.1.47/mysql-connector-java-5.1.47.jar"/>
<context id="DB2Tables" targetRuntime="MyBatis3">
<commentGenerator>
<property name="suppressDate" value="true"/>
<!-- 是否去除自动生成的注释 true:是 : false:否 -->
<property name="suppressAllComments" value="true"/>
</commentGenerator>
<!--数据库链接URL、用户名、密码 -->
<jdbcConnection driverClass="com.mysql.jdbc.Driver" connectionURL="jdbc:mysql://localhost:3306/example?useSSL=false" userId="root" password="">
</jdbcConnection>
<javaTypeResolver>
<property name="forceBigDecimals" value="false"/>
</javaTypeResolver>
<!-- 生成模型的包名和位置-->
<javaModelGenerator targetPackage="com.bfd.example.entity" targetProject="src/main/java">
<property name="enableSubPackages" value="true"/>
<property name="trimStrings" value="true"/>
</javaModelGenerator>
<!-- 生成映射文件的包名和位置-->
<sqlMapGenerator targetPackage="mapper" targetProject="src/main/resources">
<property name="enableSubPackages" value="true"/>
</sqlMapGenerator>
<!-- 生成DAO的包名和位置-->
<javaClientGenerator type="XMLMAPPER" targetPackage="com.bfd.example.dao" targetProject="src/main/java">
<property name="enableSubPackages" value="true"/>
</javaClientGenerator>
<!-- 要生成的表 tableName是数据库中的表名或视图名 domainObjectName是实体类名-->
<table tableName="user" enableCountByExample="User" enableUpdateByExample="false" enableDeleteByExample="false" enableSelectByExample="false" selectByExampleQueryId="false"/>
</context>
</generatorConfiguration>
5、运行generatorConfig.xml
运行创建的generatorConfig.xml文件,自动生成entity、dao和mapper代码,
生成位置为generatorConfig.xml文件中指定的路径。
在IDEA工具的顶部选择Run→ Edit Configurations,在其左上角“+”号里添加
Maven,并在Command line中填写 mybatis-generator:generate -e,选择
Apply→ok。回到idea顶部选择 Run→ Run ‘xxx [mybatis-generator:generate e]’
来运行generatorConfig.xml文件。
在generatorConfig.xml文件中指定的位置查看自动生成的代码:
测试实例
一、定义User实体对象集合
1、在UserMapper.java中添加:
List<User> getUserName();
2、在接口名上添加@Mapper注解(一定注意添加,否则会扫描不到D ao.UserMapper)
二、修改UserMapper.xml文件
在UserMapper.xml文件中为UserMapper.java写的方法添加查询语句,id名与方法名一致。
<select id="getUserName" resultMap="BaseResultMap">
select * from user
</select>
如图所示:
三、service层和controller层的编写与实现
1、编写service及其实现(注意一定要加上注解)
package com.bfd.example.service;
import org.springframework.stereotype.Component;
@Component
public interface UserNameService {
String getUserName();
}
package com.bfd.example.service.Impl;
import com.alibaba.fastjson.JSON;
import com.bfd.example.dao.UserMapper;
import com.bfd.example.entity.User;
import com.bfd.example.service.UserNameService;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import java.util.List;
@Service
public class UserNameServiceImpl implements UserNameService {
@Resource
UserMapper mapper;
@Override
public String getUserName(){
List<User> userName = mapper.getUserName();
return JSON.toJSONString(userName);
}
}
2、编写controller
package com.bfd.example.controller;
import com.bfd.example.service.*;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import javax.annotation.Resource;
@Controller
@RequestMapping("/user")
public class UserController {
@Resource
UserNameService userNameService;
/**
* 获取用户信息
* @param
* @return
*/
@RequestMapping(value = "/username",method = {RequestMethod.GET,RequestMethod.POST})
@ResponseBody
public String getUserNames(){
return userNameService.getUserName();
}
}
3、编写ExampleApplication入口类并运行程序
package com.bfd.example;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.annotation.EnableScheduling;
@EnableScheduling
@EnableAsync
@SpringBootApplication
@MapperScan("com.bfd.example.dao")
@ComponentScan(basePackages = {"com.bfd.example.*"})
public class ExampleApplication {
public static void main(String[] args) {
SpringApplication.run(ExampleApplication.class, args);
}
}
测试结果
通过postman进行接口测试:
可以看到返回结果为user表的所有信息。