今天我给大家分享的是SpringBoot集成mybatis+SpringMVC,所需软件:JDK1.8、IDEA、MYSQL。
一、新建项目,之前的博客中有提到,在这里就不多说了,建好后修改pom.xml文件,如下:
<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>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.5.2.RELEASE</version>
</parent>
<groupId>cn.personal.qin.demo</groupId>
<artifactId>springboot_demo</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>war</packaging>
<name>springboot</name>
<url>http://maven.apache.org</url>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<!-- java版本 -->
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<scope>test</scope>
</dependency>
<!-- 添加springMVC支持 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!-- MySQL -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
<!-- mybatis -->
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>1.3.2</version>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>1.3.1</version>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.5.0</version>
</dependency>
<!-- dbcp连接池 <dependency> <groupId>commons-dbcp</groupId> <artifactId>commons-dbcp</artifactId>
<version>1.4</version> </dependency> -->
<!-- 连接池 -->
<dependency>
<groupId>com.jolbox</groupId>
<artifactId>bonecp-spring</artifactId>
<version>0.8.0.RELEASE</version>
</dependency>
<!-- spring核心 -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-tx</artifactId>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aspects</artifactId>
</dependency>
<!-- Begin##添加JSP支持##Begin -->
<dependency>
<groupId>org.apache.tomcat.embed</groupId>
<artifactId>tomcat-embed-jasper</artifactId>
<scope>provided</scope>
</dependency>
<!-- End##添加JSP支持##Begin -->
</dependencies>
<build>
<finalName>${project.artifactId}</finalName>
<plugins>
<!-- 资源文件拷贝插件 -->
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-resources-plugin</artifactId>
<configuration>
<encoding>UTF-8</encoding>
</configuration>
</plugin>
<!-- java编译插件 -->
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>1.7</source>
<target>1.7</target>
<encoding>UTF-8</encoding>
</configuration>
</plugin>
<!-- Begin##03、添加SpringBoot的插件支持##Begin -->
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
<!-- End##03、添加SpringBoot的插件支持##End -->
</plugins>
<pluginManagement>
<plugins>
<!-- 配置Tomcat插件 -->
<plugin>
<groupId>org.apache.tomcat.maven</groupId>
<artifactId>tomcat7-maven-plugin</artifactId>
<version>2.2</version>
</plugin>
</plugins>
</pluginManagement>
</build>
</project>
二、创建包,创建controller类,如下:
package org.personal.qin.demo;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
@Controller //springmvc的controller控制器
@SpringBootApplication //springboot核心注解,目的是开启自动配置,scan会自动扫描该类所在的包或者子包
@Configuration
public class MainApplication {
@RequestMapping("hello")
@ResponseBody
public String hello() {
return "hello world!";
}
public static void main(String[] args) {
SpringApplication.run(MainApplication.class, args);
}
}
通过代码可以发现,hello方法是一个controller方法,我们通过浏览器访问hello就可以访问该controller。由于SpringBoot内置了Tomcat所以Web项目不需要部署,直接运行即可:鼠标右键-->run as-->Java Application?
三、测试,网址:http://127.0.0.1:8080/hello?
?四、将配置文件拷贝到src/main/resources文件夹中。
?五、配置mybatis。
1、MyBatis目录配置类Cast,Cast.java类的作用是用于配置MyBatis中配置文件及mapper、pom的位置。
package org.personal.qin.demo.config;
public class Cast {
//配置MyBatis
public static final String MYBATIS_CONFIG = "classpath:mybatis-config.xml";
public static final String PO_PACKAGE = "org.personal.qin.demo.po";
public static final String MAPPER_PACKAGE = "org.personal.qin.demo.mapper";
public static final String MAPPER_SCANNER = "classpath:config/mapper/*.xml";
}
2、MyBatis加载配置文件及配置数据源MyBatisConfig,MyBatisConfig.java类的作用是加载MyBatis配置文件,并配置数据源。
package org.personal.qin.demo.config;
import javax.sql.DataSource;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.boot.autoconfigure.SpringBootVFS;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.core.io.support.ResourcePatternResolver;
@Configuration
public class MyBatisConfig {
/**
* ConditionalOnMissingBean当容器里没有指定的Bean的情况下创建该对象
*/
@Bean
@ConditionalOnMissingBean
public SqlSessionFactory sqlSessionFactoryBean(DataSource dataSource) throws Exception {
SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
// 设置数据源
sqlSessionFactoryBean.setDataSource(dataSource);
// 添加一行如下代码,解决setTypeAliasesPackage别名设置不起作用问题
sqlSessionFactoryBean.setVfs(SpringBootVFS.class);
//设置mybatis的主配置文件
ResourcePatternResolver resourceResolver = new PathMatchingResourcePatternResolver();
Resource mybatisConfigXml = resourceResolver.getResource(Cast.MYBATIS_CONFIG);
sqlSessionFactoryBean.setConfigLocation(mybatisConfigXml);
// 设置别名包
sqlSessionFactoryBean.setTypeAliasesPackage(Cast.PO_PACKAGE);
PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
sqlSessionFactoryBean.setMapperLocations(resolver.getResources(Cast.MAPPER_SCANNER));
return sqlSessionFactoryBean.getObject();
}
}
3、Mapper扫描MapperScannerConfig,MapperScannerConfig.java类的作用是扫描Mapper。
package org.personal.qin.demo.config;
import org.mybatis.spring.mapper.MapperScannerConfigurer;
import org.springframework.boot.autoconfigure.AutoConfigureAfter;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
/**
* 保证在MybatisConfig类实例化后才实例化此方法
*/
@Configuration
@AutoConfigureAfter(MyBatisConfig.class)
public class MapperScannerConfig {
/**
* mapper接口的扫描器
*
* @return
*/
@Bean
public MapperScannerConfigurer mapperScannerConfigurer() {
MapperScannerConfigurer mapperScannerConfigurer = new MapperScannerConfigurer();
mapperScannerConfigurer.setBasePackage(Cast.MAPPER_PACKAGE);
return mapperScannerConfigurer;
}
}
五、配置SpringBoot。
BootApplication.java文件的作用是配置SpringBoot,并加载jdbc配置文件,配置数据库及数据库连接池,MainApplication.java提供了main方法,是该程序的入口以供程序运行。
package org.personal.qin.demo.config;
import javax.sql.DataSource;
import com.jolbox.bonecp.BoneCPDataSource;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
/**
* 配置文件读取和扫描
*/
@Configuration
@PropertySource(value = { "classpath:jdbc.properties" })
@ComponentScan(basePackages = "org.personal.qin.demo")
@SpringBootApplication
public class BootApplication {
@Value("${jdbc.driver}")
private String driverClassName; // 数据库驱动
@Value("${jdbc.url}")
private String url; // 相应驱动的jdbcUrl
@Value("${jdbc.username}")
private String username; // 数据库的用户名
@Value("${jdbc.password}")
private String password; // 数据库的密码
@Value("${jdbc.period_in_minutes}")
private int periodInMinutes; // 检查数据库连接池中空闲连接的间隔时间,单位是分,默认值:240,如果要取消则设置为0
@Value("${jdbc.max_age_in_minutes}")
private int maxAgeInMinutes; // 连接池中未使用的链接最大存活时间,单位是分,默认值:60,如果要永远存活设置为0
@Value("${jdbc.max_connections_per_partition}")
private int maxConnectionsPerPartition; // 每个分区最大的连接数
@Value("${jdbc.min_connections_per_partition}")
private int minConnectionsPerPartition; // 每个分区最小的连接数
/**
* 配置数据源
*
* @return
*/
@Bean(destroyMethod = "close")
public DataSource dataSource() {
BoneCPDataSource boneCPDataSource = new BoneCPDataSource();
boneCPDataSource.setDriverClass(driverClassName);
boneCPDataSource.setJdbcUrl(url);
boneCPDataSource.setUsername(username);
boneCPDataSource.setPassword(password);
boneCPDataSource.setIdleConnectionTestPeriodInMinutes(periodInMinutes);
boneCPDataSource.setIdleMaxAgeInMinutes(maxAgeInMinutes);
boneCPDataSource.setMaxConnectionsPerPartition(maxConnectionsPerPartition);
boneCPDataSource.setMinConnectionsPerPartition(minConnectionsPerPartition);
return boneCPDataSource;
}
protected SpringApplicationBuilder springApplicationBuilder(SpringApplicationBuilder builder) {
return builder.sources(BootApplication.class);
}
}
六、开始编写业务层代码Pojo、Mapper、Controller
1、Pojo User.java是Pojo
package org.personal.qin.demo.po;
?
public class User {
?
?? ?private int id;
?? ?private String name;
?? ?private String password;
?
?? ?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 String getPassword() {
?? ??? ?return password;
?? ?}
?
?? ?public void setPassword(String password) {
?? ??? ?this.password = password;
?? ?}
?
?? ?@Override
?? ?public String toString() {
?? ??? ?return "【User】: name=" + name + ", password=" + password;
?? ?}
?
}
2、Mapper UserMapper.java是Mapper接口,UserMapper.xml是操作数据库的配置文件。
package org.personal.qin.demo.mapper;
?
import java.util.List;
?
import org.personal.qin.demo.po.User;
?
public interface UserMapper {
?
? ? /**
? ? ?* 获取全部用户
? ? ?*?
? ? ?* @return
? ? ?*/
? ? List<User> listAll();
?
}
<?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="org.personal.qin.demo.mapper.UserMapper">
?? ?<select id="listAll" resultType="User">
?? ??? ?select * from t_user
?? ?</select>
</mapper>
3、Controller UserController.java是控制器,提供给web访问
package org.personal.qin.demo.controller;
?
import java.util.List;
?
import org.personal.qin.demo.mapper.UserMapper;
import org.personal.qin.demo.po.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
?
@Controller
public class UserController {
?
? ? @Autowired
? ? private UserMapper mapper;
?
? ? @RequestMapping("/users")
? ? @ResponseBody
? ? public Object getAllUser() {
? ? ? ? List<User> users = mapper.listAll();
? ? ? ? return users;
? ? }
?
}
七、浏览器测试,网址:http://127.0.0.1:8080/users 运行MainApplication.java中的main方法
?八、在配置包下添加springMVCconfig。
package org.personal.qin.demo.config;
import java.nio.charset.Charset;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
@Configuration //申明这是一个配置
public class SrpingMVCConfig extends WebMvcConfigurerAdapter {
/**
* 自定义拦截器
*/
@Override
public void addInterceptors(InterceptorRegistry registry) {
HandlerInterceptor handlerInterceptor = new HandlerInterceptor() {
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
throws Exception {
System.out.println("自定义拦截器............");
return true;
}
@Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
ModelAndView modelAndView) throws Exception {
}
@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler,
Exception ex) throws Exception {
}
};
registry.addInterceptor(handlerInterceptor).addPathPatterns("/**");
}
/**
* 自定义消息转化器的第二种方法
*/
@Override
public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
StringHttpMessageConverter converter = new StringHttpMessageConverter(Charset.forName("UTF-8"));
converters.add(converter);
}
}
九、测试,运行MainApplication.java中的main方法。
如此,我们便在springboot中集成了mybatis和springVMC,快行动起来试试。?
|