IntelliJ IDEA 2017版 spring-boot与Mybatis简单整合

时间:2021-05-27 05:52:57

一、编译器建立项目

参考:http://www.cnblogs.com/liuyangfirst/p/8372291.html

二、代码编辑

1、建立数据库

 /*
Navicat MySQL Data Transfer Source Server : mysql
Source Server Version : 50549
Source Host : localhost:3306
Source Database : test Target Server Type : MYSQL
Target Server Version : 50549
File Encoding : 65001 Date: 2018-01-28 20:07:45
*/ SET FOREIGN_KEY_CHECKS=0; -- ----------------------------
-- Table structure for demo
-- ----------------------------
DROP TABLE IF EXISTS `demo`;
CREATE TABLE `demo` (
`id` int(40) NOT NULL AUTO_INCREMENT,
`name` varchar(255) DEFAULT NULL,
`updateTime` datetime DEFAULT NULL,
`password` varchar(255) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=9 DEFAULT CHARSET=latin1; -- ----------------------------
-- Records of demo
-- ----------------------------
INSERT INTO `demo` VALUES ('', 'zhangsan', '2018-01-28 19:45:59', '');
INSERT INTO `demo` VALUES ('', 'lisi', '2018-01-28 19:46:33', '');
INSERT INTO `demo` VALUES ('', 'longwu', '2018-01-28 19:46:46', '');
INSERT INTO `demo` VALUES ('', 'zhangsan', '2018-01-28 19:52:56', '');
INSERT INTO `demo` VALUES ('', 'zhangsan', '2018-01-28 19:53:08', '');
INSERT INTO `demo` VALUES ('', 'zhangsan', '2018-01-28 19:53:22', '');
INSERT INTO `demo` VALUES ('', 'zhangsan', '2018-01-28 19:53:38', '');
INSERT INTO `demo` VALUES ('', 'zhangsan', null, null);

2、pom.xml配置

 <?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.spring</groupId>
<artifactId>boot-add-mybatis</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging> <name>boot-add-mybatis</name>
<url>http://maven.apache.org</url>
<description>Demo project for Spring Boot</description> <parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.5.9.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-web</artifactId>
</dependency> <dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency> <!-- servlet 依赖. -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<scope>provided</scope>
</dependency> <!--
JSTL(JSP Standard Tag Library,JSP标准标签库)是一个不断完善的开放源代码的JSP标签库,是由apache的jakarta小组来维护的。
-->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
</dependency> <!-- tomcat 的支持.-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-tomcat</artifactId>
<scope>provided</scope>
</dependency> <dependency>
<groupId>org.apache.tomcat.embed</groupId>
<artifactId>tomcat-embed-jasper</artifactId>
<!--<scope>provided</scope>-->
</dependency> <dependency>
<groupId>org.eclipse.jdt.core.compiler</groupId>
<artifactId>ecj</artifactId>
<version>4.6.1</version>
<scope>provided</scope>
</dependency> <!-- 添加fastjson 依赖包. -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.15</version>
</dependency> <!-- mysql 数据库驱动. -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency> <!--
spring-boot mybatis依赖: 请不要使用1.0.0版本,因为还不支持拦截器插件,
1.1.1 是博主写帖子时候的版本,大家使用最新版本即可
-->
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>1.1.1</version>
</dependency> <!--
MyBatis提供了拦截器接口,我们可以实现自己的拦截器,
将其作为一个plugin装入到SqlSessionFactory中。
Github上有位开发者写了一个分页插件,我觉得使用起来还可以,挺方便的。
Github项目地址: https://github.com/pagehelper/Mybatis-PageHelper
-->
<dependency>
<groupId>com.github.pagehelper</groupId>
<artifactId>pagehelper</artifactId>
<version>4.1.0</version>
</dependency> </dependencies> <build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build> </project>

3、application.properties配置

 #页面默认前缀目录
spring.mvc.view.prefix=/WEB-INF/index/
# 响应默认后缀
spring.mvc.view.suffix=.jsp #######################################################
##datasource -- 指定mysql数据库连接信息.
#######################################################
spring.datasource.url=jdbc:mysql://localhost:3306/test
spring.datasource.username=root
spring.datasource.password=123456
spring.datasource.driverClassName=com.mysql.jdbc.Driver
spring.datasource.max-active=20
spring.datasource.max-idle=8
spring.datasource.min-idle=8
spring.datasource.initial-size=10
########################################################
### Java Persistence Api -- Spring jpa的配置信息.
########################################################
# Specify the DBMS
spring.jpa.database=MYSQL
# Show or not log for each sql query
spring.jpa.show-sql=true
# Hibernate ddl auto (create, create-drop, update)
spring.jpa.hibernate.ddl-auto=update
# Naming strategy
#[org.hibernate.cfg.ImprovedNamingStrategy #org.hibernate.cfg.DefaultNamingStrategy]
spring.jpa.hibernate.naming-strategy=org.hibernate.cfg.ImprovedNamingStrategy
# stripped before adding them to the entity manager)
spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.MySQL5Dialect

4、实体类创建

 package com.spring.pojo;

 /**
* Created by liuya on 2018-01-28.
*
*
* test 用的实体类
*/ public class Demo { //类的id
private long id;
//类的名称
private String name; public Demo() {
} public Demo(long id,String name) {
this.id = id;
this.name = name;
} public long getId() {
return id;
} public void setId(long id) {
this.id = id;
} public String getName() {
return name;
} public void setName(String name) {
this.name = name;
}
}

5、dao搭建

 package com.spring.dao;

 import java.util.List;

 import com.spring.pojo.Demo;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Options;
import org.apache.ibatis.annotations.Select; public interface DemoMappper { //#{name}:参数占位符
@Select("select *from Demo where name=#{name}")
public List<Demo> likeName(String name); @Select("select *from Demo where id = #{id}")
public Demo getById(long id); @Select("select name from Demo where id = #{id}")
public String getNameById(long id); /**
* 保存数据.
*/
@Insert("insert into Demo(name) values(#{name})")
@Options(useGeneratedKeys=true,keyProperty="id",keyColumn="id")
public void save(Demo demo); }

6、service搭建

 package com.spring.service;

 import java.util.List;

 import com.spring.dao.DemoMappper;
import com.spring.pojo.Demo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional; @Service
public class DemoService { @Autowired
private DemoMappper demoMappper; public List<Demo> likeName(String name){
return demoMappper.likeName(name);
} @Transactional//添加事务.
public void save(Demo demo){
demoMappper.save(demo);
} }

7、Controller搭建

 package com.spring.controller;

 import java.util.List;

 import com.spring.pojo.Demo;
import com.spring.service.DemoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController; import com.github.pagehelper.PageHelper; @RestController
public class DemoController { @Autowired
private DemoService demoService; /**
* 访问路径: http://127.0.0.1:8080/likeName?name=zhangsan
* @param name
* @return
*/
@RequestMapping("/likeName")
public List<Demo> likeName(String name){
/*
* 第一个参数:第几页;
* 第二个参数:每页获取的条数.
*/
PageHelper.startPage(1, 2);
return demoService.likeName(name);
} /**
* 访问路径:
* @return
*/ @RequestMapping("/save")
public Demo save(){
Demo demo = new Demo();
demo.setName("zhangsan");
demoService.save(demo);
return demo;
} }

8、Application.java编辑

 package com.spring;

 import com.alibaba.fastjson.serializer.SerializerFeature;
import com.alibaba.fastjson.support.config.FastJsonConfig;
import com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.web.HttpMessageConverters;
import org.springframework.context.annotation.Bean;
import org.springframework.http.converter.HttpMessageConverter; @SpringBootApplication
@MapperScan("com.spring.*")
public class BootAddMybatisApplication { public static void main(String[] args) {
SpringApplication.run(BootAddMybatisApplication.class, args);
} /**
* 在这里我们使用 @Bean注入 fastJsonHttpMessageConvert
* @return
*/
@Bean
public HttpMessageConverters fastJsonHttpMessageConverters() {
// 1、需要先定义一个 convert 转换消息的对象;
FastJsonHttpMessageConverter fastConverter = new FastJsonHttpMessageConverter(); //2、添加fastJson 的配置信息,比如:是否要格式化返回的json数据;
FastJsonConfig fastJsonConfig = new FastJsonConfig();
fastJsonConfig.setSerializerFeatures(SerializerFeature.PrettyFormat); //3、在convert中添加配置信息.
fastConverter.setFastJsonConfig(fastJsonConfig); HttpMessageConverter<?> converter = fastConverter;
return new HttpMessageConverters(converter);
}
}

9、configer编辑

 package com.spring.configer;

 import java.util.Properties;

 import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration; import com.github.pagehelper.PageHelper; @Configuration
public class MyBatisConfiguration { @Bean
public PageHelper pageHelper() {
System.out.println("MyBatisConfiguration.pageHelper()");
PageHelper pageHelper = new PageHelper();
Properties p = new Properties();
p.setProperty("offsetAsPageNum", "true");
p.setProperty("rowBoundsWithCount", "true");
p.setProperty("reasonable", "true");
pageHelper.setProperties(p);
return pageHelper;
}
}

10、访问测试:url:http://127.0.0.1:8080/likeName?name=zhangsan 保存访问路径:http://127.0.0.1:8080/save

IntelliJ IDEA 2017版 spring-boot与Mybatis简单整合