首先建立表:CREATE TABLE sys_sequence
( NAME
varchar(50) NOT NULL, CURRENT_VALUE
int(11) NOT NULL DEFAULT '0', INCREMENT
int(11) NOT NULL DEFAULT '1',
PRIMARY KEY (NAME
)
)
插入記錄:INSERT INTO SYS_SEQUENCE(NAME,CURRENT_VALUE,INCREMENT) VALUES('TBL_FS', 1,1)
執行函數:DELIMITER $$ sql
DROP FUNCTION IF EXISTS currval
$$ 數據庫
CREATE DEFINER=root
@%
FUNCTION currval
(seq_name VARCHAR(50)) RETURNS INT(11)
BEGIN
DECLARE VALUE INTEGER;
SET VALUE=0;
SELECT current_value INTO VALUE
FROM sys_sequence
WHERE NAME=seq_name;
RETURN VALUE;
END$$ mybatis
DELIMITER ;
查詢記錄:select currval('TBL_FS');
若是出現Error Code: 1449 The user specified as a definer ('root'@'%') does not exist 錯誤,則執行以下sql:grant all privileges on . to root@"%" identified by "password";
flush privileges; app
繼續執行當前記錄sql則成功
建立nextval函數 :
DELIMITER $$
DROP FUNCTION IF EXISTS nextval
$$ ide
CREATE DEFINER=root
@%
FUNCTION nextval
(seq_name varchar(50)) RETURNS int(11)
BEGIN
UPDATE sys_sequence
SET CURRENT_VALUE = CURRENT_VALUE + INCREMENT
where name=seq_name;
return currval(seq_name);
END$$
建立好了表以後 :如圖
NAME字段爲代理表名稱,原來爲 TBL_FS,此處我修改了,current_value爲當前序號,INCREMENT爲步長。函數
接下來在mybatis配置文件目錄下建立mapper文件:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"spa
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="MySQLFunctionMapper">代理
<select id="getNexVal" parameterType="string" resultType="int"> select nextval(#{table_name}) </select> <select id="getCurrVal" parameterType="string" resultType="int"> select currval(#{table_name}) </select>
</mapper>code
接下來在service層寫對應的獲取數據方法:
@Service
public class MySQLFunctionServiceImpl implements MySQLFunctionService{xml
@Resource(name = "daoSupport") private DaoSupport dao; //DaoSupport封裝了對應mybatis操做數據庫的方法,上篇文章有介紹 @Override public int getNexVal(String table_name) { // TODO Auto-generated method stub return (int) dao.findForObject("MySQLFunctionMapper.getNexVal", table_name); } @Override public int getCurrVal(String table_name) { // TODO Auto-generated method stub return (int) dao.findForObject("MySQLFunctionMapper.getCurrVal", table_name); }
}
這樣就能夠調用getNexVal方法獲取代理表中的ID值,再對應賦值到其餘表的主鍵中,通常可在controller調用給其餘表的主鍵賦值後存入數據庫