📜  TypeORM-使用存储库

📅  最后修改于: 2020-10-19 03:41:29             🧑  作者: Mango


存储库特定于实体。换句话说,每个实体都有自己的内置存储库,可以使用连接对象的getRepository()方法对其进行访问,如下所示:

const studRepository = manager.getRepository(Student);

一旦创建了学生存储库对象,就可以将其用于执行学生对象的所有数据库操作。

储存库类型

存储库分为四类。它们如下-

资料库

实体的默认存储库,可以使用下面指定的getRepository()方法访问它-

const studRepository = manager.getRepository(Student);

现在, studRepository可用于查询学生表

树存储库

用于树状结构实体,可以使用以下指定的getTreeRepository()方法进行访问-

const studcaRepository = manager.getTreeRepository(Student);

Mongo存储库

在mongoDB操作实体内部使用,可以使用下面指定的getMongoRepository()方法进行访问-

const detailsRepository = manager.getMongoRepository(Details);

CustomRepository

用于自定义存储库,可以使用以下指定的getCustomRepository()方法对其进行访问,

const myUserRepository = manager.getCustomRepository(UserRepository);

仓库API

让我们学习本章中最重要的EntityManager方法。

经理

我们可以使用下面指定的管理器方法访问EntityManager-

const manager = repository.manager;

queryRunner

queryRunner方法返回自定义查询运行器对象,并由存储库用于数据库操作。示例代码如下-

const queryRunner = repository.queryRunner;

元数据

元数据返回存储库的元数据。示例代码如下-

const metadata = repository.metadata;

询问

query方法执行SQL查询。简单选择查询,如下所示-

const qur = await repository.query(`select * from students`);

插入

insert方法用于将新实体或实体数组插入数据库。示例代码如下-

await repository.insert({ 
   Name: "Student3", 
   Age: 14 
});

上面的查询等同于,

insert into student(Name,age) values("Student3",14)

更新

update用于更新数据库中的现有记录。

await repository.update(1, { Name: "Adam" });

此查询的工作方式类似于以下提到的查询-

update student SET Name = "Adam" where id = 1

删除

delete方法将从表中删除指定的记录,

await repository.delete(Student, 1);

这将从学生表中删除ID为1学生。相当于

delete from student where id=1;

如果要按名称删除,请使用以下查询,

await repository.delete({ Name: "Student1" });

此查询将删除所有名称为Student1的学生

** soft删除并恢复**

它用于软删除数据,您可以根据学生的ID恢复记录。示例代码如下-

await repository.softDelete(1);

您可以使用以下命令恢复学生记录-

await repository.restore(1);

另外一种方式来删除和恢复是使用softRemove恢复方法。示例代码如下-

//find the entities const enty = await repository.find(); 

//soft removed entity const entySoftRemove = await repository.softRemove(enty);

并且,您可以使用以下指定的恢复方法来恢复它们,

await repository.recover(entySoftRemove);

save用于将给定的实体保存到数据库中。可以保存简单学生实体,如下所示-

import {Student} from "./entity/Student"; 

createConnection().then(async connection => {                     
   console.log("Inserting a new record into the student database..."); 
   const stud = new Student();
   stud.Name = "student1"; 
   stud.age = 12; 
   await repository.save(stud);

这会将新的学生记录添加到数据库中。

去掉

remove用于从数据库中删除给定的实体。可以删除Simple学生实体,如下所示-

await repository.remove(stud);

计数

count方法将返回表中可用记录的数量,您可以使用它进行分页。示例代码如下-

const cnt = await repository.count(Student, { age: 12 });

find方法用于搜索目的。它从数据库中获取所有记录,如下所示:

const result = await repository.find({ id: 1 });

找一个

find方法类似,但返回第一个匹配的记录。示例代码如下-

const result = await repository.findOne({ id: 1 });

明确

clear方法清除表中的所有数据。示例代码如下-

await repository.clear();