SpringBoot項目配置Mybatis數據源(註解方式)

採用阿里的Druid作線程池;html

  • 首先在項目的build.gradle或pom文件中增長mysql或oracle的依賴
//druid鏈接池
compile ("com.alibaba:druid-spring-boot-starter:1.1.10")
//oracle
compile ("com.oracle:ojdbc14:10.2.0.3.0")
//mysql
compile ("mysql:mysql-connector-java:8.0.12")
//Mybatis 依賴
compile ("org.mybatis.spring.boot:mybatis-spring-boot-starter:1.3.1")
複製代碼
  • 在項目中的啓動配置文件中增長數據庫鏈接信息,這裏以yml爲例,properties同理;
spring:
  datasource:
    druid:
      name: project
      url: jdbc:mysql://10.211.55.3:3306/project
      username: oracle
      password: 123456
      type: com.alibaba.druid.pool.DruidDataSource
      driver-calss: com.mysql.jdbc.Driver
      #屬性類型是字符串,經過別名的方式配置擴展插件經常使用的插件有:監控統計用的filter:stat 日誌用的filter:log4j 防護sql注入的filter:wall
      filters: stat
      #初始化時創建物理鏈接的個數。初始化發生在顯示調用init方法,或者第一次getConnection時
      initialSize: 5
      #最小鏈接池數量
      minIdle: 5
      #最大鏈接池數量
      maxActive: 10
      #有兩個含義:1) Destroy線程會檢測鏈接的間隔時間 2) testWhileIdle的判斷依據,詳細看testWhileIdle屬性的說明
      timeBetweenEvictionRunsMillis: 20000
      #配置一個鏈接在池中最小生存的時間,單位是毫秒
      minEvictableIdleTimeMillis: 300000
      #用來檢測鏈接是否有效的sql,要求是一個查詢語句 若是validationQuery爲null,testOnBorrow、testOnReturn、testWhileIdle都不會其做用。
      validationQuery: SELECT '1' FROM DUAL
      #建議配置爲true,不影響性能,而且保證安全性。申請鏈接的時候檢測,若是空閒時間大於timeBetweenEvictionRunsMillis 執行validationQuery檢測鏈接是否有效
      testWhileIdle: true
      #申請鏈接時執行validationQuery檢測鏈接是否有效,作了這個配置會下降性能。
      testOnBorrow: false
      #歸還鏈接時執行validationQuery檢測鏈接是否有效,作了這個配置會下降性能
      testOnReturn: false
      #要啓用PSCache,必須配置大於0,當大於0時,poolPreparedStatements自動觸發修改成true。 在Druid中,不會存在Oracle下PSCache佔用內存過多的問題 能夠把這個數值配置大一些,好比說100
      maxOpenPreparedStatements: 100
      #關閉 abanded 鏈接時輸出錯誤日誌
      logAbandoned: true複製代碼
  • 啓動類中增長事物的開啓
@EnableTransactionManagement////啓用事務管理複製代碼
  • 設置數據源配置
package com.project.core.config;

import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.spring.boot.autoconfigure.DruidDataSourceBuilder;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.SqlSessionTemplate;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;

import javax.sql.DataSource;

/**
 * @author lantao 
 * @Title: DataSourseConfiguration
 * @ProjectName project
 * @date 2018/9/13 17:46
 * @Description: druid 數據庫鏈接池 配置類
 */
@Configuration
//設置掃描 DAO層
@MapperScan(basePackages = {DataSourseConfiguration.MAPPER_PACKAGE})
public class DataSourseConfiguration {

    public static final String MAPPER_PACKAGE = "com.project.core.mapper";

    public static final String MAPPER_XML_PACKAGE = "classpath:mapper/*.xml";

    public static final String MYBATIS_BEAN_PACKAGE = "com.project.core.bean";

    @Primary
    @ConfigurationProperties(prefix = "spring.datasource.druid")
    @Bean(name = "dataSource")
    public DataSource dataSourceConfig() {
        DruidDataSource dataSource = DruidDataSourceBuilder.create().build();
        return dataSource;
    }

    @Bean(name = "sqlSessionFactory")
    public SqlSessionFactory sqlSessionFactory() throws Exception {
        SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
        sqlSessionFactoryBean.setDataSource(dataSourceConfig());

        //設置掃描 mybatis-config.xml
        sqlSessionFactoryBean.setConfigLocation(null);

        //設置掃描mapper.xml
        PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
        Resource[] resources = resolver.getResources(MAPPER_XML_PACKAGE);
        sqlSessionFactoryBean.setMapperLocations(resources);

        //設置掃描實體類
        sqlSessionFactoryBean.setTypeAliasesPackage(MYBATIS_BEAN_PACKAGE);

        return sqlSessionFactoryBean.getObject();
    }


    @Primary
    @Bean(name = "sqlSessionTemplate")
    public SqlSessionTemplate popSqlSessionTemplate(@Qualifier("sqlSessionFactory") SqlSessionFactory sqlSessionFactory) {
        return new SqlSessionTemplate(sqlSessionFactory);
    }

    @Primary
    @Bean(name = "transactionManager")
    public DataSourceTransactionManager transactionManager() {
        return new DataSourceTransactionManager(dataSourceConfig());
    }
}
複製代碼

測試:java

  • Controller
package com.project.api.controller;

import com.project.core.service.UserService;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * @author lantao 
 * @Title: TestController
 * @ProjectName project
 * @date 2018/9/12 14:30
 * @Description: TODO
 */
@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService;

    @GetMapping("/getUser")
    @ApiOperation(value = "獲取用戶信息", notes = "獲取用戶信息")
    public Object getUesr() {
        return userService.selUserInfoForAll();
    }


    @GetMapping("/getName/{userName}")
    @ApiOperation(value = "獲取用戶名", notes = "獲取用戶名")
    public Object getName(@PathVariable("userName") String userName) {
        return userService.selUserInfo(userName);
    }

    @DeleteMapping("/delUser/{userName}")
    @ApiOperation(value = "刪除用戶信息", notes = "刪除用戶信息")
    public String delUser(@PathVariable("userName") String userName) {
        try {
            userService.deleteUser(userName);
        } catch (Exception e) {
            return "失敗";
        }
        return "成功";
    }
}
複製代碼
  • Service
package com.project.core.service;

import com.project.core.bean.UserBean;

import java.util.List;

/**
 * @author lantao
 * @Title: UserService
 * @ProjectName project
 * @date 2018/9/18 13:53
 * @Description: TODO
 */
public interface UserService {

    List<UserBean> selUserInfoForAll();

    UserBean selUserInfo(String userName);

    void deleteUser(String userName);
}
複製代碼
  • ServiceImpl
package com.project.core.service.impl;

import com.project.core.bean.UserBean;
import com.project.core.mapper.UserMapper;
import com.project.core.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @author lantao
 * @Title: UserServiceImpl
 * @ProjectName project
 * @date 2018/9/18 13:56
 * @Description: TODO
 */
@Service
public class UserServiceImpl implements UserService{

    @Autowired
    private UserMapper userMapper;

    @Override
    public List<UserBean> selUserInfoForAll() {
        return userMapper.selUserInfoForAll();
    }

    @Override
    public UserBean selUserInfo(String userName) {
        return userMapper.selUserInfo(userName);
    }

    @Override
    public void deleteUser(String userName) {
        userMapper.deleteUser(userName);
    }
}
複製代碼
  • Mapper
package com.project.core.mapper;

import com.project.core.bean.UserBean;
import org.apache.ibatis.annotations.Param;
import org.springframework.stereotype.Repository;

import java.util.List;

/**
 * @author lantao
 * @Title: UserMapper
 * @ProjectName project
 * @date 2018/9/18 13:56
 * @Description: TODO
 */
@Repository
public interface UserMapper {

    List<UserBean> selUserInfoForAll();

    void deleteUser(@Param(value = "userName") String userName);

    UserBean selUserInfo(@Param(value = "userName") String userName);
}
複製代碼
  • 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.project.core.mapper.UserMapper">

    <resultMap id="userBean" type="com.project.core.bean.UserBean">
        <result column="NAME" property="name"/>
        <result column="SEX" property="sex"/>
        <result column="AGE" property="age"/>
        <result column="USER_NAME" property="userName"/>
        <result column="PASS_WORD" property="passWd"/>
    </resultMap>

    <select id="selUserInfoForAll"  resultMap="userBean">
        SELECT * FROM USER_INFO
    </select>

    <select id="selUserInfo"  parameterType="java.lang.String" resultMap="userBean">
        SELECT * FROM USER_INFO t WHERE USER_NAME = #{userName}
    </select>

    <delete id="deleteUser" parameterType="java.lang.String">
        DELETE FROM USER_INFO  WHERE USER_NAME = #{userName}
    </delete>
</mapper>
複製代碼

  • 數據庫表

源碼Git: github.com/lantaoGitHu…mysql

有問題請評論,及時回答;git

相關文章
相關標籤/搜索