spring-mybatis-data-common程序級分表操作實例


spring-mybatis-data-common-2.0新增分表機制,在1.0基礎上做了部分調整.

基於機架展示分庫應用
數據庫分表實力創建

create table tb_example_1( id bigint primary key auto_increment , eId bigint, exampleName varchar(40), exampleTitle varchar(200), exampleDate datetime )ENGINE=MyISAM  DEFAULT CHARSET=utf8 AUTO_INCREMENT=1 ; create table tb_example_2 like tb_example_1; create table tb_example_3 like tb_example_1; create table tb_example( id bigint primary key auto_increment , eId bigint, exampleName varchar(40), exampleTitle varchar(200), exampleDate datetime )ENGINE=MERGE UNION=(tb_example_1,tb_example_2,tb_example_3) INSERT_METHOD=LAST AUTO_INCREMENT=1 ; 

程序構建分表操作
1.spring-mybatis-common-data中提供了com.spring.mybatis.data.common.model.ExampleModel用於Demo的實體類
添加maven依賴

<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/maven-v4_0_0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>com.spring.mybatis</groupId>
    <artifactId>com-spring-mybatis-common-data-demo</artifactId>
    <packaging>war</packaging>
    <version>0.0.1-SNAPSHOT</version>
    <name>com-spring-mybatis-common-data-demo Maven Webapp</name>
    <url>http://maven.apache.org</url>
    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <spring.mybatis.data.version>2.0</spring.mybatis.data.version>
        <junit.version>4.11</junit.version>
    </properties>
    <dependencies>
        <!-- spring-mybatis-data-common begin -->
        <dependency>
            <groupId>com.spring.mybatis</groupId>
            <artifactId>spring-mybatis-data-common</artifactId>
            <version>${spring.mybatis.data.version}</version>
        </dependency>
        <!-- spring-mybatis-data-common end -->
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>${junit.version}</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid</artifactId>
            <version>0.2.26</version>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.1</version>
        </dependency>
        <dependency>
            <groupId>org.codehaus.jackson</groupId>
            <artifactId>jackson-mapper-asl</artifactId>
            <version>1.9.13</version>
        </dependency>
    </dependencies>
    <build>
        <finalName>com-spring-mybatis-common-data-demo</finalName>
    </build>
</project>

2.持久層繼承分表Dao接口,也可以自己定義

@Repository public interface ExampleModelDao extends ShardCudDao<ExampleModel>,ShardReadDao<ExampleModel>{ /**get common base table max auto_increment id*/
    public Long selectMaxId() throws DaoException; }

在持久層自定義了一個selectMaxId()用於多個分表共享同一個自增策略,這里采用程序級別控制
3.業務層繼承分表,業務層操作可以自定義,也可以繼承com.spring.mybatis.data.common.service.BaseService中提供的常規業務

@Service public class ExampleModelService extends BaseShard{ @Autowired private ExampleModelDao exampleModelDao; @Override public String getBaseShardTableName() { return "tb_example_"; } @Override public int getShardTableCount() { return 3; } public int deleteObject(ExampleModel entity) throws ServiceException { try { return this.exampleModelDao.delete(getShardTableName(entity.geteId()+"", 1), entity.getId()); } catch (DaoException e) { e.printStackTrace(); } return 0; } public int save(ExampleModel entity) throws ServiceException { long mxId = 1; try { Long maxId = this.exampleModelDao.selectMaxId(); if(null != maxId && maxId >= 1){ mxId = maxId + 1; } } catch (DaoException e) { LogUtils.dao.error("insert exampleModel before get Max Id error.",e); e.printStackTrace(); } try { entity.setId(mxId); return this.exampleModelDao.insert(getShardTableName(entity.geteId()+"", 1), entity); } catch (DaoException e) { LogUtils.dao.error("insert exampleModel to table " + getShardTableName(entity.geteId()+"", 1) + " error"); e.printStackTrace(); } return 0; } public ExampleModel selectObject(ExampleModel entity) throws ServiceException { try { return this.exampleModelDao.selectById(getShardTableName(entity.geteId()+"", 1), entity.geteId()); } catch (DaoException e) { e.printStackTrace(); } return null; } public void setExampleModelDao(ExampleModelDao exampleModelDao) { this.exampleModelDao = exampleModelDao; } }

BaseShard是一個抽象類,繼承它需要實現兩個方法.

    /** * get shard table count * @return
     */
    public abstract int getShardTableCount(); /** * get base shard name * @return
     */
    public abstract String getBaseShardTableName();

getShardTableCount()用於返回分表數量, public abstract String getBaseShardTableName()用於返回分表表名統一前綴.
如實例中的分表為tb_example、tb_example_1、tb_example_2、tb_example_3,分表表名前綴為"tb_example_",分表數量為3.
BaseShard中獲取映射表名的操作

    /** * get shard table name <br> * * shard table index start with 0 * * just like follows * * tb_example_0 * tb_example_1 * tb_example_2 * tb_example_3 * * @param tableName * @return
     */
    public String getShardTableName(String shardKey); /** * get shard table name <br> * * shard table index start with (0+baseNumber) * * just like follows * * tb_example_(0+baseNumber) * tb_example_(1+baseNumber) * tb_example_(2+baseNumber) * tb_example_(3+baseNumber) * * * @param shardKey * @param baseNumber * @return
     */
    public String getShardTableName(String shardKey,int baseNumber);

4.持久層實現

<?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.spring.mybatis.common.data.demo.dao">
    
  <!--insert entity-->  
  <insert id="insert" parameterType="exampleModel" flushCache="true">
      INSERT INTO ${tablename}(
            id,
            eId,
            exampleName,
            exampleTitle,
            exampleDate)
    VALUES(
        #{object.id},
        #{object.eId},
        #{object.exampleName},
        #{object.exampleTitle},
        #{object.exampleDate}
    )
  </insert>
  
  <select id="selectMaxId" resultType="long">
          select max(id) from tb_example
  </select>
  
  <delete id="delete" parameterType="long" flushCache="true">
      DELETE FROM
          ${tablename}
      WHERE
          id=#{id}
  </delete>
  
  <select id="selectById" parameterType="long" resultType="exampleModel">
      SELECT 
          id AS id,eId AS eId,exampleName AS exampleName,exampleTitle AS exampleTitle,exampleDate AS exampleDate
      FROM 
          ${tablename}
      WHERE
          id=#{id}
  </select>
  
</mapper>

 

程序運行結果

查詢各個分表

實例下載: http://files.cnblogs.com/dennisit/spring-mybatis-data-common-2.0-and-demo.7z


轉載請注明地址:[http://www.cnblogs.com/dennisit/p/3793501.html]


免責聲明!

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



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