IntelliJ IDEA 2017版 spring-boot与Mybatis简单整合
一、编译器建立项目
参考:http://www.cnblogs.com/liuyangfirst/p/8372291.html
二、代码编辑
1、建立数据库
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 /* 2 Navicat MySQL Data Transfer 3 4 Source Server : mysql 5 Source Server Version : 50549 6 Source Host : localhost:3306 7 Source Database : test 8 9 Target Server Type : MYSQL 10 Target Server Version : 50549 11 File Encoding : 65001 12 13 Date: 2018-01-28 20:07:45 14 */ 15 16 SET FOREIGN_KEY_CHECKS=0; 17 18 -- ---------------------------- 19 -- Table structure for demo 20 -- ---------------------------- 21 DROP TABLE IF EXISTS `demo`; 22 CREATE TABLE `demo` ( 23 `id` int(40) NOT NULL AUTO_INCREMENT, 24 `name` varchar(255) DEFAULT NULL, 25 `updateTime` datetime DEFAULT NULL, 26 `password` varchar(255) DEFAULT NULL, 27 PRIMARY KEY (`id`) 28 ) ENGINE=InnoDB AUTO_INCREMENT=9 DEFAULT CHARSET=latin1; 29 30 -- ---------------------------- 31 -- Records of demo 32 -- ---------------------------- 33 INSERT INTO `demo` VALUES ('1', 'zhangsan', '2018-01-28 19:45:59', '123456'); 34 INSERT INTO `demo` VALUES ('2', 'lisi', '2018-01-28 19:46:33', '123456'); 35 INSERT INTO `demo` VALUES ('3', 'longwu', '2018-01-28 19:46:46', '123456'); 36 INSERT INTO `demo` VALUES ('4', 'zhangsan', '2018-01-28 19:52:56', '1223456'); 37 INSERT INTO `demo` VALUES ('5', 'zhangsan', '2018-01-28 19:53:08', '123456'); 38 INSERT INTO `demo` VALUES ('6', 'zhangsan', '2018-01-28 19:53:22', '4546546546'); 39 INSERT INTO `demo` VALUES ('7', 'zhangsan', '2018-01-28 19:53:38', '1234565'); 40 INSERT INTO `demo` VALUES ('8', 'zhangsan', null, null);
2、pom.xml配置
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
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.spring</groupId> 7 <artifactId>boot-add-mybatis</artifactId> 8 <version>0.0.1-SNAPSHOT</version> 9 <packaging>jar</packaging> 10 11 <name>boot-add-mybatis</name> 12 <url>http://maven.apache.org</url> 13 <description>Demo project for Spring Boot</description> 14 15 <parent> 16 <groupId>org.springframework.boot</groupId> 17 <artifactId>spring-boot-starter-parent</artifactId> 18 <version>1.5.9.RELEASE</version> 19 <relativePath/> <!-- lookup parent from repository --> 20 </parent> 21 22 <properties> 23 <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> 24 <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding> 25 <java.version>1.8</java.version> 26 </properties> 27 28 <dependencies> 29 <dependency> 30 <groupId>org.springframework.boot</groupId> 31 <artifactId>spring-boot-starter-web</artifactId> 32 </dependency> 33 34 <dependency> 35 <groupId>org.springframework.boot</groupId> 36 <artifactId>spring-boot-starter-test</artifactId> 37 <scope>test</scope> 38 </dependency> 39 40 41 <!-- servlet 依赖. --> 42 <dependency> 43 <groupId>javax.servlet</groupId> 44 <artifactId>javax.servlet-api</artifactId> 45 <scope>provided</scope> 46 </dependency> 47 48 <!-- 49 JSTL(JSP Standard Tag Library,JSP标准标签库)是一个不断完善的开放源代码的JSP标签库,是由apache的jakarta小组来维护的。 50 --> 51 <dependency> 52 <groupId>javax.servlet</groupId> 53 <artifactId>jstl</artifactId> 54 </dependency> 55 56 <!-- tomcat 的支持.--> 57 <dependency> 58 <groupId>org.springframework.boot</groupId> 59 <artifactId>spring-boot-starter-tomcat</artifactId> 60 <scope>provided</scope> 61 </dependency> 62 63 <dependency> 64 <groupId>org.apache.tomcat.embed</groupId> 65 <artifactId>tomcat-embed-jasper</artifactId> 66 <!--<scope>provided</scope>--> 67 </dependency> 68 69 <dependency> 70 <groupId>org.eclipse.jdt.core.compiler</groupId> 71 <artifactId>ecj</artifactId> 72 <version>4.6.1</version> 73 <scope>provided</scope> 74 </dependency> 75 76 <!-- 添加fastjson 依赖包. --> 77 <dependency> 78 <groupId>com.alibaba</groupId> 79 <artifactId>fastjson</artifactId> 80 <version>1.2.15</version> 81 </dependency> 82 83 84 <!-- mysql 数据库驱动. --> 85 <dependency> 86 <groupId>mysql</groupId> 87 <artifactId>mysql-connector-java</artifactId> 88 </dependency> 89 90 <!-- 91 spring-boot mybatis依赖: 92 93 请不要使用1.0.0版本,因为还不支持拦截器插件, 94 1.1.1 是博主写帖子时候的版本,大家使用最新版本即可 95 --> 96 <dependency> 97 <groupId>org.mybatis.spring.boot</groupId> 98 <artifactId>mybatis-spring-boot-starter</artifactId> 99 <version>1.1.1</version> 100 </dependency> 101 102 103 <!-- 104 MyBatis提供了拦截器接口,我们可以实现自己的拦截器, 105 将其作为一个plugin装入到SqlSessionFactory中。 106 Github上有位开发者写了一个分页插件,我觉得使用起来还可以,挺方便的。 107 Github项目地址: https://github.com/pagehelper/Mybatis-PageHelper 108 --> 109 <dependency> 110 <groupId>com.github.pagehelper</groupId> 111 <artifactId>pagehelper</artifactId> 112 <version>4.1.0</version> 113 </dependency> 114 115 </dependencies> 116 117 <build> 118 <plugins> 119 <plugin> 120 <groupId>org.springframework.boot</groupId> 121 <artifactId>spring-boot-maven-plugin</artifactId> 122 </plugin> 123 </plugins> 124 </build> 125 126 127 </project>
3、application.properties配置
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 #页面默认前缀目录 2 spring.mvc.view.prefix=/WEB-INF/index/ 3 # 响应默认后缀 4 spring.mvc.view.suffix=.jsp 5 6 ####################################################### 7 ##datasource -- 指定mysql数据库连接信息. 8 ####################################################### 9 spring.datasource.url=jdbc:mysql://localhost:3306/test 10 spring.datasource.username=root 11 spring.datasource.password=123456 12 spring.datasource.driverClassName=com.mysql.jdbc.Driver 13 spring.datasource.max-active=20 14 spring.datasource.max-idle=8 15 spring.datasource.min-idle=8 16 spring.datasource.initial-size=10 17 ######################################################## 18 ### Java Persistence Api -- Spring jpa的配置信息. 19 ######################################################## 20 # Specify the DBMS 21 spring.jpa.database=MYSQL 22 # Show or not log for each sql query 23 spring.jpa.show-sql=true 24 # Hibernate ddl auto (create, create-drop, update) 25 spring.jpa.hibernate.ddl-auto=update 26 # Naming strategy 27 #[org.hibernate.cfg.ImprovedNamingStrategy #org.hibernate.cfg.DefaultNamingStrategy] 28 spring.jpa.hibernate.naming-strategy=org.hibernate.cfg.ImprovedNamingStrategy 29 # stripped before adding them to the entity manager) 30 spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.MySQL5Dialect
4、实体类创建
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 package com.spring.pojo; 2 3 /** 4 * Created by liuya on 2018-01-28. 5 * 6 * 7 * test 用的实体类 8 */ 9 10 11 public class Demo { 12 13 //类的id 14 private long id; 15 //类的名称 16 private String name; 17 18 public Demo() { 19 } 20 21 public Demo(long id,String name) { 22 this.id = id; 23 this.name = name; 24 } 25 26 public long getId() { 27 return id; 28 } 29 30 public void setId(long id) { 31 this.id = id; 32 } 33 34 public String getName() { 35 return name; 36 } 37 38 public void setName(String name) { 39 this.name = name; 40 } 41 }
5、dao搭建
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 package com.spring.dao; 2 3 import java.util.List; 4 5 import com.spring.pojo.Demo; 6 import org.apache.ibatis.annotations.Insert; 7 import org.apache.ibatis.annotations.Options; 8 import org.apache.ibatis.annotations.Select; 9 10 public interface DemoMappper { 11 12 //#{name}:参数占位符 13 @Select("select *from Demo where name=#{name}") 14 public List<Demo> likeName(String name); 15 16 17 @Select("select *from Demo where id = #{id}") 18 public Demo getById(long id); 19 20 @Select("select name from Demo where id = #{id}") 21 public String getNameById(long id); 22 23 24 /** 25 * 保存数据. 26 */ 27 @Insert("insert into Demo(name) values(#{name})") 28 @Options(useGeneratedKeys=true,keyProperty="id",keyColumn="id") 29 public void save(Demo demo); 30 31 }
6、service搭建
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 package com.spring.service; 2 3 import java.util.List; 4 5 import com.spring.dao.DemoMappper; 6 import com.spring.pojo.Demo; 7 import org.springframework.beans.factory.annotation.Autowired; 8 import org.springframework.stereotype.Service; 9 import org.springframework.transaction.annotation.Transactional; 10 11 @Service 12 public class DemoService { 13 14 @Autowired 15 private DemoMappper demoMappper; 16 17 public List<Demo> likeName(String name){ 18 return demoMappper.likeName(name); 19 } 20 21 @Transactional//添加事务. 22 public void save(Demo demo){ 23 demoMappper.save(demo); 24 } 25 26 }
7、Controller搭建
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 package com.spring.controller; 2 3 import java.util.List; 4 5 import com.spring.pojo.Demo; 6 import com.spring.service.DemoService; 7 import org.springframework.beans.factory.annotation.Autowired; 8 import org.springframework.web.bind.annotation.RequestMapping; 9 import org.springframework.web.bind.annotation.RestController; 10 11 import com.github.pagehelper.PageHelper; 12 13 @RestController 14 public class DemoController { 15 16 @Autowired 17 private DemoService demoService; 18 19 20 /** 21 * 访问路径: http://127.0.0.1:8080/likeName?name=zhangsan 22 * @param name 23 * @return 24 */ 25 @RequestMapping("/likeName") 26 public List<Demo> likeName(String name){ 27 /* 28 * 第一个参数:第几页; 29 * 第二个参数:每页获取的条数. 30 */ 31 PageHelper.startPage(1, 2); 32 return demoService.likeName(name); 33 } 34 35 /** 36 * 访问路径: 37 * @return 38 */ 39 40 @RequestMapping("/save") 41 public Demo save(){ 42 Demo demo = new Demo(); 43 demo.setName("zhangsan"); 44 demoService.save(demo); 45 return demo; 46 } 47 48 }
8、Application.java编辑
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 package com.spring; 2 3 import com.alibaba.fastjson.serializer.SerializerFeature; 4 import com.alibaba.fastjson.support.config.FastJsonConfig; 5 import com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter; 6 import org.mybatis.spring.annotation.MapperScan; 7 import org.springframework.boot.SpringApplication; 8 import org.springframework.boot.autoconfigure.SpringBootApplication; 9 import org.springframework.boot.autoconfigure.web.HttpMessageConverters; 10 import org.springframework.context.annotation.Bean; 11 import org.springframework.http.converter.HttpMessageConverter; 12 13 @SpringBootApplication 14 @MapperScan("com.spring.*") 15 public class BootAddMybatisApplication { 16 17 public static void main(String[] args) { 18 SpringApplication.run(BootAddMybatisApplication.class, args); 19 } 20 21 /** 22 * 在这里我们使用 @Bean注入 fastJsonHttpMessageConvert 23 * @return 24 */ 25 @Bean 26 public HttpMessageConverters fastJsonHttpMessageConverters() { 27 // 1、需要先定义一个 convert 转换消息的对象; 28 FastJsonHttpMessageConverter fastConverter = new FastJsonHttpMessageConverter(); 29 30 //2、添加fastJson 的配置信息,比如:是否要格式化返回的json数据; 31 FastJsonConfig fastJsonConfig = new FastJsonConfig(); 32 fastJsonConfig.setSerializerFeatures(SerializerFeature.PrettyFormat); 33 34 //3、在convert中添加配置信息. 35 fastConverter.setFastJsonConfig(fastJsonConfig); 36 37 38 HttpMessageConverter<?> converter = fastConverter; 39 return new HttpMessageConverters(converter); 40 } 41 }
9、configer编辑
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 package com.spring.configer; 2 3 import java.util.Properties; 4 5 import org.springframework.context.annotation.Bean; 6 import org.springframework.context.annotation.Configuration; 7 8 import com.github.pagehelper.PageHelper; 9 10 @Configuration 11 public class MyBatisConfiguration { 12 13 @Bean 14 public PageHelper pageHelper() { 15 System.out.println("MyBatisConfiguration.pageHelper()"); 16 PageHelper pageHelper = new PageHelper(); 17 Properties p = new Properties(); 18 p.setProperty("offsetAsPageNum", "true"); 19 p.setProperty("rowBoundsWithCount", "true"); 20 p.setProperty("reasonable", "true"); 21 pageHelper.setProperties(p); 22 return pageHelper; 23 } 24 }
10、访问测试:url:http://127.0.0.1:8080/likeName?name=zhangsan 保存访问路径:http://127.0.0.1:8080/save
十年磨一剑,一剑破万法