第三章: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集成,并对外提供了接口支持。

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值