首先创建表: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 $$
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$$
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;
继续执行当前记录sql则成功
创建nextval函数 :
DELIMITER $$
DROP FUNCTION IF EXISTS nextval
$$
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"
"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>
接下来在service层写对应的获取数据方法:
@Service
public class MySQLFunctionServiceImpl implements MySQLFunctionService{
@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调用给其他表的主键赋值后存入数据库
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。