1. 程式人生 > >第三章:Spring Cloud服務提供者整合Mybatis

第三章:Spring Cloud服務提供者整合Mybatis

接第二章

服務提供者簡單使用spring boot整合mybatis來實現

1、不太相似的pom.xml:

<?xml version="1.0"?>
<project xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd" xmlns="http://maven.apache.org/POM/4.0.0"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
  <modelVersion>4.0.0</modelVersion
>
<groupId>cloud-demo-service</groupId> <artifactId>cloud-demo-service</artifactId> <name>cloud-demo-service</name> <url>http://maven.apache.org</url> <parent> <groupId>org.springframework.boot</groupId> <artifactId
>
spring-boot-starter-parent</artifactId> <version>1.3.5.RELEASE</version> <relativePath /> </parent> <dependencyManagement> <dependencies> <dependency> <groupId>org.springframework.cloud</groupId
>
<artifactId>spring-cloud-starter-parent</artifactId> <version>Brixton.RELEASE</version> <type>pom</type> <scope>import</scope> </dependency> </dependencies> </dependencyManagement> <dependencies> <!-- springboot web啟動器 --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <!-- SpringCloud配置啟動器 --> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-config</artifactId> </dependency> <!-- SpringCloud實現的eureka服務註冊於釋出器 --> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-eureka-server</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-actuator</artifactId> </dependency> <!-- 與資料庫操作相關的依賴 --> <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> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-tx</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> </dependencies> <repositories> <repository> <snapshots> <enabled>true</enabled> </snapshots> <id>public</id> <name>Public Repositories</name> <url>http://maven.aliyun.com/nexus/content/groups/public/</url> </repository> </repositories> <pluginRepositories> <pluginRepository> <id>public</id> <name>Public Repositories</name> <url>http://maven.aliyun.com/nexus/content/groups/public/</url> </pluginRepository> </pluginRepositories> <build> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> </plugins> <defaultGoal>compile</defaultGoal> </build> </project>

2、啟動類,需要注意的是整合mybatis是必須要使用@EnableAutoConfiguration這個註解,spring會自動實現相關的ORM對映,程式碼如下:

package org.cloud.demo.service;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.netflix.eureka.EnableEurekaClient;

@EnableAutoConfiguration
@SpringBootApplication
//@EnableEurekaServer //此服務即是eureka註冊中心又是服務的提供者
@EnableEurekaClient
public class ServiceApplication{
    public static void main( String[] args ){
        SpringApplication.run(ServiceApplication.class, args);
    }
}

3、配置檔案,包含mybatis資料連線池的相關配置及eureka服務中心的配置:

server:
  port: 8081

spring: 
  application: 
    name: cloudservice
  cloud:
    config:
      uri: http://${config.server.ip}:${config.server.port}
      name: cloudservice
      profile: ${app.profile:test}

#service discovery url
eureka: 
  client:
    serviceUrl: 
      defaultZone: http://localhost:8761/eureka/

#datasource config
jdbc:
  driverClassName: com.mysql.jdbc.Driver
  url: jdbc:mysql://192.168.99.100:3306/blog?zeroDateTimeBehavior=convertToNull&amp;useUnicode=true&amp;characterEncoding=utf-8
  username: root
  password: 123456

#mybatis config
mybatis:
  typeAliasesPackage: org.cloud.demo.service.model
  mapperLocations: classpath:mapper/*.xml

4、spring與mybatis的連線配置類,這裡使用阿里的druid資料池:

package org.cloud.demo.service.conf;

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;

/** 
* @ClassName: MyBatisConfig 
* @Description: Spring Boot整合Mybatis的基本入口
* @author S1ow 
* @date 2017年5月23日 上午9:59:56 
*  
*/
@Configuration
@MapperScan(basePackages="org.cloud.demo.service.dao")
public class MyBatisConfig {

    @Autowired
    private Environment env;

    /**  
    * @Title: getDataSource  
    * @Description: 建立資料來源 
    * @param @return 
    * @return DataSource
    * @throws  
    */  
    @Bean
    public DataSource getDataSource(){
        Properties props = new Properties();
        props.put("driverClass", 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"));
        try {
            return DruidDataSourceFactory.createDataSource(props);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

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

5、Dao層的實現,就是簡單的介面,對映到mapper檔案中的名稱空間

package org.cloud.demo.service.dao;

import java.util.List;

import org.cloud.demo.service.model.User;

public interface UserDao {

    int deleteByPrimaryKey(Integer id);

    int insert(User record);

    int insertSelective(User record);

    User selectByPrimaryKey(Integer id);

    int updateByPrimaryKeySelective(User record);

    int updateByPrimaryKey(User record);

    List<User> getAllUsers();
}

6、mapper配置檔案:

<?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="org.cloud.demo.service.dao.UserDao" >

  <resultMap id="BaseResultMap" type="org.cloud.demo.service.model.User" >
    <id column="id" property="id" jdbcType="INTEGER" />
    <result column="name" property="name" jdbcType="VARCHAR" />
    <result column="password" property="password" jdbcType="VARCHAR" />
    <result column="phone" property="phone" jdbcType="BIGINT" />
    <result column="city" property="city" jdbcType="VARCHAR" />
    <result column="ip" property="ip" jdbcType="VARCHAR" />
    <result column="img" property="img" jdbcType="VARCHAR" />
    <result column="wechat" property="wechat" jdbcType="VARCHAR" />
    <result column="sina" property="sina" jdbcType="VARCHAR" />
  </resultMap>

  <sql id="Base_Column_List" >
    id, name, password, phone, city, ip, img, wechat, sina
  </sql>

  <select id="selectByPrimaryKey" resultMap="BaseResultMap" parameterType="java.lang.Integer" >
    select 
    <include refid="Base_Column_List" />
    from b_user
    where id = #{id,jdbcType=INTEGER}
  </select>

  <select id="getAllUsers" resultMap="BaseResultMap" >
    select 
    <include refid="Base_Column_List" />
    from b_user
  </select>

  <delete id="deleteByPrimaryKey" parameterType="java.lang.Integer" >
    delete from b_user
    where id = #{id,jdbcType=INTEGER}
  </delete>

  <insert id="insert" parameterType="org.cloud.demo.service.model.User" >
    insert into b_user (name, password, 
      phone, city, ip, img, 
      wechat, sina)
    values (#{name,jdbcType=VARCHAR}, #{password,jdbcType=VARCHAR}, 
      #{phone,jdbcType=BIGINT}, #{city,jdbcType=VARCHAR}, #{ip,jdbcType=VARCHAR}, #{img,jdbcType=VARCHAR}, 
      #{wechat,jdbcType=VARCHAR}, #{sina,jdbcType=VARCHAR})
  </insert>

  <insert id="insertSelective" parameterType="org.cloud.demo.service.model.User" >
    insert into b_user
    <trim prefix="(" suffix=")" suffixOverrides="," >
      <if test="name != null" >
        name,
      </if>
      <if test="password != null" >
        password,
      </if>
      <if test="phone != null" >
        phone,
      </if>
      <if test="city != null" >
        city,
      </if>
      <if test="ip != null" >
        ip,
      </if>
      <if test="img != null" >
        img,
      </if>
      <if test="wechat != null" >
        wechat,
      </if>
      <if test="sina != null" >
        sina,
      </if>
    </trim>
    <trim prefix="values (" suffix=")" suffixOverrides="," >
      <if test="name != null" >
        #{name,jdbcType=VARCHAR},
      </if>
      <if test="password != null" >
        #{password,jdbcType=VARCHAR},
      </if>
      <if test="phone != null" >
        #{phone,jdbcType=BIGINT},
      </if>
      <if test="city != null" >
        #{city,jdbcType=VARCHAR},
      </if>
      <if test="ip != null" >
        #{ip,jdbcType=VARCHAR},
      </if>
      <if test="img != null" >
        #{img,jdbcType=VARCHAR},
      </if>
      <if test="wechat != null" >
        #{wechat,jdbcType=VARCHAR},
      </if>
      <if test="sina != null" >
        #{sina,jdbcType=VARCHAR},
      </if>
    </trim>
  </insert>

  <update id="updateByPrimaryKeySelective" parameterType="org.cloud.demo.service.model.User" >
    update b_user
    <set >
      <if test="name != null" >
        name = #{name,jdbcType=VARCHAR},
      </if>
      <if test="password != null" >
        password = #{password,jdbcType=VARCHAR},
      </if>
      <if test="phone != null" >
        phone = #{phone,jdbcType=BIGINT},
      </if>
      <if test="city != null" >
        city = #{city,jdbcType=VARCHAR},
      </if>
      <if test="ip != null" >
        ip = #{ip,jdbcType=VARCHAR},
      </if>
      <if test="img != null" >
        img = #{img,jdbcType=VARCHAR},
      </if>
      <if test="wechat != null" >
        wechat = #{wechat,jdbcType=VARCHAR},
      </if>
      <if test="sina != null" >
        sina = #{sina,jdbcType=VARCHAR},
      </if>
    </set>
    where id = #{id,jdbcType=INTEGER}
  </update>

  <update id="updateByPrimaryKey" parameterType="org.cloud.demo.service.model.User" >
    update b_user
    set name = #{name,jdbcType=VARCHAR},
      password = #{password,jdbcType=VARCHAR},
      phone = #{phone,jdbcType=BIGINT},
      city = #{city,jdbcType=VARCHAR},
      ip = #{ip,jdbcType=VARCHAR},
      img = #{img,jdbcType=VARCHAR},
      wechat = #{wechat,jdbcType=VARCHAR},
      sina = #{sina,jdbcType=VARCHAR}
    where id = #{id,jdbcType=INTEGER}
  </update>
</mapper>

7、service層的實現:

package org.cloud.demo.service.bo;

import java.util.List;

import org.cloud.demo.service.dao.UserDao;
import org.cloud.demo.service.model.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class UserService {

    @Autowired
    private UserDao userDao;

    public int addUser(User user){
        return userDao.insert(user);
    }

    public User getUserById(int id){
        return userDao.selectByPrimaryKey(id);
    }

    public List<User> getAllUsers(){
        return userDao.getAllUsers();
    }
}

8、對外暴露rest介面,即restController:

package org.cloud.demo.service.controller;

import java.util.List;

import javax.annotation.Resource;

import org.cloud.demo.service.bo.UserService;
import org.cloud.demo.service.model.User;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/user")
public class UserController {

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

    @Autowired
    private UserService userService;

    @Resource
    private DiscoveryClient client;

    @RequestMapping(value="/addUser",method=RequestMethod.POST)
    @ResponseBody
    public int addUser(@RequestBody User user){
        return userService.addUser(user);
    }

    @RequestMapping(value="/getUserById",method=RequestMethod.GET)
    @ResponseBody
    public User getUserById(){
        return userService.getUserById(1);
    }

    @RequestMapping(value="/getAllUsers",method=RequestMethod.GET)
    @ResponseBody
    public List<User> getAllUsers(){
        List<User> listUser = userService.getAllUsers();
        //獲取服務資訊
        ServiceInstance instance = client.getLocalServiceInstance();
        //輸出服務資訊
        logger.info("uri={},serviceId={},result={}", instance.getUri(), instance.getServiceId(),listUser);
        return listUser;
    }
}

以上就完成了簡單的mybatis整合,並對外提供了介面支援。