我正在尝试使用feathersjs-sequelize和mysql数据库重现Java / Hibernate / TABLE Sequence功能https://dzone.com/articles/hibernate-identity-sequence。
所以,我在mysql中创建了以下函数
FUNCTION `generate_pessoa_seq`() RETURNS bigint(16)
BEGIN
DECLARE R_ID BIGINT(16);
UPDATE pessoa_seq SET next_value = next_value + 1;
SELECT next_value INTO R_ID FROM pessoa_seq;
RETURN R_ID;
之后我在mysql cli中测试了:
mysql> select generate_pessoa_seq();
+-----------------------+
| generate_pessoa_seq() |
+-----------------------+
| 11 |
+-----------------------+
1 row in set (0,00 sec)
确定。现在我可以使用11作为我的表的ID值“pessoa”。
所以我试图按照下面的想法(pessoa hook)
const pessoaBeforeCreateHook = options => { // always wrap in a function so you can pass options and for consistency.
return hook => {
console.log('Pessoa hook ' + hook);
sequelize = hook.app.get('sequelize');
var newId = -1; //forcing an error
sequelize.query('select generate_pessoa_seq();',{ type: sequelize.QueryTypes.SELECT}).then(function(response){
//getNewId();
newId = response;
}).error(function(err){
console.log(err);
newId=-1;
});
hook.data.IdiPessoa=newId;
return Promise.resolve(hook); // A good convention is to always return a promise.
};
};
exports.before = {
all: [],
find: [],
get: [],
create: [pessoaBeforeCreateHook()],
update: [],
patch: [],
remove: []
};
感谢您的帮助。
答案 0 :(得分:1)
Sequelize查询返回一个promise并以异步方式运行,因此在解析后要运行的任何逻辑都需要在.then处理程序中。您还必须从钩子函数返回该承诺,以便它等待它完成:
所以,最终的代码在这里:
pessoaService.hooks({
before: {
create(hook) {
const sequelize = app.get('sequelize');
var newId = -1; //forcing an error
return sequelize.query('select generate_pessoa_seq() as nextId;',{
nest: true,
raw: true }).then(function(response){
//getNewId();
var stringId = response[0];
newId = parseInt(stringId.nextId, 10);
hook.data.IdiPessoa=newId;
return hook;
}).error(function(err){
console.log(err);
return hook;
});
}
}
});