高瀬博道の技術ブログ

高瀬博道の技術ブログです。

TypeORMに入門する - 5

前回

takasehiromichiex.com

Photoの作成

Photoを作成してデータベースに保存してみます。

src/index.ts
import { AppDataSource } from "./data-source";
import { Photo } from "./entity/Photo";

AppDataSource.initialize()
  .then(() => {
    console.log("start...");

    const photo = new Photo();

    photo.name = "my photo";
    photo.description = "my description";
    photo.filename = "photo.jpg";
    photo.views = 1;
    photo.isPublished = true;

    AppDataSource.manager.save(photo);
  })
  .catch((error) => {
    console.log(error);
  });

実行してみます。

$ docker-compose up -d
$ npm start
start...
query: START TRANSACTION
query: INSERT INTO `photo`(`id`, `name`, `description`, `filename`, `views`, `isPublished`) VALUES (DEFAULT, ?, ?, ?, ?, ?) -- PARAMETERS: ["my photo","my description","photo.jpg",1,1]
query: COMMIT

データベースの中もみてみましょう。

$ docker-compose exec mysql bash
bash-4.4# mysql -u test -p
Enter password: 
Welcome to the MySQL monitor.  Commands end with ; or \g.
Your MySQL connection id is 9
Server version: 8.0.32 MySQL Community Server - GPL

Copyright (c) 2000, 2023, Oracle and/or its affiliates.

Oracle is a registered trademark of Oracle Corporation and/or its
affiliates. Other names may be trademarks of their respective
owners.

Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.

mysql> show databases;
+--------------------+
| Database           |
+--------------------+
| information_schema |
| performance_schema |
| test               |
+--------------------+
3 rows in set (0.00 sec)

mysql> use test
Reading table information for completion of table and column names
You can turn off this feature to get a quicker startup with -A

Database changed
mysql> show tables;
+----------------+
| Tables_in_test |
+----------------+
| photo          |
| user           |
+----------------+
2 rows in set (0.00 sec)

mysql> select * from photo;
+----+----------+----------------+-----------+-------+-------------+
| id | name     | description    | filename  | views | isPublished |
+----+----------+----------------+-----------+-------+-------------+
|  1 | my photo | my description | photo.jpg |     1 |           1 |
+----+----------+----------------+-----------+-------+-------------+
1 row in set (0.00 sec)

データが入っていました。

エンティティマネージャ

AppDataSource.managerは、エンティティマネージャといい、任意のエンティティを管理できます。

insert、update、delete、loadなどができます。

単一の場所にある全てのエンティティにアクセスでき、リポジトリのコレクションのようなものです。

まとめ

ここまでで、

  • Photoの作成について
  • エンティティマネージャについて

を学びました。

次回はリポジトリについてを掘り下げようと思います。

コード

今回のコードは、以下に格納しました。

github.com

2023/2/3 予定