原文連接html
咱們這一篇博客講的是如何整合Springboot和Mybatis框架,而後使用generator自動生成mapper,pojo等文件。而後再使用阿里巴巴提供的開源鏈接池druid,這個鏈接池的好處我就不說了,集合了全部鏈接池的好處,而且還提供了監控等功能,加大了可擴展性等等。java
1. 建立一個springboot項目:mysql
2.能夠看到的是咱們除了引入web依賴以外還引入了三個依賴,分別是MySQL,JDBC,Mybatis,咱們以下觀看一下完整的依賴狀況: git
1 <?xml version="1.0" encoding="UTF-8"?> 2 <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 3 xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/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配置文件進行編輯: github
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=.html 10 #spring.thymeleaf.mode=HTML5 11 #spring.thymeleaf.encoding=UTF-8 12 #spring.thymeleaf.servlet.content-type=text/html 13 14 15 #設置熱部署 16 #開啓熱部署 17 spring.devtools.restart.enabled=true 18 #重啓範圍 19 spring.devtools.restart.additional-paths=src/main/java 20 21 #設置數據源 22 #數據庫鏈接用戶名 23 spring.datasource.username=root 24 #數據庫鏈接密碼 25 spring.datasource.password=123 26 #驅動 27 spring.datasource.driver-class-name= com.mysql.jdbc.Driver 28 #數據庫鏈接路徑 29 spring.datasource.url=jdbc:mysql://localhost:3306/bysj 30 #鏈接池類型 31 spring.datasource.type=com.alibaba.druid.pool.DruidDataSource 32 33 #鏈接池配置,由於springboot默認是開啓了鏈接池的,它有默認配置,這一段能夠忽略 34 # 初始化大小,最小,最大 35 spring.datasource.initialSize=5 36 spring.datasource.minIdle=5 37 spring.datasource.maxActive=20 38 # 配置獲取鏈接等待超時的時間 39 spring.datasource.maxWait=60000 40 # 配置間隔多久才進行一次檢測,檢測須要關閉的空閒鏈接,單位是毫秒 41 spring.datasource.timeBetweenEvictionRunsMillis=60000 42 # 配置一個鏈接在池中最小生存的時間,單位是毫秒 43 spring.datasource.minEvictableIdleTimeMillis=300000 44 spring.datasource.validationQuery=SELECT 1 FROM DUAL 45 spring.datasource.testWhileIdle=true 46 spring.datasource.testOnBorrow=false 47 spring.datasource.testOnReturn=false 48 # 打開PSCache,而且指定每一個鏈接上PSCache的大小 49 spring.datasource.poolPreparedStatements=true 50 spring.datasource.maxPoolPreparedStatementPerConnectionSize=20 51 # 配置監控統計攔截的filters,去掉後監控界面sql沒法統計,'wall'用於防火牆 52 spring.datasource.filters=stat,wall,log4j 53 # 經過connectProperties屬性來打開mergeSql功能;慢SQL記錄 54 spring.datasource.connectionProperties=druid.stat.mergeSql=true;druid.stat.slowSqlMillis=500 55 56 #配置mybatis 57 mybatis.mapper-location=classpath:mapping/*.xml 58 #全局的映射,不用在xml文件寫實體類的全路徑 59 mybatis.type-aliases-package=com.zsl.pojo 60 #開啓駝峯映射
mybatis.configuration.map-underscore-to-camel-case=true 61 #配置分頁插件 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.xmlweb
1 <?xml version="1.0" encoding="UTF-8"?> 2 <!DOCTYPE generatorConfiguration 3 PUBLIC "-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN" 4 "http://mybatis.org/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.建立數據庫以及表格 spring
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 Configurationssql
回到下圖所示頁面的時候點擊三角便可:數據庫
7.查看項目狀況以及生成代碼:apache
7.1:生成的mapper:
7.2:生成的pojo實體類:
7.3生成的mapper的xml文件:在這裏務必要注意namespace是否正確,請注意查看這一點
1 <?xml version="1.0" encoding="UTF-8" ?> 2 <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/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" > 11 user_id, user_name, password, phone 12 </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" > 14 select 15 <include refid="Base_Column_List" /> 16 from user 17 where user_id = #{userId,jdbcType=INTEGER} 18 </select> 19 <delete id="deleteByPrimaryKey" parameterType="java.lang.Integer" > 20 delete from user 21 where user_id = #{userId,jdbcType=INTEGER} 22 </delete> 23 <insert id="insert" parameterType="com.zsl.pojo.User" > 24 insert into user (user_id, user_name, password, 25 phone) 26 values (#{userId,jdbcType=INTEGER}, #{userName,jdbcType=VARCHAR}, #{password,jdbcType=VARCHAR}, 27 #{phone,jdbcType=VARCHAR}) 28 </insert> 29 <insert id="insertSelective" parameterType="com.zsl.pojo.User" > 30 insert into user 31 <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" > 61 update user 62 <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> 73 where user_id = #{userId,jdbcType=INTEGER} 74 </update> 75 <update id="updateByPrimaryKey" parameterType="com.zsl.pojo.User" > 76 update user 77 set user_name = #{userName,jdbcType=VARCHAR}, 78 password = #{password,jdbcType=VARCHAR}, 79 phone = #{phone,jdbcType=VARCHAR} 80 where 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 @Controller 13 public class Userontroller { 14 15 @Resource 16 private UserServiceImpl userService; 17 18 //增長用戶 19 @ResponseBody 20 @RequestMapping("/insertUser") 21 public String insertUser(User user){ 22 return userService.insertUser(user); 23 } 24 25 //查詢全部的用戶 26 @ResponseBody 27 @RequestMapping("/selectAllUser") 28 public 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 @Service 12 public class UserServiceImpl implements UserService { 13 14 @Autowired 15 private UserMapper userMapper;//報錯不影響 16 /* 17 * 增長/修改用戶 18 * */ 19 @Override 20 public 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 @Override 32 public List<User> selectAllUser() { 33 //PageHelper.startPage(1, 3); 34 List<User> list = userMapper.selectAllUser(); 35 return list; 36 } 37 }
注意:在實驗的時候務必要在啓動類上加上MapperScna註解,指定掃描mapper文件,或者能夠在每一個mapper文件上加mapper註解,不過這樣太麻煩了: