mybatis调用oracle存储过程例子(生成随机数)

主要是练习下存储过程,实际项目中这么写就太复杂了。

1.存储过程

CREATE OR REPLACE PROCEDURE GETRAND(RAND_TYPE IN VARCHAR,
                                    RAND_CODE OUT VARCHAR) AS
  I          INTEGER := 0;
  PRE0       VARCHAR2(50); --补0字符串
  PRELENGTH  INTEGER; --补0个数
  CODELENGTH INTEGER; --随机数位数
  V_CODE     VARCHAR2(50); --随机数
  V_DIGIT    NUMBER; --需要生成的随机数的位数
BEGIN
  SELECT R.CODE, R.DIGIT
    INTO V_CODE, V_DIGIT
    FROM CM_RAND R
   WHERE R.TYPE = RAND_TYPE;

  V_CODE := V_CODE + 1;
  --当更新的code位数大于随机数的最大位数时,从1开始
  CODELENGTH := LENGTH(V_CODE);
  IF (CODELENGTH > V_DIGIT) THEN
    V_CODE     := 1;
    CODELENGTH := 1;
  END IF;

  --生成的随机数位数不足时,补0
  IF (CODELENGTH < V_DIGIT) THEN
    PRELENGTH := V_DIGIT - CODELENGTH;
    FOR I IN 1 .. PRELENGTH LOOP
      PRE0 := PRE0 || '0';
    END LOOP;
  END IF;

  --更新code字段
  V_CODE := PRE0 || V_CODE;
  UPDATE CM_RAND SET CODE = V_CODE WHERE TYPE = RAND_TYPE;
  SELECT V_CODE INTO RAND_CODE FROM DUAL;
END;

2.数据库表

create table CM_RAND
(
  ID     NUMBER not null,
  type      VARCHAR2(50) not null,
  code      VARCHAR2(50) not null,
  digit     NUMBER not null
);
-- Add comments to the table 
comment on table CM_RAND
  is '随机数表';
-- Add comments to the columns 
comment on column CM_RAND.id
  is '主键';
comment on column CM_RAND.type
  is '类型';
comment on column CM_RAND.code
  is '当前随机数,0001、0002、0003……';
comment on column CM_RAND.digit
  is '生成几位随机数';
  

mybatis调用oracle存储过程例子(生成随机数)_第1张图片

3.entity

/**  
 * @Description: 随机数表
 */
public class RandEntity {

	private int id;//主键
	private String type;//类型
	private String code;//当前随机数,如0001、0002、0003……
	private int digit;//生成几位随机数
	
	public int getId() {
		return id;
	}
	public void setId(int id) {
		this.id = id;
	}
	public String getType() {
		return type;
	}
	public void setType(String type) {
		this.type = type;
	}
	public String getCode() {
		return code;
	}
	public void setCode(String code) {
		this.code = code;
	}
	public int getDigit() {
		return digit;
	}
	public void setDigit(int digit) {
		this.digit = digit;
	}
	
	
}

4.service

	/**
	 * @Description:生成随机数
	 * @param string 类型
	 */
	public synchronized String getRand(String type) {
		RandEntity randEntity = new RandEntity();
		randEntity.setType(type);
		randDao.getRand(randEntity);
		return randEntity.getCode();
	}

5.dao

/**  
 * @Description: 生成随机数DAO
 */
public interface RandDao {

	/**
	 * @Description:生成随机数
	 * @param type
	 */
	public void getRand(RandEntity randEntity);
	
}

6.mapper

	
	

你可能感兴趣的:(oracle,mybatis)