SpringBoot入门篇--整合mybatis+generator自动生成代码+druid连接池+PageHelper分页插件+SpringBoot整合Mybatis-plus
package com.zsl.service.impl; import com.zsl.mapper.UserMapper; import com.zsl.pojo.User; import com.zsl.service.UserService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.util.List; @Service public class UserServiceImpl implements UserService { @Autowired private UserMapper userMapper;//报错不影响 /* * 增加/修改用户 * */ @Override public String insertUser(User user) { //增加用户 if(user.getUserId() == null){ Integer i = userMapper.insert(user); if(i != 0 && i != null){ return "success"; } } return null; } @Override public List<User> selectAllUser() { //PageHelper.startPage(1, 3); List<User> list = userMapper.selectAllUser(); return list; } }
我们这一一篇博客讲的是如何整合Springboot和Mybatis框架,然后使用generator自动生成mapper,pojo等文件。然后再使用阿里巴巴提供的开源连接池druid,这个连接池的好处我就不说了,集合了所有连接池的好处,并且还提供了监控等功能,加大了可扩展性等等。
1. 创建一个springboot项目:
2.可以看到的是我们除了引入web依赖之外还引入了三个依赖,分别是MySQL,JDBC,Mybatis,我们如下观看一下完整的依赖情况:
<?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.example</groupId> <artifactId>springboot-mybatis02</artifactId> <version>0.0.1-SNAPSHOT</version> <packaging>jar</packaging> <name>springboot-mybatis02</name> <description>Demo project for Spring Boot</description> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>2.0.1.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-jdbc</artifactId> </dependency> <!--web依赖--> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <!--这个依赖已经包括JDBC依赖--> <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> <!--需要手动添加的依赖--> <!--使用durid连接池的依赖--> <dependency> <groupId>com.alibaba</groupId> <artifactId>druid-spring-boot-starter</artifactId> <version>1.1.1</version> </dependency> <!--热部署依赖--> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-devtools</artifactId> </dependency> <!--thymeleaf依赖--> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-thymeleaf</artifactId> </dependency> <!-- 分页插件 --> <dependency> <groupId>com.github.pagehelper</groupId> <artifactId>pagehelper-spring-boot-starter</artifactId> <version>4.1.6</version> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> <!-- mybatis generator 自动生成代码插件 --> <plugin> <groupId>org.mybatis.generator</groupId> <artifactId>mybatis-generator-maven-plugin</artifactId> <version>1.3.2</version> <configuration> <configurationFile>${basedir}/src/main/resources/generator/generatorConfig.xml</configurationFile> <overwrite>true</overwrite> <verbose>true</verbose> </configuration> </plugin> </plugins> </build> </project>
3.依赖引入完成以后我们再对application.properties配置文件进行编辑:
#设置访问端口 server.port=80 #thymeleaf配置,这里是可以省略的,因为默认配置已经足够 #关闭缓存,及时刷新页面,这一点很重要 spring.thymeleaf.cache=false #注释的部分是Thymeleaf默认的配置,如有其它需求可以自行更改 #spring.thymeleaf.prefix=classpath:/templates/ #spring.thymeleaf.suffix=.html #spring.thymeleaf.mode=HTML5 #spring.thymeleaf.encoding=UTF-8 #spring.thymeleaf.servlet.content-type=text/html #设置热部署 #开启热部署 spring.devtools.restart.enabled=true #重启范围 spring.devtools.restart.additional-paths=src/main/java #设置数据源 #数据库连接用户名 spring.datasource.username=root #数据库连接密码 spring.datasource.password=123 #驱动 spring.datasource.driver-class-name= com.mysql.jdbc.Driver #数据库连接路径 spring.datasource.url=jdbc:mysql://localhost:3306/bysj #连接池类型 spring.datasource.type=com.alibaba.druid.pool.DruidDataSource #连接池配置,因为springboot默认是开启了连接池的,它有默认配置,这一段可以忽略 # 初始化大小,最小,最大 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 # 打开PSCache,并且指定每个连接上PSCache的大小 spring.datasource.poolPreparedStatements=true spring.datasource.maxPoolPreparedStatementPerConnectionSize=20 # 配置监控统计拦截的filters,去掉后监控界面sql无法统计,'wall'用于防火墙 spring.datasource.filters=stat,wall,log4j # 通过connectProperties属性来打开mergeSql功能;慢SQL记录 spring.datasource.connectionProperties=druid.stat.mergeSql=true;druid.stat.slowSqlMillis=500 #配置mybatis mybatis.mapper-location=classpath:mapping/*.xml #全局的映射,不用在xml文件写实体类的全路径 mybatis.type-aliases-package=com.zsl.pojo #开启驼峰映射 mybatis.configuration.map-underscore-to-camel-case=true #配置分页插件 #pagehelper分页插件 pagehelper.helper-dialect=mysql pagehelper.reasonable=true pagehelper.support-methods-arguments=true pagehelper.params=count=countSql
4. 配置generator自动生成代码:文件放置的位置就在pom.xml文件里面一如插件的位置${basedir}/src/main/resources/generator/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:\mysql-connector-java-5.1.41.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/bysj" userId="root" password="123"> </jdbcConnection> <javaTypeResolver> <property name="forceBigDecimals" value="false"/> </javaTypeResolver> <!-- 生成模型的包名和位置--> <javaModelGenerator targetPackage="com.zsl.pojo" targetProject="src/main/java"> <property name="enableSubPackages" value="true"/> <property name="trimStrings" value="true"/> </javaModelGenerator> <!-- 生成映射文件的包名和位置--> <sqlMapGenerator targetPackage="mapping" targetProject="src/main/resources"> <property name="enableSubPackages" value="true"/> </sqlMapGenerator> <!-- 生成DAO的包名和位置--> <javaClientGenerator type="XMLMAPPER" targetPackage="com.zsl.mapper" targetProject="src/main/java"> <property name="enableSubPackages" value="true"/> </javaClientGenerator> <!-- 要生成的表 tableName是数据库中的表名或视图名 domainObjectName是实体类名--> <table tableName="user" domainObjectName="User" enableCountByExample="false" enableUpdateByExample="false" enableDeleteByExample="false" enableSelectByExample="false" selectByExampleQueryId="false"></table> </context> </generatorConfiguration>
5.创建数据库以及表格
CREATE DATABASE bysj; CREATE TABLE user( user_id INT NOT NULL PRIMARY KEY AUTO_INCREMENT, user_name VARCHAR(255) NOT NULL , password VARCHAR(255) NOT NULL , phone VARCHAR(255) NOT NULL ) ENGINE=INNODB AUTO_INCREMENT=1000 DEFAULT CHARSET=utf8;
6. 操作IDEA生成代码:Run-->Edit Configurations
回到下图所示页面的时候点击三角即可:
7.查看项目情况以及生成代码:
7.2:生成的pojo实体类:
7.3生成的mapper的xml文件:在这里务必要注意namespace是否正确,请注意查看这一点
<?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="com.zsl.mapper.UserMapper" > <resultMap id="BaseResultMap" type="com.zsl.pojo.User" > <id column="user_id" property="userId" jdbcType="INTEGER" /> <result column="user_name" property="userName" jdbcType="VARCHAR" /> <result column="password" property="password" jdbcType="VARCHAR" /> <result column="phone" property="phone" jdbcType="VARCHAR" /> </resultMap> <sql id="Base_Column_List" > user_id, user_name, password, phone </sql> <!--自己写的--> <select id="selectAllUser" resultType="user"> select <include refid="Base_Column_List" /> from user; </select> <select id="selectByPrimaryKey" resultMap="BaseResultMap" parameterType="java.lang.Integer" > select <include refid="Base_Column_List" /> from user where user_id = #{userId,jdbcType=INTEGER} </select> <delete id="deleteByPrimaryKey" parameterType="java.lang.Integer" > delete from user where user_id = #{userId,jdbcType=INTEGER} </delete> <insert id="insert" parameterType="com.zsl.pojo.User" > insert into user (user_id, user_name, password, phone) values (#{userId,jdbcType=INTEGER}, #{userName,jdbcType=VARCHAR}, #{password,jdbcType=VARCHAR}, #{phone,jdbcType=VARCHAR}) </insert> <insert id="insertSelective" parameterType="com.zsl.pojo.User" > insert into user <trim prefix="(" suffix=")" suffixOverrides="," > <if test="userId != null" > user_id, </if> <if test="userName != null" > user_name, </if> <if test="password != null" > password, </if> <if test="phone != null" > phone, </if> </trim> <trim prefix="values (" suffix=")" suffixOverrides="," > <if test="userId != null" > #{userId,jdbcType=INTEGER}, </if> <if test="userName != null" > #{userName,jdbcType=VARCHAR}, </if> <if test="password != null" > #{password,jdbcType=VARCHAR}, </if> <if test="phone != null" > #{phone,jdbcType=VARCHAR}, </if> </trim> </insert> <update id="updateByPrimaryKeySelective" parameterType="com.zsl.pojo.User" > update user <set > <if test="userName != null" > user_name = #{userName,jdbcType=VARCHAR}, </if> <if test="password != null" > password = #{password,jdbcType=VARCHAR}, </if> <if test="phone != null" > phone = #{phone,jdbcType=VARCHAR}, </if> </set> where user_id = #{userId,jdbcType=INTEGER} </update> <update id="updateByPrimaryKey" parameterType="com.zsl.pojo.User" > update user set user_name = #{userName,jdbcType=VARCHAR}, password = #{password,jdbcType=VARCHAR}, phone = #{phone,jdbcType=VARCHAR} where user_id = #{userId,jdbcType=INTEGER} </update> </mapper>
7.4项目的总体结构:
7.5 自己用于测试分页,驼峰映射,实体类映射等配置的controller,service
package com.zsl.controller; import com.zsl.pojo.User; import com.zsl.service.impl.UserServiceImpl; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; import javax.annotation.Resource; import java.util.List; @Controller public class Userontroller { @Resource private UserServiceImpl userService; //增加用户 @ResponseBody @RequestMapping("/insertUser") public String insertUser(User user){ return userService.insertUser(user); } //查询所有的用户 @ResponseBody @RequestMapping("/selectAllUser") public String getAllUser(){ List<User> list = userService.selectAllUser(); System.out.println(list.size()); System.out.println(list); System.out.println(list.get(1).getUserId()); return null; } }
注意:在实验的时候务必要在启动类上加上MapperScna注解,指定扫描mapper文件,或者可以在每个mapper文件上加mapper注解,不过这样太麻烦了:
加依赖
<dependency> <groupId>com.baomidou</groupId> <artifactId>mybatis-plus-boot-starter</artifactId> <version>3.0.1</version> </dependency>
mapper继承即可,相当于通用mapper不需要任何配置爽!