node mysql sequelize 无法进行事务回滚

今天学习node想使用一下事务处理 结果sequelize的日记显示回滚了 但实际上插入的记录依然存在

配置和代码如下

//groups.js 这里是模型定义

const Sequelize = require('sequelize');
module.exports = function(sequelize, DataTypes) {
  return sequelize.define('groups', {
    group_id: {
      autoIncrement: true,
      type: DataTypes.INTEGER,
      allowNull: false,
      primaryKey: true,
      comment: "群id"
    },
    user_id: {
      type: DataTypes.INTEGER,
      allowNull: false,
      comment: "群主id"
    },
    name: {
      type: DataTypes.STRING(20),
      allowNull: true,
      comment: "群名称"
    },
    img_url: {
      type: DataTypes.STRING(20),
      allowNull: true,
      comment: "群头像"
    },
    intro: {
      type: DataTypes.TEXT,
      allowNull: false,
      comment: "群公告"
    },
    last_time: {
      type: DataTypes.BIGINT,
      allowNull: true,
      comment: "最后通讯时间"
    },
    time: {
      type: DataTypes.BIGINT,
      allowNull: false,
      defaultValue: 1642435200000,
      comment: "创建时间"
    }
  }, {
    sequelize,
    tableName: 'groups',
    timestamps: false,
    indexes: [
      {
        name: "PRIMARY",
        unique: true,
        using: "BTREE",
        fields: [
          { name: "group_id" },
        ]
      },
    ]
  });
};
//这里是模型调用方法

var DataTypes = require("sequelize").DataTypes;

var _groups = require("./groups");

function models(sequelize) {

  var groups = _groups(sequelize, DataTypes);




  return {

    groups

  };
}
module.exports = models;
//这里是实际接口
/**
 * @func createGroup()
 * @desc 创建群组
 * @param {user_id:群主id,name:群名,img_url:群头像,t:事务}  
 * @return {object:groupList||object:error} 
 */
 exports.createGroup = async function (user_id, name, img_url) {
     //将事务存入变量
    const t = await sequelize.transaction();
    try {

        //传入连接实例并获取初始化模型
        let result = await models(sequelize).groups.create({
            user_id: user_id,
            name: name,
            img_url: img_url
        },{ transaction: t });

        //为了方法直接回滚 尝试了多种写法都行 数据依然存在
        await t.rollback();

        console.log('回滚');
     
        return func.resJsonSuccess(result, '建群成功!');

    } catch (error) {
 
        return func.resJsonError([], error.message);
    }

}

下图可以看到sequelize已经在控制台输出了 ROLLBACK 但实际上插入的数据依然存在

实际响应

阅读 2.9k
1 个回答

问题已解决 原因:代码没问题 表的存储引擎问题 将mysql表存储引擎修改为支持事务处理的 InnoDB即可

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题