typeorm常见用法
时间: 2024-04-24 17:23:28 浏览: 18
TypeORM 是一个用于 Node.js 和 TypeScript 的 ORM(对象关系映射)库,它提供了许多常见的用法来简化数据库操作。以下是一些常见的 TypeORM 用法:
1. 定义实体(Entity):使用 `@Entity()` 装饰器来定义数据库表的实体类。可以使用装饰器来定义表名、列、关系等。
```typescript
@Entity()
class User {
@PrimaryGeneratedColumn()
id: number;
@Column()
name: string;
@Column()
age: number;
}
```
2. 创建数据库连接:使用 `createConnection()` 函数来创建数据库连接。可以在连接选项中指定数据库类型、主机、端口、用户名、密码等。
```typescript
import { createConnection } from "typeorm";
createConnection({
type: "mysql",
host: "localhost",
port: 3306,
username: "root",
password: "password",
database: "myapp",
entities: [User],
synchronize: true,
});
```
3. 查询数据:使用 `getRepository()` 函数获取实体类的存储库(Repository)对象,然后使用该存储库对象进行查询操作。
```typescript
import { getRepository } from "typeorm";
const userRepository = getRepository(User);
const users = await userRepository.find();
console.log(users);
```
4. 插入数据:使用存储库对象的 `save()` 方法插入数据。
```typescript
const newUser = new User();
newUser.name = "John";
newUser.age = 25;
await userRepository.save(newUser);
```
5. 更新数据:使用存储库对象的 `save()` 方法更新数据。
```typescript
const userToUpdate = await userRepository.findOne(1);
userToUpdate.age = 30;
await userRepository.save(userToUpdate);
```
6. 删除数据:使用存储库对象的 `remove()` 方法删除数据。
```typescript
const userToRemove = await userRepository.findOne(1);
await userRepository.remove(userToRemove);
```
这些只是 TypeORM 的一些常见用法示例,还有许多其他功能和选项可以探索和使用。你可以查看 TypeORM 的官方文档以获取更多详细信息和示例代码。
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)