SpringBoot之SpringBoot+Mybatis+Mysql+Maven整合

软件环境

eclipse

jdk1.8

maven3.5

mysql5.6

SpringBoot1.5.0

增加一个maven工程

建立对应包名

com.zns.config

com.zns.controller

com.zns.service

com.zns.dao.mapper

com.zns.model

最终文件目录结构为

src/main/java
com.zns.config
	DruidDataSourceConfig.java
	MyBatisConfig.java
	MyBatisMapperScannerConfig.java
com.zns.controller
	ProductController.java
com.zns.service
	ProductService.java
	impl
	    ProductServiceImpl.java
com.zns.dao.mapper
	ProductMapper.java
com.zns.model
	Product.java
Application.java

src/main/resources
mybatis
	mapper
		ProductMapper.xml
	mybatis-config.xml
application.yml
banner.txt

pom.xml

<parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.5.0.RELEASE</version>
    </parent>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-jdbc</artifactId>
        </dependency>
        <!-- mybatis 包 -->
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.2.8</version>
        </dependency>
        <!--mybatis和spring整合包 -->
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis-spring</artifactId>
            <version>1.2.2</version>
        </dependency>
        <!--mybatis分页插件 -->
        <dependency>
            <groupId>com.github.pagehelper</groupId>
            <artifactId>pagehelper</artifactId>
            <version>4.2.0</version>
        </dependency>
        <!-- mybatis通用mapper -->
        <dependency>
            <groupId>tk.mybatis</groupId>
            <artifactId>mapper</artifactId>
            <version>3.3.0</version>
        </dependency>
        <!-- mysql连接驱动 -->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.34</version>
        </dependency>
        <!-- druid连接池 -->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid</artifactId>
            <version>1.0.20</version>
        </dependency>
    </dependencies>

    <build>
        <finalName>${project.artifactId}</finalName>
        <plugins>
            <!-- java编译插件 -->
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <configuration>
                    <source>1.8</source>
                    <target>1.8</target>
                    <encoding>UTF-8</encoding>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

application.yml

server:
  port: 8080
  context-path: / 

#mysql数据源和连接池配置  
spring:
    datasource:
        name: test
        url: jdbc:mysql://localhost:3306/mydb1
        username: root
        password: 123456
        #使用druid数据源
        type: com.alibaba.druid.pool.DruidDataSource
        driver-class-name: com.mysql.jdbc.Driver
        filters: stat
        maxActive: 20
        initialSize: 1
        maxWait: 60000
        minIdle: 1
        timeBetweenEvictionRunsMillis: 60000
        minEvictableIdleTimeMillis: 300000
        validationQuery: select ‘x‘
        testWhileIdle: true
        testOnBorrow: false
        testOnReturn: false
        poolPreparedStatements: true
        maxOpenPreparedStatements: 20

DruidDataSourceConfig.java

package com.zns.config;

import java.sql.SQLException;
import java.util.HashMap;
import java.util.Map;
import javax.sql.DataSource;
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.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.PlatformTransactionManager;
import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.support.http.StatViewServlet;
import com.alibaba.druid.support.http.WebStatFilter;

@Configuration
public class DruidDataSourceConfig {
    /**
     * 配置DruidDataSource
     *
     * @return
     */
    @Bean
    @ConfigurationProperties(prefix = "spring.datasource")
    public DataSource druidDataSource() {
        DruidDataSource druidDataSource = new DruidDataSource();
        return druidDataSource;
    }

    /**
     * 配置transactionManager
     *
     * @return
     */
    @Bean
    public PlatformTransactionManager transactionManager() throws SQLException {
        return new DataSourceTransactionManager(druidDataSource());
    }

    /**
     * 注册DruidServlet
     *
     * @return
     */
    @Bean
    public ServletRegistrationBean druidServletRegistrationBean() {
        ServletRegistrationBean servletRegistrationBean = new ServletRegistrationBean();
        servletRegistrationBean.setServlet(new StatViewServlet());
        servletRegistrationBean.addUrlMappings("/druid/*");
        //登录查看信息的账号密码.
        servletRegistrationBean.addInitParameter("loginUsername", "admin");
        servletRegistrationBean.addInitParameter("loginPassword", "123456");
        return servletRegistrationBean;
    }

    /**
     * 注册DruidFilter拦截
     *
     * @return
     */
    @Bean
    public FilterRegistrationBean duridFilterRegistrationBean() {
        FilterRegistrationBean filterRegistrationBean = new FilterRegistrationBean();
        filterRegistrationBean.setFilter(new WebStatFilter());
        Map<String, String> initParams = new HashMap<String, String>();
        // 设置忽略请求
        initParams.put("exclusions", "*.js,*.gif,*.jpg,*.bmp,*.png,*.css,*.ico,/druid/*");
        filterRegistrationBean.setInitParameters(initParams);
        filterRegistrationBean.addUrlPatterns("/*");
        return filterRegistrationBean;
    }
}

MyBatisConfig.java

package com.zns.config;

import javax.sql.DataSource;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.core.io.support.ResourcePatternResolver;

@Configuration
@MapperScan("com.zns.dao.mapper")//mapper扫描包路径
public class MyBatisConfig {
    @Bean
    @ConditionalOnMissingBean // 当容器里没有指定的Bean的情况下创建该对象
    public SqlSessionFactoryBean sqlSessionFactory(DataSource dataSource) throws Exception {
        SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
        // 设置数据源
        sqlSessionFactoryBean.setDataSource(dataSource);
        ResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
        // 设置mybatis的主配置文件
        sqlSessionFactoryBean.setConfigLocation(resolver.getResource("classpath:mybatis/mybatis-config.xml"));
        // 设置mybatis的mapper文件路径
        sqlSessionFactoryBean.setMapperLocations(resolver.getResources("classpath:mybatis/mapper/*.xml"));
        // 设置别名包
        // sqlSessionFactoryBean.setTypeAliasesPackage("com.zns.model");

        // 代码方式配置PageHelper插件
        /*
         * PageHelper pageHelper = new PageHelper(); Properties properties = new
         * Properties(); properties.setProperty("reasonable", "true");
         * properties.setProperty("supportMethodsArguments", "true");
         * properties.setProperty("returnPageInfo", "check");
         * properties.setProperty("params", "count=countSql");
         * pageHelper.setProperties(properties);
         * sqlSessionFactoryBean.setPlugins(new Interceptor[]{pageHelper});
         */

        return sqlSessionFactoryBean;
    }
}

MyBatisMapperScannerConfig.java

package com.zns.config;

import java.util.Properties;
import org.springframework.boot.autoconfigure.AutoConfigureAfter;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import tk.mybatis.mapper.common.BaseMapper;
import tk.mybatis.spring.mapper.MapperScannerConfigurer;

@Configuration
@AutoConfigureAfter(MyBatisConfig.class)
public class MyBatisMapperScannerConfig {
    @Bean
    public MapperScannerConfigurer mapperScannerConfigurer() {
        MapperScannerConfigurer mapperScannerConfigurer = new MapperScannerConfigurer();
        mapperScannerConfigurer.setSqlSessionFactoryBeanName("sqlSessionFactoryBean");
        // 设置mapper扫描包路径
        mapperScannerConfigurer.setBasePackage("com.zns.dao.mapper");
        // 继承了BaseMapper接口的才会被扫描
        //mapperScannerConfigurer.setMarkerInterface(BaseMapper.class);

        // 配置通用mapper插件
        Properties properties = new Properties();
        // 通用mapper包路径
        properties.setProperty("mappers", BaseMapper.class.getName());
        properties.setProperty("notEmpty", "false");
        properties.setProperty("IDENTITY", "MYSQL");
        mapperScannerConfigurer.setProperties(properties);

        return mapperScannerConfigurer;
    }
}

mybatis-config.xml

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
  PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
  "http://mybatis.org/dtd/mybatis-3-config.dtd">

<configuration>
    <!-- 返回resultType为map时,如果数据为空的字段,则该字段会省略不显示, 可以通过添加该配置,返回null -->
    <settings>
        <setting name="callSettersOnNulls" value="true" />
    </settings>

    <plugins>
        <!-- 配置分页插件 -->
        <plugin interceptor="com.github.pagehelper.PageHelper">
            <!-- 设置数据库类型 Oracle,Mysql,MariaDB,SQLite,Hsqldb,PostgreSQL六种数据库 -->
            <property name="dialect" value="mysql" />
        </plugin>
    </plugins>

</configuration>

Product.java

package com.zns.model;

import javax.persistence.Column;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;

@Table(name = "product")
public class Product {
    @Id
    @Column(name = "id")
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Integer id;
    private String name;
    public Integer getId() {
        return id;
    }
    public void setId(Integer id) {
        this.id = id;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }

}

ProductMapper.java

package com.zns.dao.mapper;

import com.github.pagehelper.Page;
import com.zns.model.Product;
import tk.mybatis.mapper.common.BaseMapper;

public interface ProductMapper extends BaseMapper<Product> {
    public Product getById(Integer id);
    public Page<Product> getPagerList();
}

ProductMapper.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="com.zns.dao.mapper.ProductMapper">
    <select id="getById" parameterType="int" resultType="com.zns.model.Product">
        select id,name from product where id=#{id}
    </select>
    <select id="getPagerList" resultType="com.zns.model.Product">
        select id,name from product
    </select>
</mapper>

ProductService.java

package com.zns.service;

import com.github.pagehelper.Page;
import com.zns.model.Product;

public interface ProductService {
    public Product getById(Integer id);
    public Page<Product> getPagerList(Integer pageIndex,Integer pageSize);
    public Product selectByPrimaryKey(Integer id);
}

ProductServiceImpl.java

package com.zns.service.impl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.zns.dao.mapper.ProductMapper;
import com.zns.model.Product;
import com.zns.service.ProductService;

@Service
public class ProductServiceImpl implements ProductService {
    @Autowired
    private ProductMapper productMapper;

    public Product getById(Integer id){
        return productMapper.getById(id);
    }

    public Page<Product> getPagerList(Integer pageIndex,Integer pageSize){
        PageHelper.startPage(pageIndex, pageSize);
        return productMapper.getPagerList();
    }

    public Product selectByPrimaryKey(Integer id){
        return productMapper.selectByPrimaryKey(id);
    }
}

ProductController.java

package com.zns.controller;

import java.util.List;
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.Page;
import com.zns.model.Product;
import com.zns.service.ProductService;

@RestController
@RequestMapping("/product")
public class ProductController {
    @Autowired
    private ProductService productService;

    @RequestMapping("/get")
    public Product get(Integer id) {
        System.out.println("id为:" + id);
        return productService.getById(id);
    }

    @RequestMapping("/getPagerList")
    public Object getPagerList() {
        Page<Product> pageInfo = productService.getPagerList(1, 10);
        List<Product> list = pageInfo.getResult();
        long totalCount = pageInfo.getTotal();
        for (Product item : list) {
            System.out.println(item.getId() + "--" + item.getName());
        }
        System.out.println(totalCount);
        return list;
    }

    @RequestMapping("/getByKey")
    public Product getByKey(Integer id) {
        System.out.println("id为:" + id);
        return productService.selectByPrimaryKey(id);
    }
}

项目启动类Application.java

package com.zns;

import org.springframework.boot.Banner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.transaction.annotation.EnableTransactionManagement;

@ComponentScan(basePackages="com.zns")
@EnableTransactionManagement //如果service实现类中加入事务注解@Transactional,需要此处添加该注解
@SpringBootApplication
public class Application {
    public static void main(String[] args) {
        SpringApplication application = new SpringApplication(Application.class);
        //设置启动时是否显示banner图
        application.setBannerMode(Banner.Mode.OFF);
        application.run(args);
    }
}

浏览器访问测试

http://localhost:8080/product/get?id=1

druid监控后台地址

http://localhost:8080/druid/index.html

原文地址:https://www.cnblogs.com/zengnansheng/p/10389782.html

时间: 2024-10-22 05:22:44

SpringBoot之SpringBoot+Mybatis+Mysql+Maven整合的相关文章

freemarker + spring mvc + spring + mybatis + mysql + maven项目搭建

今天说说搭建项目,使用freemarker + spring mvc + spring + mybatis + mysql + maven搭建web项目. 先假设您已经配置好eclipse的maven,创建好一个maven的web项目--Demo.我这里是jdk1.7,tomcat7. 修改pom.xml如下: <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/

myBatis+SpringMVC+Maven整合

一.先创建表结构 二.使用generator通过表结构自动生成model和dao.mapper 使用步骤: 1.解压generator.rar文件 2.文件中的generator.xml文件需要进行修改,修改里面的文件生成地址 3.打开生成语句.txt文件,复制出里面的内容,回到该文件所在目录下,右键-->打开命令窗口,将该命令执行,将会在相应的目录下生成文件Model,Dao.Mapper 生成的文件包括mapper.xml中生成的封装语句,已办是不够用的,需要后期添加和修改 注意:文件路径不

Spring+Mybatis+MySql+Maven 简单的事务管理案例

利用Maven来管理项目中的JAR包,同时使用Spring在业务处理层进行事务管理.数据库使用MySq,数据处理层使用Spring和Mybatis结合. 本案例代码主要结构如图: 1.数据库脚本 -- ---------------------------- -- Table structure for `user` -- ---------------------------- DROP TABLE IF EXISTS `user`; CREATE TABLE `user` (   `id` 

springmvc学习总结(二) -- maven+springmvc+spring+mybatis+mysql详细搭建整合过程讲解

@[email protected] 写在最前 之前分享过下面这几篇: mybatis学习笔记(五) -- maven+spring+mybatis从零开始搭建整合详细过程(上)(附demo和搭建过程遇到的问题解决方法) mybatis学习笔记(六) -- maven+spring+mybatis从零开始搭建整合详细过程(下) springmvc学习笔记(一) -- 从零搭建,基础入门 这一篇,在这些练习的基础上,将它们整合在一起! 搭建步骤如下 一.新建maven项目,配置环境,测试是否配置成

日常开发系列——Maven+Spring+Spring MVC+MyBatis+MySQL整合SSM框架

进入公司开发已经3个多月了,项目用的是Maven+Spring+Spring MVC+MyBatis+MySQL,趁这个周末有空,仔细研读一下公司项目的基本框架,学习一下这个环境是怎么搭建起来的,经过自己的研究终于是成功地试验出来.自己亲手做的才算是自己学到的,决定将其记录下来,以便日后查询,源码同时也欢迎大家拍砖. 一.数据库的准备 这次整合试验想着做个简单的,就决定做一个普通的用户登陆,就一张表吧 我新建的数据库名字是test,然后新建了一张表 DROP TABLE IF EXISTS `u

记一次springboot访问linux的mysql数据库

今天使用springboot连接linux的mysql,期间一直报错,这里简单记录一下过程. 工具:idea-2017,linux-7.x,mysql-5.6.40. 首先说一下这几个注解的作用: (1)Spring Boot的@SpringBootApplication.@EnableAutoConfiguration.@ComponentScan注解,我经常在启动类上傻傻分不清, (2)@EnableAutoConfiguration这个注解是是Springboot根据我们所引入的jar包自

Spring+SpringMVC+Mybatis+Mysql整合实例【转】

本文要实现Spring+SpringMVC+Mybatis+Mysql的一个整合,实现了SpringMVC控制访问的页面,将得到的页面参数传递给Spring中的Mybatis的bean类,然后查找Mysql数据的功能,并通过JSP显示出来.建议可以先看笔者另一文章Mybatis与Spring整合创建Web项目 .笔者觉得整合过程中问题比较多的还是Spring+Mybatis的整合,SpringMVC的整合还是比较简单. Spring        Spring 是一个开源框架, Spring 是

Maven 整合 Spring + MyBatis

Maven 整合 Spring + MyBatis 存记录备忘,根据网上搜的孙宇老师的一个视频整理而成 一.搭建工程 使用Intellij搭建工程(由于eclipse对maven支持不如Intellij,所以选用Intellij,eclipse搭建工程相对复杂,可以百度相关文章). 搭建工程十分简单,建好之后直接进入mybatis 与 Spring整合. 二.整合Mybatis 工程搭建好之后已经包含以下jar包,版本为4.1.1.RELEASE 1 <dependency> 2 <gr

Spring+Mybatis+Maven 整合配置

1 <?xml version="1.0" encoding="UTF-8"?> 2 <beans default-autowire="byName" 3 xmlns="http://www.springframework.org/schema/beans" 4 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 5 xsi:sche