springboot整合mybatis实现ssm框架(druid连接池)

springboot整合mybatis实现ssm框架(druid连接池)

1.创建一个maven的web项目,项目结构如下

2.编写pom.xml添加jar包依赖和maven打包插件等配置

<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.pypua</groupId>
  <artifactId>springboot-ssm</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  <packaging>jar</packaging>

  <name>springboot-ssm</name>
  <url>http://maven.apache.org</url>
<!-- spring boot parent节点,引入这个之后,在下面和spring boot相关的就不需要引入版本了; -->
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.4.1.RELEASE</version>
    </parent>
  <properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<!-- 指定一下jdk的版本 ,这里我们使用jdk 1.8 ,默认是1.6 -->
    <java.version>1.8</java.version>
    <version.spring>3.2.9.RELEASE</version.spring>
    <version.jackson>2.4.4</version.jackson>
  </properties>

  <dependencies>
<!-- web支持: 1、web mvc; 2、restful; 3、jackjson支持; 4、aop ........ -->
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
<!--模板引擎,有很多种, 什么freemarker什么的, 这个thymeleaf是官方推荐的,具体可以百度 
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-thymeleaf</artifactId>
    </dependency>
    -->
<!-- oracle 数据库驱动. -->
    <dependency>
        <groupId>com.oracle</groupId>
        <artifactId>ojdbc6</artifactId>
        <version>11.2.0.1.0</version>
    </dependency>
<!-- 阿里数据库连接池 -->
    <dependency>
       <groupId>com.alibaba</groupId>
       <artifactId>druid</artifactId>
       <version>1.0.20</version>
    </dependency>
<!--添加适用于生产环境的功能,如性能指标和监测等功能。 -->
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-actuator</artifactId>
    </dependency>
<!-- mybatis相关 -->
    <dependency>
        <groupId>org.mybatis</groupId>
        <artifactId>mybatis-spring</artifactId>
        <version>1.2.2</version>
    </dependency>
    <dependency>
        <groupId>org.mybatis</groupId>
        <artifactId>mybatis</artifactId>
        <version>3.2.8</version>
    </dependency> 
<!-- 对redis键值数据存储的支持,包括spring-redis -->  
    <dependency>  
        <groupId>org.springframework.boot</groupId>  
        <artifactId>spring-boot-starter-redis</artifactId>  
    </dependency>
<!-- springboot对缓存的支持 -->  
    <dependency>  
        <groupId>org.springframework.boot</groupId>  
        <artifactId>spring-boot-starter-cache</artifactId>  
    </dependency>
<!-- springBoot对jdbc数据库的支持 -->  
    <dependency>  
        <groupId>org.springframework.boot</groupId>  
        <artifactId>spring-boot-starter-jdbc</artifactId>  
    </dependency>  
<!-- springBoot的默认日志系统lockback -->  
    <dependency>  
        <groupId>org.springframework.boot</groupId>  
        <artifactId>spring-boot-starter-logging</artifactId>  
    </dependency>  
<!-- 面向切面变成的支持,包括spring-aop和Aspectj -->  
    <dependency>  
        <groupId>org.springframework.boot</groupId>  
        <artifactId>spring-boot-starter-aop</artifactId>  
    </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>
<!-- 
      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>
<!-- aspectJ -->
    <dependency>
        <groupId>org.aspectj</groupId>
        <artifactId>aspectjweaver</artifactId>
    </dependency>
<!-- servlet 依赖. -->
    <dependency>
        <groupId>javax.servlet</groupId>
        <artifactId>javax.servlet-api</artifactId>
        <scope>provided</scope>
    </dependency>
<!--阿里快速json-->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>1.1.43</version>
        </dependency>
<!-- springMVC -->
        <dependency>
            <groupId>com.mangofactory</groupId>
            <artifactId>swagger-springmvc</artifactId>
            <version>0.9.5</version>
        </dependency>
<!-- jackson -->
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-annotations</artifactId>
            <version>${version.jackson}</version>
        </dependency>
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-databind</artifactId>
            <version>${version.jackson}</version>
        </dependency>
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-core</artifactId>
            <version>${version.jackson}</version>
        </dependency>   
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>3.8.1</version>
      <scope>test</scope>
    </dependency>
  </dependencies>
<build>
  <testSourceDirectory>src/test/java</testSourceDirectory>
  <finalName>spring-boot-ssm</finalName>
  <plugins>
     <plugin>
        <artifactId>maven-compiler-plugin</artifactId>
        <version>3.1</version>
        <configuration>
            <source>1.8</source>
            <target>1.8</target>
        </configuration>
     </plugin>
     <!-- maven逆向工程插件 -->  
          <plugin>  
              <groupId>org.mybatis.generator</groupId>  
              <artifactId>mybatis-generator-maven-plugin</artifactId>  
              <version>1.3.2</version>  
              <configuration>  
                  <verbose>true</verbose>  
                  <overwrite>true</overwrite>  
              </configuration>  
          </plugin>
          <plugin>
                <artifactId>maven-war-plugin</artifactId>
                <version>2.5</version>
                <configuration>
                    <warSourceDirectory>src/main/webapp</warSourceDirectory>
                    <failOnMissingWebXml>false</failOnMissingWebXml>
                </configuration>
            </plugin>
  </plugins>
  
  <resources>  
          <resource>  
              <directory>src/main/java</directory>  
              <includes>  
                  <include>**/*.xml</include>  
              </includes>  
          </resource>  
          <resource>  
              <directory>src/main/resources</directory>  
              <includes>  
                  <include>**/*.xml</include>  
                  <include>**/*.properties</include>  
              </includes>  
          </resource>  
    </resources>
</build>
</project>

3.编写配置问件application.properties

# \u9875\u9762\u9ed8\u8ba4\u524d\u7f00\u76ee\u5f55
spring.mvc.view.prefix=/view
# \u54cd\u5e94\u9875\u9762\u9ed8\u8ba4\u540e\u7f00
spring.mvc.view.suffix=.jsp


#mybatis.mapper-locations=com.pypua.mapper.*.xml  

#\u6570\u636E\u5E93\u8BBF\u95EE\u914D\u7F6E
#mysql
#spring.datasource.type=com.alibaba.druid.pool.DruidDataSource
#spring.datasource.driver-class-name=com.mysql.jdbc.Driver
#spring.datasource.url=jdbc:mysql://localhost:3306/blog
#oracle
spring.datasource.driverClassName=oracle.jdbc.driver.OracleDriver
spring.datasource.url=jdbc:oracle:thin:@localhost:1521:ORCL
spring.datasource.username=test1
spring.datasource.password=pypua

#\u8FDE\u63A5\u6C60\u914D\u7F6E
spring.datasource.initialSize=5
spring.datasource.minIdle=5
spring.datasource.maxActive=20
#\u8FDE\u63A5\u7B49\u5F85\u8D85\u65F6\u65F6\u95F4
spring.datasource.maxWait=60000
#\u914D\u7F6E\u9694\u591A\u4E45\u8FDB\u884C\u4E00\u6B21\u68C0\u6D4B(\u68C0\u6D4B\u53EF\u4EE5\u5173\u95ED\u7684\u7A7A\u95F2\u8FDE\u63A5)
spring.datasource.timeBetweenEvictionRunsMillis=60000
#\u914D\u7F6E\u8FDE\u63A5\u5728\u6C60\u4E2D\u7684\u6700\u5C0F\u751F\u5B58\u65F6\u95F4
spring.datasource.minEvictableIdleTimeMillis=300000
spring.datasource.validationQuery=SELECT 1 FROM DUAL
spring.datasource.testWhileIdle=true
spring.datasource.testOnBorrow=false
spring.datasource.testOnReturn=false
# \u6253\u5F00PSCache\uFF0C\u5E76\u4E14\u6307\u5B9A\u6BCF\u4E2A\u8FDE\u63A5\u4E0APSCache\u7684\u5927\u5C0F
spring.datasource.poolPreparedStatements=true
spring.datasource.maxPoolPreparedStatementPerConnectionSize=20
# \u914D\u7F6E\u76D1\u63A7\u7EDF\u8BA1\u62E6\u622A\u7684filters\uFF0C\u53BB\u6389\u540E\u76D1\u63A7\u754C\u9762sql\u65E0\u6CD5\u7EDF\u8BA1\uFF0C'wall'\u7528\u4E8E\u9632\u706B\u5899
spring.datasource.filters=stat,wall,log4j
# \u901A\u8FC7connectProperties\u5C5E\u6027\u6765\u6253\u5F00mergeSql\u529F\u80FD\uFF1B\u6162SQL\u8BB0\u5F55
spring.datasource.connectionProperties=druid.stat.mergeSql=true;druid.stat.slowSqlMillis=5000

4.添加log4j日志文件

#config root logger
log4j.rootLogger = INFO,system.out
log4j.appender.system.out=org.apache.log4j.ConsoleAppender
log4j.appender.system.out.layout=org.apache.log4j.PatternLayout
log4j.appender.system.out.layout.ConversionPattern=[Log] %5p[%F:%L]:%m%n

#config this Project.file logger
log4j.logger.thisProject.file=INFO,thisProject.file.out
log4j.appender.thisProject.file.out=org.apache.log4j.DailyRollingFileAppender
log4j.appender.thisProject.file.out.File=logContentFile.log
log4j.appender.thisProject.file.out.layout=org.apache.log4j.PatternLayout

5.编写连接池配置文件DruidConfiguration.java配置监控台等信息

package com.pypua.config;


import java.sql.SQLException;

import javax.sql.DataSource;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.aop.framework.autoproxy.BeanNameAutoProxyCreator;
import org.springframework.boot.bind.RelaxedPropertyResolver;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.boot.web.servlet.ServletRegistrationBean;
import org.springframework.context.EnvironmentAware;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.core.env.Environment;
import org.springframework.transaction.annotation.EnableTransactionManagement;

import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.support.http.StatViewServlet;
import com.alibaba.druid.support.http.WebStatFilter;
import com.alibaba.druid.support.spring.stat.DruidStatInterceptor;

/**  
 * Druid的DataResource配置类  
 * 凡是被Spring管理的类,实现接口 EnvironmentAware 重写方法 setEnvironment 可以在工程启动时,  
 * 获取到系统环境变量和application配置文件中的变量。 还有一种方式是采用注解的方式获取 @value("${变量的key值}")  
 * 获取application配置文件中的变量。 这里采用第一种要方便些  
 * Created by sun on 2017-1-20.  
 */
@Configuration
@EnableTransactionManagement
public class DruidConfiguration implements EnvironmentAware{

    private static final Logger logger = LoggerFactory.getLogger(DruidConfiguration.class);

    private static final String DB_PREFIX = "spring.datasource";
    private RelaxedPropertyResolver propertyResolver;
    @Override
    public void setEnvironment(Environment env) {
        this.propertyResolver = new RelaxedPropertyResolver(env, "spring.datasource.");
        
    }
    @Bean  
    public DataSource dataSource() {  
        DruidDataSource datasource = new DruidDataSource();  
        datasource.setUrl(propertyResolver.getProperty("url"));  
        datasource.setDriverClassName(propertyResolver.getProperty("driverClassName"));  
        datasource.setUsername(propertyResolver.getProperty("username"));  
        datasource.setPassword(propertyResolver.getProperty("password"));  
        datasource.setInitialSize(Integer.valueOf(propertyResolver.getProperty("initialSize")));  
        datasource.setMinIdle(Integer.valueOf(propertyResolver.getProperty("minIdle")));  
        datasource.setMaxWait(Long.valueOf(propertyResolver.getProperty("maxWait")));  
        datasource.setMaxActive(Integer.valueOf(propertyResolver.getProperty("maxActive")));  
        datasource.setMinEvictableIdleTimeMillis(  
                Long.valueOf(propertyResolver.getProperty("minEvictableIdleTimeMillis")));  
        try {  
            datasource.setFilters("stat,wall");  
        } catch (SQLException e) {  
            e.printStackTrace();  
        }  
        return datasource;  
    }
    
     /**
     * 注册ServletRegistrationBean
     * @return
     */
    @Bean
    public ServletRegistrationBean druidServlet() {
        logger.info("init Druid Servlet Configuration ");
        ServletRegistrationBean servletRegistrationBean = new ServletRegistrationBean(new StatViewServlet(), "/druid/*");
        /** 初始化参数配置,initParams**/
        // IP白名单,多个ip逗号隔开
        servletRegistrationBean.addInitParameter("allow", "localhost,localhost");
        // IP黑名单(共同存在时,deny优先于allow)如果满足deny的话提示:Sorry, you are not permitted to view this page.
        servletRegistrationBean.addInitParameter("deny", "192.168.1.100");
        //控制台管理用户
        servletRegistrationBean.addInitParameter("loginUsername", "admin");
        servletRegistrationBean.addInitParameter("loginPassword", "admin");
        //是否能够重置数据 禁用HTML页面上的“Reset All”功能
        servletRegistrationBean.addInitParameter("resetEnable", "false");
        return servletRegistrationBean;
    }
    /**
     * 注册FilterRegistrationBean
     * @return
     */
    @Bean
    public FilterRegistrationBean filterRegistrationBean() {
        
        FilterRegistrationBean filterRegistrationBean = new FilterRegistrationBean(new WebStatFilter());
         //添加过滤规则.
        filterRegistrationBean.addUrlPatterns("/*");
         //添加不需要忽略的格式信息.
        filterRegistrationBean.addInitParameter("exclusions", "*.js,*.gif,*.jpg,*.png,*.css,*.ico,/druid/*");
        return filterRegistrationBean;
    }
    
    // 按照BeanId来拦截配置 用来bean的监控  
    @Bean(value = "druid-stat-interceptor")  
    public DruidStatInterceptor DruidStatInterceptor() {  
        DruidStatInterceptor druidStatInterceptor = new DruidStatInterceptor();  
        return druidStatInterceptor;  
    }  
  
    @Bean  
    public BeanNameAutoProxyCreator beanNameAutoProxyCreator() {  
        BeanNameAutoProxyCreator beanNameAutoProxyCreator = new BeanNameAutoProxyCreator();  
        beanNameAutoProxyCreator.setProxyTargetClass(true);  
        // 设置要监控的bean的id  
        //beanNameAutoProxyCreator.setBeanNames("sysRoleMapper","loginController");  
        beanNameAutoProxyCreator.setInterceptorNames("druid-stat-interceptor");  
        return beanNameAutoProxyCreator;  
    } 
}

6.编写App启动类文件App.java

package com.pypua;

import javax.sql.DataSource;

import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.log4j.Logger;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.web.servlet.ServletComponentScan;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.PlatformTransactionManager;




/**
 * Hello world!
 *
 */
@SpringBootApplication
@ServletComponentScan
@MapperScan("com.pypua.mapper")// 表示Mybatis的映射路径
public class App 
{
     private static Logger logger = Logger.getLogger(App.class);
     // DataSource配置
        // 表示将根据前缀“spring.datasource”从application.properties中匹配相关属性值
        @Bean
        @ConfigurationProperties(prefix="spring.datasource")
        public DataSource dataSource() {
            return new  com.alibaba.druid.pool.DruidDataSource();
        }
        // 提供SqlSeesion
        @Bean
        public SqlSessionFactory sqlSessionFactoryBean() throws Exception {

            SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
            sqlSessionFactoryBean.setDataSource(dataSource());

            PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();

            sqlSessionFactoryBean.setMapperLocations(resolver.getResources("com.pypua.mapper.*.xml"));

            return sqlSessionFactoryBean.getObject();
        }
        @Bean
        public PlatformTransactionManager transactionManager() {
            return new DataSourceTransactionManager(dataSource());
        }
        /**
         * Start
         */
    public static void main( String[] args )
    {
        SpringApplication.run(App.class, args);
        logger.info("SpringBoot Start Success");
    }
}

7.TicketChooseController.java

package com.pypua.controller;

import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

import com.pypua.entity.Student;
import com.pypua.service.ticketChooseService;




@Controller
@Scope("prototype")
public class TicketChooseController{
    private Logger logger = Logger.getLogger(TicketChooseController.class);
    @Autowired
    private ticketChooseService ticketchooseservice;
    
    @RequestMapping(value = "/ticket/choose/list",method = {RequestMethod.GET,RequestMethod.POST})
    public ModelAndView initial(HttpServletRequest request,
            HttpServletResponse response,
             @RequestParam(value = "studentNo", required = false) String studentNo
             )throws Exception{
        System.out.println("in door");
        List<Student> studentList = ticketchooseservice.findStudentInfoByStudNo(studentNo);
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.addObject("studentList", studentList);
        modelAndView.setViewName("/ticket/choose/studentList");
        return modelAndView;
    }
}

 

8.studentList.jsp

<%@ page language="java" contentType="text/html; charset=utf-8"
    pageEncoding="utf-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<%@ include file="/view/common/resource.jsp" %>
<%@ include file="/view/common/tags.jsp" %>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Insert title here</title>
</head>
<body>
<h1>hahaha</h1>
<table>
  <tbody>
    <tr>
      <td>学号 </td>
      <td>班级</td>
      <td>姓名</td>
      <td>成绩</td>
      <td>所属部门</td>
    </tr>
     <c:forEach items="${studentList }" var="student" varStatus="status">
     <tr>
      <td>${student.stuno}</td>
      <td>${student.classid}</td>
      <td>${student.sname}</td>
      <td>${student.gread}</td>
      <td>${student.dept}</td>
     </tr>
   </c:forEach>
  </tbody>
</table>
  
</body>
</html>

 

其他entity文,services,impl这里就不一一粘贴了,至此,整合完毕

运行结果:

druid数据源监控台显示

程序运行结果如图所示

 

posted @ 2017-08-18 17:46  十月围城小童鞋  阅读(1482)  评论(0编辑  收藏  举报