Sequelize增删改查与事务 | Sequelize


Sequelize ORM

1.数据的增删改查与事务

初始化模型

const { Sequelize, Model, DataTypes } = require("sequelize");


const sequelize = new Sequelize({
    dialect: "mysql",
    host: "localhost",
    port: 3306,
    username: "root",
    password: "password",
    database: "demo",
    timezone: "+08:00",
    pool: {
        max: 10,
        min: 0
    },
    logging: true,
});


class User extends Model {}

User.init({
    id: {
        type: DataTypes.INTEGER({ unsigned: true }),
        primaryKey: true,
        autoIncrement: true,
        comment: "用户ID",
    },
    username: {
        type: DataTypes.STRING(40),
        unique: true,
        allowNull: false,
        comment: "账号",
    },
    password: {
        type: DataTypes.CHAR(64),
        allowNull: false,
        comment: "密码",
    },
}, {
    sequelize: sequelize,
    tableName: "user",
    modelName: "user",
    paranoid: true,  // 逻辑删除,填充删除时间
    underscored: true,  // 内置字段用下划线代替驼峰命名
});
    • 单条插入

      (async ()=>{
          try{
              await sequelize.sync({force: true});
              const user = await User.create({
                  username: "mkl",
                  password: "123456",
              });
              console.log("创建成功", user.toJSON());
          } catch(e){
              console.log(e);
          }
      })();
      
    • 批量插入

      (async ()=>{
          try{
              await sequelize.sync({force: true});
              const users = await User.bulkCreate([
                  {username: "mkl", password: "123456"}, 
                  {username: "bob", password: "123456"},
              ], {
                  individualHooks: true, // 对每个数据都执行一次生命周期,为false只执行bulkCreate的生命周期
              });
              console.log("创建成功", users.map(user=>user.toJSON()));
          } catch(e){
              console.log(e);
          }
      })();
      
  • 更新

    • 批量更新

      (async ()=>{
          try{
              // await sequelize.sync({force: true});
              const [count, users] = await User.update({username: "bob", password: "123456"},
              {
                  where: {
                      username: 'marry',
                  },
                  individualHooks: true, // 对每个数据都执行一次生命周期,为false只执行bulkCreate的生命周期
              });
              console.log(`总共更新了${count}`, users.map(user=>user.toJSON()));
          } catch(e){
              console.log(e);
          }
      })();
      
    • 单条更新

      (async ()=>{
          try{
              const user = await User.findOne({
                  where: {
                      username: "bob"
                  }
              });
              if (!user){
                  throw new Error("用户不存在.");
              }
              user.password = "password";
              await user.save();
              console.log(user.toJSON());
          } catch(e){
              console.log(e);
          }
      })();
      
  • 删除

    • 批量删除(逻辑)
      (async ()=>{
          try{
              const count = await User.destroy({
                  where: {
                      username: "bob"
                  }
              });
              console.log(`删除了${count}条数据.`)
          } catch(e){
              console.log(e);
          }
      })();
      
    • 单条删除(物理)

      
      
  • 查询

    • 单条查询

      根据ID查询

      (async ()=>{
          /**
          * 根据ID查询
          */
          const userById = await User.findByPk(1);
          console.log(userById?userById.toJSON():"未查到数据");
      })();
      

      findOne根据where查询

      (async ()=>{
          /**
          * 根据条件查询,并返回指定字段
          */
          const user = await User.findOne({
              attributes: ["password"],
              where: {
                  username: "mkl",
              }
          });
          console.log(user?user.toJSON():"未查到数据");
      })();
      
    • 多条查询

      (async ()=>{
          /**
          * 根据条件查询,并返回指定字段
          */
          const user = await User.findAll({
              attributes: ["password"],
              where: {
                  username: "mkl",
              },
              order: [
                  ["id", "DESC"],
                  ["username", "DESC"],
              ],
              offset: 0,
              limit: 10
          });
          console.log(user);
      })();
      
    • 查询或创建单条数据

      (async ()=>{
          /**
          * 根据条件查询,并返回指定字段
          */
          const [user, created] = await User.findOrCreate({
              where: {
                  username: "bob",
              },
              defaults: {
                  username: "bob",
                  password: "password",
              }
          });
          if (created){
              console.log("创建用户成功", user.toJSON());
          } else {
              console.log("查询用户成功", user.toJSON());
          }
          console.log(user);
      })();
      
    • 同时查询列表和数据总数

      (async ()=>{
          const {rows, count} = await User.findAndCountAll({
              where: {
                  username: "mkl",
              }
          });
          console.log(rows.map(row=>row.toJSON()), count);
      })();
      
    • 统计数据

      (async () => {
          const count = await User.count({
              where: {
                  username: "mkl",
              }
          });
          console.log(count);
      })();
      
    • 运算符

      查看上一篇博客

  • 事务

    • 自动事务

      (async () => {
          const result = await sequelize.transaction({
              isolationLevel: Transaction.ISOLATION_LEVELS.SERIALIZABLE  // 设置隔离级别
          }, async (transaction) => {
              const user = await User.create({
                  username: "marry",
                  password: 123,
              }, {transaction: transaction});  // 选项中必须传递事务对象
              const user2 = await User.create({
                  username: "jerry",
                  password: 456,
              }, {transaction: transaction});
              return [user, user2];
          });
          console.log(result.map(user=>user.toJSON()));
      })();
      
    • 手动事务

      (async () => {
          const transaction = await sequelize.transaction({
              isolationLevel: Transaction.ISOLATION_LEVELS.SERIALIZABLE,
          });
          try{
              const user = await User.create({
                  username: "miaokela",
                  password: "password",
              }, {transaction: transaction});
              const user2 = await User.create({
                  username: "boby",
                  password: "123456",
              });
              await transaction.commit();
          } catch(e){
              await transaction.rollback();
              throw e;
          }
      })();
      


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM