数据库

数据库使用的是typeorm

中文文档:https://typeorm.biunav.comopen in new window

官方文档:https://typeorm.ioopen in new window,国外网站有可能打不开,打不开看上面的中文文档

midway数据库文档:https://www.yuque.com/midwayjs/midway_v2/ormopen in new window

事务示例

cool-admin封装了自己事务,让代码更简洁

示例

import { Inject, Provide } from '@midwayjs/decorator';
import { BaseService, CoolTransaction } from '@cool-midway/core';
import { InjectEntityModel } from '@midwayjs/orm';
import { Repository, QueryRunner } from 'typeorm';
import { DemoAppGoodsEntity } from '../entity/goods';

/**
 * 商品
 */
@Provide()
export class DemoGoodsService extends BaseService {
  @InjectEntityModel(DemoAppGoodsEntity)
  demoAppGoodsEntity: Repository<DemoAppGoodsEntity>;

  /**
   * 事务
   * @param params
   * @param queryRunner 无需调用者传参, 自动注入,最后一个参数
   */
  @CoolTransaction({ isolation: 'SERIALIZABLE' })
  async testTransaction(params: any, queryRunner?: QueryRunner) {
    await queryRunner.manager.insert<DemoAppGoodsEntity>(DemoAppGoodsEntity, {
      title: '这是个商品',
      pic: '商品图',
      price: 99.0,
      type: 1,
    });
  }
}

TIP

CoolTransaction中已经做了异常捕获,所以方法内部无需捕获异常,必须使用queryRunner做数据库操作, 而且不能是异步的,否则事务无效, queryRunner会注入到被注解的方法最后一个参数中, 无需调用者传参

Last Updated: