我们这一一篇博客讲的是如何整合Springboot和Mybatis框架,然后使用generator自动生成mapper,pojo等文件。然后再使用阿里巴巴提供的开源连接池druid,这个连接池的好处我就不说了,集合了所有连接池的好处,并且还提供了监控等功能,加大了可扩展性等等。
1. 创建一个springboot项目:
2.可以看到的是我们除了引入web依赖之外还引入了三个依赖,分别是MySQL,JDBC,Mybatis,我们如下观看一下完整的依赖情况:
1 <?xml version="1.0" encoding="UTF-8"?> 2 <project xmlns="/POM/4.0.0" xmlns:xsi="/2001/XMLSchema-instance" 3xsi:schemaLocation="/POM/4.0.0 /xsd/maven-4.0.0.xsd"> 4<modelVersion>4.0.0</modelVersion> 5 6<groupId>com.example</groupId> 7<artifactId>springboot-mybatis02</artifactId> 8<version>0.0.1-SNAPSHOT</version> 9<packaging>jar</packaging> 10 11<name>springboot-mybatis02</name> 12<description>Demo project for Spring Boot</description> 13 14<parent> 15 <groupId>org.springframework.boot</groupId> 16 <artifactId>spring-boot-starter-parent</artifactId> 17 <version>2.0.1.RELEASE</version> 18 <relativePath/> <!-- lookup parent from repository --> 19</parent> 20 21<properties> 22 <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> 23 <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding> 24 <java.version>1.8</java.version> 25</properties> 26 27<dependencies> 28 <dependency> 29 <groupId>org.springframework.boot</groupId> 30 <artifactId>spring-boot-starter-jdbc</artifactId> 31 </dependency> 32 33 <!--web依赖--> 34 <dependency> 35 <groupId>org.springframework.boot</groupId> 36 <artifactId>spring-boot-starter-web</artifactId> 37 </dependency> 38 39 <!--这个依赖已经包括JDBC依赖--> 40 <dependency> 41 <groupId>org.mybatis.spring.boot</groupId> 42 <artifactId>mybatis-spring-boot-starter</artifactId> 43 <version>1.3.2</version> 44 </dependency> 45 46 <!--数据库连接--> 47 <dependency> 48 <groupId>mysql</groupId> 49 <artifactId>mysql-connector-java</artifactId> 50 <scope>runtime</scope> 51 </dependency> 52 53 <!--需要手动添加的依赖--> 54 <!--使用durid连接池的依赖--> 55 <dependency> 56 <groupId>com.alibaba</groupId> 57 <artifactId>druid-spring-boot-starter</artifactId> 58 <version>1.1.1</version> 59 </dependency> 60 61 <!--热部署依赖--> 62 <dependency> 63 <groupId>org.springframework.boot</groupId> 64 <artifactId>spring-boot-devtools</artifactId> 65 </dependency> 66 67 <!--thymeleaf依赖--> 68 <dependency> 69 <groupId>org.springframework.boot</groupId> 70 <artifactId>spring-boot-starter-thymeleaf</artifactId> 71 </dependency> 72 73 74 <!-- 分页插件 --> 75 <dependency> 76 <groupId>com.github.pagehelper</groupId> 77 <artifactId>pagehelper-spring-boot-starter</artifactId> 78 <version>4.1.6</version> 79 </dependency> 80 81 <dependency> 82 <groupId>org.springframework.boot</groupId> 83 <artifactId>spring-boot-starter-test</artifactId> 84 <scope>test</scope> 85 </dependency> 86</dependencies> 87 88<build> 89 <plugins> 90 <plugin> 91 <groupId>org.springframework.boot</groupId> 92 <artifactId>spring-boot-maven-plugin</artifactId> 93 </plugin> 94 95 <!-- mybatis generator 自动生成代码插件 --> 96 <plugin> 97 <groupId>org.mybatis.generator</groupId> 98 <artifactId>mybatis-generator-maven-plugin</artifactId> 99 <version>1.3.2</version>100 <configuration>101 <configurationFile>${basedir}/src/main/resources/generator/generatorConfig.xml</configurationFile>102 <overwrite>true</overwrite>103 <verbose>true</verbose>104 </configuration>105 </plugin>106 </plugins>107</build>108 109 110 </project>
3.依赖引入完成以后我们再对application.properties配置文件进行编辑:
1 #设置访问端口 2 server.port=80 3 4 #thymeleaf配置,这里是可以省略的,因为默认配置已经足够 5 #关闭缓存,及时刷新页面,这一点很重要 6 spring.thymeleaf.cache=false 7 #注释的部分是Thymeleaf默认的配置,如有其它需求可以自行更改 8 #spring.thymeleaf.prefix=classpath:/templates/ 9 #spring.thymeleaf.suffix=.html10 #spring.thymeleaf.mode=HTML511 #spring.thymeleaf.encoding=UTF-812 #spring.thymeleaf.servlet.content-type=text/html13 14 15 #设置热部署16 #开启热部署17 spring.devtools.restart.enabled=true18 #重启范围19 spring.devtools.restart.additional-paths=src/main/java20 21 #设置数据源22 #数据库连接用户名23 spring.datasource.username=root24 #数据库连接密码25 spring.datasource.password=12326 #驱动27 spring.datasource.driver-class-name= com.mysql.jdbc.Driver28 #数据库连接路径29 spring.datasource.url=jdbc:mysql://localhost:3306/bysj30 #连接池类型31 spring.datasource.type=com.alibaba.druid.pool.DruidDataSource32 33 #连接池配置,因为springboot默认是开启了连接池的,它有默认配置,这一段可以忽略34 # 初始化大小,最小,最大35 spring.datasource.initialSize=536 spring.datasource.minIdle=537 spring.datasource.maxActive=2038 # 配置获取连接等待超时的时间39 spring.datasource.maxWait=6000040 # 配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒41 spring.datasource.timeBetweenEvictionRunsMillis=6000042 # 配置一个连接在池中最小生存的时间,单位是毫秒43 spring.datasource.minEvictableIdleTimeMillis=30000044 spring.datasource.validationQuery=SELECT 1 FROM DUAL45 spring.datasource.testWhileIdle=true46 spring.datasource.testOnBorrow=false47 spring.datasource.testOnReturn=false48 # 打开PSCache,并且指定每个连接上PSCache的大小49 spring.datasource.poolPreparedStatements=true50 spring.datasource.maxPoolPreparedStatementPerConnectionSize=2051 # 配置监控统计拦截的filters,去掉后监控界面sql无法统计,'wall'用于防火墙52 spring.datasource.filters=stat,wall,log4j53 # 通过connectProperties属性来打开mergeSql功能;慢SQL记录54 spring.datasource.connectionProperties=druid.stat.mergeSql=true;druid.stat.slowSqlMillis=50055 56 #配置mybatis57 mybatis.mapper-location=classpath:mapping/*.xml58 #全局的映射,不用在xml文件写实体类的全路径59 mybatis.type-aliases-package=com.zsl.pojo60 #开启驼峰映射
mybatis.configuration.map-underscore-to-camel-case=true61 #配置分页插件62 #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
1 <?xml version="1.0" encoding="UTF-8"?> 2 <!DOCTYPE generatorConfiguration 3 PUBLIC "-////DTD MyBatis Generator Configuration 1.0//EN" 4 "/dtd/mybatis-generator-config_1_0.dtd"> 5 <generatorConfiguration> 6<!-- 数据库驱动:选择你的本地硬盘上面的数据库驱动包--> 7<classPathEntry location="C:\mysql-connector-java-5.1.41.jar"/> 8<context id="DB2Tables" targetRuntime="MyBatis3"> 9 <commentGenerator>10 <property name="suppressDate" value="true"/>11 <!-- 是否去除自动生成的注释 true:是 : false:否 -->12 <property name="suppressAllComments" value="true"/>13 </commentGenerator>14 <!--数据库链接URL,用户名、密码 -->15 <jdbcConnection driverClass="com.mysql.jdbc.Driver" connectionURL="jdbc:mysql://localhost/bysj" userId="root" password="123">16 </jdbcConnection>17 <javaTypeResolver>18 <property name="forceBigDecimals" value="false"/>19 </javaTypeResolver>20 <!-- 生成模型的包名和位置-->21 <javaModelGenerator targetPackage="com.zsl.pojo" targetProject="src/main/java">22 <property name="enableSubPackages" value="true"/>23 <property name="trimStrings" value="true"/>24 </javaModelGenerator>25 <!-- 生成映射文件的包名和位置-->26 <sqlMapGenerator targetPackage="mapping" targetProject="src/main/resources">27 <property name="enableSubPackages" value="true"/>28 </sqlMapGenerator>29 <!-- 生成DAO的包名和位置-->30 <javaClientGenerator type="XMLMAPPER" targetPackage="com.zsl.mapper" targetProject="src/main/java">31 <property name="enableSubPackages" value="true"/>32 </javaClientGenerator>33 <!-- 要生成的表 tableName是数据库中的表名或视图名 domainObjectName是实体类名-->34 <table tableName="user" domainObjectName="User" enableCountByExample="false" enableUpdateByExample="false" enableDeleteByExample="false" enableSelectByExample="false" selectByExampleQueryId="false"></table>35</context>36 </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.1:生成的mapper:
7.2:生成的pojo实体类:
7.3生成的mapper的xml文件:在这里务必要注意namespace是否正确,请注意查看这一点
1 <?xml version="1.0" encoding="UTF-8" ?> 2 <!DOCTYPE mapper PUBLIC "-////DTD Mapper 3.0//EN" "/dtd/mybatis-3-mapper.dtd" > 3 <mapper namespace="com.zsl.mapper.UserMapper" > 4 <resultMap id="BaseResultMap" type="com.zsl.pojo.User" > 5<id column="user_id" property="userId" jdbcType="INTEGER" /> 6<result column="user_name" property="userName" jdbcType="VARCHAR" /> 7<result column="password" property="password" jdbcType="VARCHAR" /> 8<result column="phone" property="phone" jdbcType="VARCHAR" /> 9 </resultMap>10 <sql id="Base_Column_List" >11user_id, user_name, password, phone12 </sql>
<!--自己写的-->
<select id="selectAllUser" resultType="user">
select
<include refid="Base_Column_List" />
from user;
</select>13 <select id="selectByPrimaryKey" resultMap="BaseResultMap" parameterType="java.lang.Integer" >14select 15<include refid="Base_Column_List" />16from user17where user_id = #{userId,jdbcType=INTEGER}18 </select>19 <delete id="deleteByPrimaryKey" parameterType="java.lang.Integer" >20delete from user21where user_id = #{userId,jdbcType=INTEGER}22 </delete>23 <insert id="insert" parameterType="com.zsl.pojo.User" >24insert into user (user_id, user_name, password, 25 phone)26values (#{userId,jdbcType=INTEGER}, #{userName,jdbcType=VARCHAR}, #{password,jdbcType=VARCHAR}, 27 #{phone,jdbcType=VARCHAR})28 </insert>29 <insert id="insertSelective" parameterType="com.zsl.pojo.User" >30insert into user31<trim prefix="(" suffix=")" suffixOverrides="," >32 <if test="userId != null" >33 user_id,34 </if>35 <if test="userName != null" >36 user_name,37 </if>38 <if test="password != null" >39 password,40 </if>41 <if test="phone != null" >42 phone,43 </if>44</trim>45<trim prefix="values (" suffix=")" suffixOverrides="," >46 <if test="userId != null" >47 #{userId,jdbcType=INTEGER},48 </if>49 <if test="userName != null" >50 #{userName,jdbcType=VARCHAR},51 </if>52 <if test="password != null" >53 #{password,jdbcType=VARCHAR},54 </if>55 <if test="phone != null" >56 #{phone,jdbcType=VARCHAR},57 </if>58</trim>59 </insert>60 <update id="updateByPrimaryKeySelective" parameterType="com.zsl.pojo.User" >61update user62<set >63 <if test="userName != null" >64 user_name = #{userName,jdbcType=VARCHAR},65 </if>66 <if test="password != null" >67 password = #{password,jdbcType=VARCHAR},68 </if>69 <if test="phone != null" >70 phone = #{phone,jdbcType=VARCHAR},71 </if>72</set>73where user_id = #{userId,jdbcType=INTEGER}74 </update>75 <update id="updateByPrimaryKey" parameterType="com.zsl.pojo.User" >76update user77set user_name = #{userName,jdbcType=VARCHAR},78 password = #{password,jdbcType=VARCHAR},79 phone = #{phone,jdbcType=VARCHAR}80where user_id = #{userId,jdbcType=INTEGER}81 </update>82 </mapper>
7.4项目的总体结构:
7.5 自己用于测试分页,驼峰映射,实体类映射等配置的controller,service
1 package com.zsl.controller; 2 3 import com.zsl.pojo.User; 4 import com.zsl.service.impl.UserServiceImpl; 5 import org.springframework.stereotype.Controller; 6 import org.springframework.web.bind.annotation.RequestMapping; 7 import org.springframework.web.bind.annotation.ResponseBody; 8 9 import javax.annotation.Resource;10 import java.util.List;11 12 @Controller13 public class Userontroller {14 15@Resource16private UserServiceImpl userService;17 18//增加用户19@ResponseBody20@RequestMapping("/insertUser")21public String insertUser(User user){22 return userService.insertUser(user);23}24 25//查询所有的用户26@ResponseBody27@RequestMapping("/selectAllUser")28public String getAllUser(){29 List<User> list = userService.selectAllUser();30 System.out.println(list.size());31 System.out.println(list);32 System.out.println(list.get(1).getUserId());33 return null;34}35 }
1 package com.zsl.service.impl; 2 3 import com.zsl.mapper.UserMapper; 4 import com.zsl.pojo.User; 5 import com.zsl.service.UserService; 6 import org.springframework.beans.factory.annotation.Autowired; 7 import org.springframework.stereotype.Service; 8 9 import java.util.List;10 11 @Service12 public class UserServiceImpl implements UserService {13 14@Autowired15private UserMapper userMapper;//报错不影响16/*17* 增加/修改用户18* */19@Override20public String insertUser(User user) {21 //增加用户22 if(user.getUserId() == null){23 Integer i = userMapper.insert(user);24 if(i != 0 && i != null){25 return "success";26 }27 }28 return null;29}30 31@Override32public List<User> selectAllUser() {33 //PageHelper.startPage(1, 3);34 List<User> list = userMapper.selectAllUser();35 return list;36}37 }
注意:在实验的时候务必要在启动类上加上MapperScna注解,指定扫描mapper文件,或者可以在每个mapper文件上加mapper注解,不过这样太麻烦了: