springboot整合mybatis(SSM開發環境搭建)&Springboot項目熱部署


0.項目結構:

 

---------------------方法一:使用mybatis官方提供的Spring Boot整合包實現---------------------

 1.application.properties中配置整合mybatis的配置文件、mybatis掃描別名的基本包與數據源

server.port=80

logging.level.org.springframework=DEBUG
#springboot   mybatis
#jiazai mybatis peizhiwenjian
mybatis.mapper-locations = classpath:mapper/*Mapper.xml mybatis.config-location = classpath:mapper/config/sqlMapConfig.xml mybatis.type-aliases-package = cn.qlq.bean

#shujuyuan
spring.datasource.driver-class-name= com.mysql.jdbc.Driver spring.datasource.url = jdbc:mysql://localhost:3306/test1?useUnicode=true&characterEncoding=utf-8
spring.datasource.username = root
spring.datasource.password = 123456

 

 2.pom.xml加入springboot整合mybatis的jar包與數據庫驅動包

<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.qlq</groupId>
  <artifactId>springboot-ssm</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  <packaging>war</packaging>
  
  <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.5.2.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-test</artifactId>
            <scope>test</scope>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-devtools</artifactId>
        </dependency>
        <!-- spring-boot整合mybatis -->
        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>1.1.1</version>
        </dependency>
        <!-- mysql驅動 -->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.6</version>
        </dependency>
        
        
        
        
        
          <!-- 基本配置 -->
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.9</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>servlet-api</artifactId>
            <version>2.5</version>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>jsp-api</artifactId>
            <version>2.0</version>
            <scope>provided</scope>
        </dependency>
        
    </dependencies>
  <build>
        <!-- 配置了很多插件 -->
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.5.1</version>  
                <configuration>
                    <source>1.7</source>
                    <target>1.7</target>
                    <encoding>UTF-8</encoding>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>
    
    
    
</project>

 

3.mybatis全局配置文件:

sqlMapConfig.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>        
    
</configuration>

 

4.編寫代碼:

(1)User.java

package cn.qlq.bean;


import java.io.Serializable;
import java.util.Date;

public class User implements Serializable{
    
    /**
     * 
     */
    private static final long serialVersionUID = 1L;
    private Integer id;    
    private String username;
    private Date birthday;
    private String sex;
    private String address;
    
    
    
    public Integer getId() {
        return id;
    }
    public void setId(Integer id) {
        this.id = id;
    }
    public Date getBirthday() {
        return birthday;
    }
    public void setBirthday(Date birthday) {
        this.birthday = birthday;
    }
    public String getSex() {
        return sex;
    }
    public void setSex(String sex) {
        this.sex = sex;
    }
    public String getUsername() {
        return username;
    }
    public void setUsername(String username) {
        this.username = username;
    }
    public String getAddress() {
        return address;
    }
    public void setAddress(String address) {
        this.address = address;
    }
    
    

}

 

(2)UserMapper.java  (注意接口上的注解是@mapper,代替之前掃描接口的操作)

package cn.qlq.mapper;


import java.util.List;

import org.apache.ibatis.annotations.Mapper;

import cn.qlq.bean.User;

@Mapper
public interface UserMapper {
    
    public List<User> findAll();

}

 

UserMapper.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.qlq.mapper.UserMapper">
    <select id="findAll" resultType="user">
        select * from user
    </select>
</mapper>

 

(3)

UserService.java

package cn.qlq.service;


import java.util.List;

import cn.qlq.bean.User;


public interface UserService {
    
    /**
     * 根據接口查詢所用的用戶
     */
    public List<User> findAllUser();
}

 

UserServiceImpl.java

package cn.qlq.service.impl;


import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import cn.qlq.bean.User;
import cn.qlq.mapper.UserMapper;
import cn.qlq.service.UserService;

@Service
public class UserServiceImpl implements UserService {
    
    @Autowired
    private UserMapper userMapper;
    
    
    public List<User> findAllUser() {
        List<User> list = userMapper.findAll();
        return list;
    }


}

 

(4)UserController.java

package cn.qlq.action;


import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import cn.qlq.bean.User;
import cn.qlq.service.UserService;


@RestController/**自動返回的是json格式數據***/
public class UserController {
    
    @Autowired
    private UserService userService;

    @RequestMapping("list")
    public List<User> list(){
        List<User> list = userService.findAllUser();
        return list;
    }
}

注意:@RestController  注解  (自動返回的是json格式數據)

 

(5)測試類

MySpringBootApplication.java

package cn.qlq;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cache.annotation.EnableCaching;
@SpringBootApplication
public class MySpringBootApplication {
    
    public static void main(String[] args) {        
        //入口運行類
        SpringApplication.run(MySpringBootApplication.class, args);
        
    }

}

4.啟動測試

git源碼地址:  https://github.com/qiao-zhi/springboot-ssm 

 

---------------方法二:使用mybatis-spring整合的方式,也就是我們傳統的方式--------------

這里我們推薦使用第二種,因為這樣我們可以很方便的控制Mybatis的各種配置。

首先,創建一個Mybatis的配置類:

代碼:

package cn.qlq.config;

import javax.sql.DataSource;

import org.mybatis.spring.SqlSessionFactoryBean;
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 {

        @Bean
        @ConditionalOnMissingBean //當容器里沒有指定的Bean的情況下創建該對象
        public SqlSessionFactoryBean sqlSessionFactory(DataSource dataSource) {
            SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
            // 設置數據源
            sqlSessionFactoryBean.setDataSource(dataSource);
            // 設置mybatis的主配置文件
            ResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
            Resource mybatisConfigXml = resolver.getResource("classpath:mybatis/SqlMapConfig.xml");
            sqlSessionFactoryBean.setConfigLocation(mybatisConfigXml);
            // 設置別名包
            sqlSessionFactoryBean.setTypeAliasesPackage("cn.qlq.bean");
            return sqlSessionFactoryBean;
        }
    }

 

然后,創建Mapper接口的掃描類MapperScannerConfig:

package cn.qlq.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;

@Configuration
@AutoConfigureAfter(MyBatisConfig.class) //保證在MyBatisConfig實例化之后再實例化該類
public class MapperScannerConfig {
    
    // mapper接口的掃描器
    @Bean
    public MapperScannerConfigurer mapperScannerConfigurer() {
        MapperScannerConfigurer mapperScannerConfigurer = new MapperScannerConfigurer();
        mapperScannerConfigurer.setBasePackage("cn.qlq.mapper");
        return mapperScannerConfigurer;
    }
}

 

創建一個spring配置類,掃描的包,與讀取的資源文件,創建數據源:

package cn.qlq.config;

import javax.sql.DataSource;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;

import com.jolbox.bonecp.BoneCPDataSource;

@Configuration // 通過該注解來表明該類是一個Spring的配置,相當於一個xml文件
@ComponentScan(basePackages = "cn.qlq") // 配置掃描包
@PropertySource(value = { "classpath:db.properties"}, ignoreResourceNotFound = true)
public class SpringConfig {

    @Value("${jdbc.url}")
    private String jdbcUrl;

    @Value("${jdbc.driverClassName}")
    private String jdbcDriverClassName;

    @Value("${jdbc.username}")
    private String jdbcUsername;

    @Value("${jdbc.password}")
    private String jdbcPassword;

    @Bean(destroyMethod = "close")
    public DataSource dataSource() {
        BoneCPDataSource boneCPDataSource = new BoneCPDataSource();
        // 數據庫驅動
        boneCPDataSource.setDriverClass(jdbcDriverClassName);
        // 相應驅動的jdbcUrl
        boneCPDataSource.setJdbcUrl(jdbcUrl);
        // 數據庫的用戶名
        boneCPDataSource.setUsername(jdbcUsername);
        // 數據庫的密碼
        boneCPDataSource.setPassword(jdbcPassword);
        // 檢查數據庫連接池中空閑連接的間隔時間,單位是分,默認值:240,如果要取消則設置為0
        boneCPDataSource.setIdleConnectionTestPeriodInMinutes(60);
        // 連接池中未使用的鏈接最大存活時間,單位是分,默認值:60,如果要永遠存活設置為0
        boneCPDataSource.setIdleMaxAgeInMinutes(30);
        // 每個分區最大的連接數
        boneCPDataSource.setMaxConnectionsPerPartition(100);
        // 每個分區最小的連接數
        boneCPDataSource.setMinConnectionsPerPartition(5);
        return boneCPDataSource;
    }

}

 

application.properties:

server.port=80

logging.level.org.springframework=DEBUG
#springboot   mybatis
#jiazai mybatis peizhiwenjian
#mybatis.mapper-locations = classpath:mapper/*Mapper.xml
#mybatis.config-location = classpath:mapper/config/sqlMapConfig.xml
#mybatis.type-aliases-package = cn.qlq.bean

#shujuyuan
spring.datasource.driver-class-name= com.mysql.jdbc.Driver
spring.datasource.url = jdbc:mysql://localhost:3306/test1?useUnicode=true&characterEncoding=utf-8
spring.datasource.username = root
spring.datasource.password = 123456

 

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>
    <groupId>cn.qlq</groupId>
    <artifactId>springboot-ssm</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>war</packaging>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.5.2.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-test</artifactId>
            <scope>test</scope>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-devtools</artifactId>
        </dependency>
        <!-- spring-boot整合mybatis -->
        <!-- <dependency> <groupId>org.mybatis.spring.boot</groupId> <artifactId>mybatis-spring-boot-starter</artifactId> 
            <version>1.1.1</version> </dependency> -->
        <!-- mysql驅動 -->

        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.6</version>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-tx</artifactId>
            <version>4.3.7.RELEASE</version>
        </dependency>





        <!-- 基本配置 -->
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.9</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>servlet-api</artifactId>
            <version>2.5</version>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>jsp-api</artifactId>
            <version>2.0</version>
            <scope>provided</scope>
        </dependency>

        <!-- Mybatis -->
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.2.7</version>
        </dependency>
        <!-- Mybatis整合Spring -->
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis-spring</artifactId>
            <version>1.2.2</version>
        </dependency>
        <!-- 連接池 -->
        <dependency>
            <groupId>com.jolbox</groupId>
            <artifactId>bonecp-spring</artifactId>
            <version>0.8.0.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-jdbc</artifactId>
        </dependency>
    </dependencies>
    <build>
        <!-- 配置了很多插件 -->
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.5.1</version>
                <configuration>
                    <source>1.7</source>
                    <target>1.7</target>
                    <encoding>UTF-8</encoding>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>



</project>

 

2.啟動測試:

  總結:我在使用過程中一開始是采用方式二搭建的環境,並且也是基於方式二整合的Mybatis的Pagehelper。但是在打成jar包運行的時候一直報一個錯誤,在MybatisConfig報錯,所以最后我選擇采用第一種方式搭建環境。現在上面的git地址也是基於第一種方式整合,但是提交記錄有基於第二種的。git上面的項目也正在完善。目前已經整合; SpringTask、freemarker、thymeleaf等。。。。

 補充:springboot項目熱部署

1.第一種是基於springloaded

            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
                <!-- spring熱部署 -->
                <dependencies>
                    <dependency>
                        <groupId>org.springframework</groupId>
                        <artifactId>springloaded</artifactId>
                        <version>1.2.6.RELEASE</version>
                    </dependency>
                </dependencies>
            </plugin>

  這種方式不需要引入spring-boot-devtools相關依賴。

  對dubug模式啟動的 SpringBootApplication 有效,run模式啟動的無效。對以maven方式運行的:spring-boot:run 也是有效的。 

 

2.第二種是基於devtools

pom加入如下配置:

        <!--熱加載 -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-devtools</artifactId>
        </dependency>

application.properties里面增加如下配置:

#\u70ED\u52A0\u8F7D
spring.devtools.livereload.enabled=true
#\u70ED\u90E8\u7F72
spring.devtools.restart.enabled=false

  對dubug模式啟動的 SpringBootApplication 有效,  run模式啟動的無效,對以maven方式運行的:spring-boot:run 也是無效的。 

 

  這兩種方式親測有效。

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM