springboot与mybatis框架的整合
如何创建springboot这里就不在赘述,前面的博客已经记录过了。这里整合的前提是已经创建好了一个springboot项目。
目录
1.在pom.xml里面添加依赖包并clean工程
2.配置数据源
3.在application.properties里面配置mybatis和数据源配置
4.创建测试类
上面的过程是在创建好springboot项目的情况下整合mybatis的,springboot创建好的目录结构如下图:
刚刚创建好的springboot项目可能会缺少一些资源包,比如缺少src/main/resource或者src/main/webapp,一般不会缺少ser/mian/java包的。如果出现这种情况,我们可以自己在工程鼠标右键new一个source folder,名字就是缺少的包名,然后把该资源文件夹放进编译环境:右键工程->build path->configure build path,在右边的java build path下面选中resourc->add folder,之后选中刚刚添加的资源文件夹就可以,如图:
1.在pom.xml里面添加依赖包并clean工程
添加依赖包前,先在项目根目录,也就是直接点击项目名称右键,创建一个文件夹,名为lib,然后下载好mysql的jdbc驱动包mysql-connector-java-5.1.41.jar放在lib目录下,这个包网上一搜就有,当然你也可以通过在线下载的方式导入,这里为了方便就使用已有的离线包。
<?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>cn.idatatech</groupId>
<artifactId>spring</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>war</packaging>
<name>spring</name>
<description>合并spring+mybatis+dorado</description>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.0.4.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>
<!-- 配置web支持 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!-- 配置mybatis依赖包 -->
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>1.3.2</version>
</dependency>
<!-- 配置mysql驱动 -->
<dependency>
<groupId>com.mysql</groupId>
<artifactId>mysql-connector-java-5.1.41-bin</artifactId>
<version>5.1.41</version>
<systemPath>${basedir}/lib/mysql-connector-java-5.1.41-bin.jar</systemPath>
<scope>system</scope>
</dependency>
<!-- 配置tomcat -->
<dependency>
<groupId>com.mysql</groupId>
<artifactId>mysql-connector-java-5.1.41-bin</artifactId>
<version>5.1.41</version>
<systemPath>${basedir}/lib/mysql-connector-java-5.1.41-bin.jar</systemPath>
<scope>system</scope>
</dependency>
<!-- 配置srping测试包支持 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<!-- 添加阿里巴巴数据源依赖包 druid-->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.0.29</version>
</dependency>
<!--配置支持jsp-->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<scope>provided</scope>
</dependency>
<!-- 引入jsp中jstl包的支持 -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>
<dependency>
<groupId>org.apache.tomcat.embed</groupId>
<artifactId>tomcat-embed-jasper</artifactId>
</dependency>
<!-- 配置dom4j,对xml文件解析支持 -->
<!-- 也可以配置saxon解析,这里主要用来解析mapper.xml文件 -->
<dependency>
<groupId>dom4j</groupId>
<artifactId>dom4j</artifactId>
<version>1.6.1</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
2.配置数据源
在src/main/java目录下cn.idatatech.spring(你自己的包名)下的Application.java那里添加配置数据源的代码(也可以将数据源配置的代码单独提出来)
Application.java
package cn.idatatech.spring;
import javax.sql.DataSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.web.servlet.support.SpringBootServletInitializer;
import org.springframework.context.annotation.Bean;
import org.springframework.core.env.Environment;
import com.alibaba.druid.pool.DruidDataSource;
@SpringBootApplication
public class Application extends SpringBootServletInitializer{
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
@Override
protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
return application.sources(Application.class);
}
@Autowired
private Environment env;
//destroy-method="close"的作用是当数据库连接不使用的时候,就把该连接重新放到数据池中,方便下次使用调用.
@Bean(destroyMethod = "close")
public DataSource dataSource() {
DruidDataSource dataSource = new DruidDataSource();
dataSource.setUrl(env.getProperty("spring.datasource.url"));
dataSource.setUsername(env.getProperty("spring.datasource.username"));//用户名
dataSource.setPassword(env.getProperty("spring.datasource.password"));//密码
dataSource.setDriverClassName(env.getProperty("spring.datasource.driver-class-name"));
dataSource.setInitialSize(2);//初始化时建立物理连接的个数
dataSource.setMaxActive(20);//最大连接池数量
dataSource.setMinIdle(0);//最小连接池数量
dataSource.setMaxWait(60000);//获取连接时最大等待时间,单位毫秒。
dataSource.setValidationQuery("SELECT 1");//用来检测连接是否有效的sql
dataSource.setTestOnBorrow(false);//申请连接时执行validationQuery检测连接是否有效
dataSource.setTestWhileIdle(true);//建议配置为true,不影响性能,并且保证安全性。
dataSource.setPoolPreparedStatements(false);//是否缓存preparedStatement,也就是PSCache
return dataSource;
}
}
这里我们已经在pom.xm使用阿里巴巴的druid数据源,配置好后通过springboot扫描器可以自动扫描到我们配置的数据源。
3.在application.properties里面配置mybatis和数据源配置
# 配置端口号server.port=6666
# 设置项目访问别名server.context-path=/springboot1
# 配置页面的默认访问前缀和后缀,高版本spring-boot-starter-paren
spring.mvc.view.prefix=/WEB-INF/views/
spring.mvc.view.suffix=.jsp
#当pom文件下的spring-boot-starter-paren版本低时使用:
#spring.view.prefix/spring.view.suffix
# 配置数据源datasource
spring.datasource.url=jdbc:mysql://localhost/mybatis?useSSL=false
spring.datasource.username=root
spring.datasource.password=123456
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
# 配置mybatis
mybatis.mapper-locations=classpath*:mappings/**/*.xml
#mybatis.type-aliases-package=cn.idatatech.spring.moduls.model
4.创建测试类
创建好的目录结构如下:
4.1创建Person.java
package cn.idatatech.spring.moduls.model;
import java.io.Serializable;
public class Person implements Serializable{
/**
* @author zoul [lang.zou]
* @date 2018-08-09 14:25:50
*/
private static final long serialVersionUID = 1L;
private int id;
private String name;
private int age;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
4.2创建PersonMapper.java
package cn.idatatech.spring.moduls.mapper;
import java.util.List;
import org.apache.ibatis.annotations.Mapper;
import cn.idatatech.spring.moduls.model.Person;
@Mapper
public interface PersonMapper {
List<Person> queryAll();
}
4.3创建PersonService.java
package cn.idatatech.spring.moduls.service;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import cn.idatatech.spring.moduls.mapper.PersonMapper;
import cn.idatatech.spring.moduls.model.Person;
@Service
public class PersonService {
@Autowired
PersonMapper personMapper;
public List<Person> findAll(){
return personMapper.queryAll();
}
}
4.4创建PersonController.java
package cn.idatatech.spring.moduls.controller;
import java.util.ArrayList;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import cn.idatatech.spring.moduls.model.Person;
import cn.idatatech.spring.moduls.service.PersonService;
@Controller
public class PersonController {
@Autowired
PersonService personService = new PersonService();
@RequestMapping("/index")
public String findAll(Model model){
List<Person> personList = new ArrayList<Person>();
personList = personService.findAll();
model.addAttribute("personList",personList);
return "personInfo";
}
}
4.5创建PersonMapper.xml
<?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="cn.idatatech.spring.moduls.mapper.PersonMapper">
<!-- <cache type="org.mybatis.caches.ehcache.EhcacheCache"/> -->
<select id="queryAll" resultType="cn.idatatech.spring.moduls.model.Person">
SELECT *
FROM person
</select>
</mapper>
4.6创建测试用的personInfo.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<%out.println("测试"); %>
<table>
<tr>
<th>编号</th>
<th>姓名</th>
<th>年龄</th>
</tr>
<c:forEach items="${personList}" var="person" >
<tr>
<td>${person.id } </td>
<td>${person.name } </td>
<td>${person.age } </td>
</tr>
</c:forEach>
</table>
</body>
</html>
创建数据库mybatis,然后创建表person。
person创建sql:
/*
Navicat MySQL Data Transfer
Source Server : mybatis
Source Server Version : 50717
Source Host : localhost:3306
Source Database : mybatis
Target Server Type : MYSQL
Target Server Version : 50717
File Encoding : 65001
Date: 2018-08-09 15:38:55
*/
SET FOREIGN_KEY_CHECKS=0;
-- ----------------------------
-- Table structure for person
-- ----------------------------
DROP TABLE IF EXISTS person;
CREATE TABLE person (
id int(32) NOT NULL,
name varchar(50) DEFAULT NULL,
age int(10) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
-- ----------------------------
-- Records of person
-- ----------------------------
INSERT INTO person VALUES ('1', '王萌', '24');
INSERT INTO person VALUES ('2', '李小龙', '43');
启动项目,待项目启动完成后打开浏览器,输入访问地址http://localhost:8080/index可以看到访问数据成功。访问成功页面如下: