1. 程式人生 > >eclipse 使用maven 構建 springboot+mybatis

eclipse 使用maven 構建 springboot+mybatis

1、專案結構


2、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>com.zzg</groupId>
	<artifactId>springbootone</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<packaging>jar</packaging>

	<name>springbootone</name>
	<url>http://maven.apache.org</url>

	<properties>
		<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
	</properties>

	<parent>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-parent</artifactId>
		<version>1.4.3.RELEASE</version>
	</parent>

	<dependencies>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-web</artifactId>
		</dependency>
		<dependency>
			<groupId>junit</groupId>
			<artifactId>junit</artifactId>
			<version>3.8.1</version>
			<scope>test</scope>
		</dependency>
		<!--引入swagger  -->
		<dependency>
           <groupId>io.springfox</groupId>
           <artifactId>springfox-swagger2</artifactId>
           <version>2.2.2</version>
        </dependency>
        <dependency>
           <groupId>io.springfox</groupId>
           <artifactId>springfox-swagger-ui</artifactId>
           <version>2.2.2</version>
        </dependency>
        <!--整合mybatis  -->
        <!-- 與資料庫操作相關的依賴 -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-jdbc</artifactId>
        </dependency>

        <!-- 使用資料來源 -->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid</artifactId>
            <version>1.0.14</version>
        </dependency>
        
        <!-- mysql -->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <scope>runtime</scope>
        </dependency>
        
        <!-- mybatis -->
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.2.8</version>
        </dependency>
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis-spring</artifactId>
            <version>1.2.2</version>
         </dependency>
	</dependencies>
</project>

說明:

  • spring-boot-starter-jdbc:引入與資料庫操作相關的依賴,例如daoSupport等

  • druid:阿里巴巴的資料來源
  • mysql-connector-java:mysql連線jar,scope為runtime
  • mybatis + mybatis-spring:mybatis相關jar

3、application.properties
jdbc.driverClassName = com.mysql.jdbc.Driver
jdbc.url = jdbc:mysql://127.0.0.1:3306/cms_website?zeroDateTimeBehavior=convertToNull&useUnicode=true&characterEncoding=utf-8
jdbc.username = root
jdbc.password = 123456

mybatis.typeAliasesPackage=com.zzg.springbootone.domain  
mybatis.mapperLocations=classpath:mapper/*.xml
 說明:
  • mybatis.typeAliasesPackage:指定domain類的基包,即指定其在*Mapper.xml檔案中可以使用簡名來代替全類名(看後邊的UserMapper.xml介紹)
  • mybatis.mapperLocations:指定*Mapper.xml的位置

4、com.zzg.springbootone.common.MybatisConfig

作用:mybatis與springboot整合的入口

package com.zzg.springbootone.common;

import java.util.Properties;

import javax.sql.DataSource;

import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;

import com.alibaba.druid.pool.DruidDataSourceFactory;

/**
 * springboot整合mybatis的基本入口
 * 1)建立資料來源
 * 2)建立SqlSessionFactory
 */
@Configuration    //該註解類似於spring配置檔案
@MapperScan(basePackages="com.zzg.springbootone.mapper")
public class MyBatisConfig {
    
    @Autowired
    private Environment env;
    
    /**
     * 建立資料來源
     * @Primary 該註解表示在同一個介面有多個實現類可以注入的時候,預設選擇哪一個,而不是讓@autowire註解報錯 
     */
    @Bean
    //@Primary
    public DataSource getDataSource() throws Exception{
        Properties props = new Properties();
        props.put("driverClassName", env.getProperty("jdbc.driverClassName"));
        props.put("url", env.getProperty("jdbc.url"));
        props.put("username", env.getProperty("jdbc.username"));
        props.put("password", env.getProperty("jdbc.password"));
        return DruidDataSourceFactory.createDataSource(props);
    }

    /**
     * 根據資料來源建立SqlSessionFactory
     */
    @Bean
    public SqlSessionFactory sqlSessionFactory(DataSource ds) throws Exception{
        SqlSessionFactoryBean fb = new SqlSessionFactoryBean();
        fb.setDataSource(ds);//指定資料來源(這個必須有,否則報錯)
        //下邊兩句僅僅用於*.xml檔案,如果整個持久層操作不需要使用到xml檔案的話(只用註解就可以搞定),則不加
        fb.setTypeAliasesPackage(env.getProperty("mybatis.typeAliasesPackage"));//指定基包
        fb.setMapperLocations(new PathMatchingResourcePatternResolver().getResources(env.getProperty("mybatis.mapperLocations")));//指定xml檔案位置
        
        return fb.getObject();
    }

}

說明:

  • 類上邊新增兩個
    • @Configuration註解(該註解類似於spring的配置檔案
    • @MapperScan註解,指定掃描的mapper介面所在的包
  • 在該類中,注入了Environment例項,使用該例項可以去讀取類路徑下application.properties檔案中的內容,讀取檔案內容的三種方式,見第二章 第二個spring-boot程式
  • 在該類中,使用druid資料來源定義了資料來源Bean,spring-boot預設使用的是tomcat-jdbc資料來源,這是springboot官方推薦的資料來源(效能和併發性都很好)
  • 根據資料來源生成SqlSessionFactory
    • 值得注意的是,資料來源是必須指定的,否則springboot啟動不了
    • typeAliasesPackage和mapperLocations不是必須的,如果整個專案不需要用到*Mapper.xml來寫SQL的話(即只用註解就可以搞定),那麼不需要配
  • @Primary註解:指定在同一個介面有多個實現類可以注入的時候,預設選擇哪一個,而不是讓@Autowire註解報錯(一般用於多資料來源的情況下)

這樣之後,在專案中再使用springboot就和在ssm中(配置完成後)使用一樣了。


5、com.zzg.springboot.mapper.UserMapper

package com.zzg.springbootone.mapper;

import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Param;

import com.zzg.springbootone.domain.User;

public interface UserMapper {
	@Insert("INSERT INTO tb_user(login_name, password) VALUES(#{loginName},#{password})")
    public int insertUser(@Param("loginName") String loginName, @Param("password")  String password);
	
	 /**
     * 插入使用者,並將主鍵設定到user中
     * 注意:返回的是資料庫影響條數,即1
     */
    public int insertUserWithBackId(User user);
}

說明:該介面中有兩個方法,

  • 一個普通插入:直接用註解搞定
  • 一個插入返回主鍵:需要使用xml來搞定
6、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">

<!-- 指定工作空間,要與介面名相同,原始碼沒有去看,猜測應該是通過"這裡的namespace.下邊方法的id"來定位方法的 -->
<mapper namespace="com.zzg.springbootone.mapper.UserMapper">
    
    <!-- 若不需要自動返回主鍵,將useGeneratedKeys="true" keyProperty="id"去掉即可(當然如果不需要自動返回主鍵,直接用註解即可) -->
    <insert id="insertUserWithBackId" parameterType="User" useGeneratedKeys="true" keyProperty="id" >
       <![CDATA[
       INSERT INTO tb_user 
       (
           login_name,
           password
       )
       VALUES
       (
           #{loginName, jdbcType=VARCHAR},
           #{password, jdbcType=VARCHAR}
       )
       ]]>
   </insert>
    
</mapper>
7、com.zzg.springboot.dao.UserDao

package com.zzg.springbootone.dao;

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

import com.zzg.springbootone.domain.User;
import com.zzg.springbootone.mapper.UserMapper;

@Repository
public class UserDao {
	 	@Autowired
	    private UserMapper userMapper;
	    
	    public int insertUser(String username, String password){
	        return userMapper.insertUser(username, password);
	    }
	    
	    public int insertUserWithBackId(User user){    
	        return userMapper.insertUserWithBackId(user);
	    }

}


8、com.zzg.springboot.service.UserService
package com.zzg.springbootone.service;

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

import com.zzg.springbootone.dao.UserDao;
import com.zzg.springbootone.domain.User;

@Service
public class UserService {
	@Autowired
    private UserDao userDao;
    
    public boolean addUser(String username, String password){
        return userDao.insertUser(username, password)==1?true:false;
    }
    
    public User addUserWithBackId(String loginname, String password){
        User user = new User();
        user.setLoginName(loginname);
        user.setPassword(password);
        userDao.insertUserWithBackId(user);//該方法後,主鍵已經設定到user中了
        return user;
    }
}

9、com.zzg.springboot.controller.UserController
package com.zzg.springbootone.controller;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiResponse;
import io.swagger.annotations.ApiResponses;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestHeader;
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.bind.annotation.RestController;

import com.zzg.springbootone.domain.User;
import com.zzg.springbootone.service.UserService;

@RestController
@RequestMapping("/user")
@Api("userController相關api")
public class UserController {
	 	@Autowired
	    private UserService userService;
	    
	    @ApiOperation("新增使用者")
	    @ApiImplicitParams({
	        @ApiImplicitParam(paramType="query",name="loginname",dataType="String",required=true,value="使用者的姓名",defaultValue="zhouzhigang"),
	        @ApiImplicitParam(paramType="query",name="password",dataType="String",required=true,value="使用者的密碼",defaultValue="123456")
	    })
	    @ApiResponses({
	        @ApiResponse(code=400,message="請求引數沒填好"),
	        @ApiResponse(code=404,message="請求路徑沒有或頁面跳轉路徑不對")
	    })
	    @RequestMapping(value="/addUser",method=RequestMethod.GET)
	    public boolean addUser(@RequestParam("loginname") String loginname, 
	                           @RequestParam("password") String password) {
	        return userService.addUser(loginname,password);
	    }
	    
	    @ApiOperation("新增使用者且返回已經設定了主鍵的user例項")
	    @ApiImplicitParams({
	        @ApiImplicitParam(paramType="query",name="loginname",dataType="String",required=true,value="使用者的姓名",defaultValue="zhouzhigang"),
	        @ApiImplicitParam(paramType="query",name="password",dataType="String",required=true,value="使用者的密碼",defaultValue="123456")
	    })
	    @ApiResponses({
	        @ApiResponse(code=400,message="請求引數沒填好"),
	        @ApiResponse(code=404,message="請求路徑沒有或頁面跳轉路徑不對")
	    })
	    @RequestMapping(value="/addUserWithBackId",method=RequestMethod.GET)
	    public User addUserWithBackId(@RequestParam("loginname") String loginname, 
	                                     @RequestParam("password") String password) {
	        return userService.addUserWithBackId(loginname, password);
	    }

}
測試結果: