19
24

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Node.jsにてMySQLのORM:sequelize

Last updated at Posted at 2019-08-21

はじめに

JAVAではRDBのデータのCURD処理はJDBC経由で操作できます。自由度が高い反面、SQL書く際に可読性、保守性が弱い問題があります。
ORMの発達でHibernate、MyBatis、jOOQなどのライブラリを利用して仕組み上はよくなります。

Node.jsからMySQLなどのRDBを操作する場合もORMを利用したほうが良いと思います。
特にテーブルのカラム数が多い場合は、?の数など一致しないミスが発生しやすいからです。また、SQLインジェクションも注意する必要があります。

Node.jsのMySQLのORMとしてSequelizeは有名です。
SequelizeはMySQL、MariaDB、PostgreSQL、SQL Serverもサポートします。

Sequelize:https://sequelize.org/

インストール

npm install --save sequelize
npm install --save mysql2

使い方

sequelize定義

const Sequelize = require('sequelize');

const sequelize = new Sequelize('database', 'username', 'password', {
  dialect: 'mysql'
})

sequelizeプールの場合

const sequelize = new Sequelize('database', 'username', 'password', {
  dialect: 'mysql',
  host: 'localhost',
  pool: {
    max: 5,
    min: 0,
    acquire: 30000,
    idle: 10000
  }
});

モデル定義

const UserModel = sequelize.define(
  'users',
  {
    userId: {
      field: 'user_id',
      type: Sequelize.INTEGER(11),
      primaryKey: true,
      autoIncrement: true
    }, // INT(11)       NOT NULL  PRIMARY KEY  AUTO_INCREMENT
    lastName: {
      field: 'last_name',
      type: Sequelize.STRING(32),
      allowNull: true
    },
    firstName: {
      field: 'first_name',
      type: Sequelize.STRING(32),
      allowNull: true
    }
  },
  {
    timestamps: true,
    createdAt: false, //デフォルト項目を生成しないように
    updatedAt: false,  //デフォルト項目を生成しないように
    tableName: "users" //明示的にテーブル名を指定
  }
)

データタイプ:https://sequelize.org/master/manual/data-types.html

CURDメソッドを用意

exports.find = async function(whereData) {
  return await UserModel.findAll({
    where: whereData
  })
}

exports.get = async function(userId) {
  return await UserModel.findByPk(userId)
}

exports.update = async function(updateData, whereCondition, updateFields) {
  return await UserModel.update(updateData, {
    where: whereCondition,
    fields: updateFields
  })
}

exports.create = async function(userData) {
  return await UserModel.create(userData)
}

詳しく説明:https://sequelize.org/master/manual/models-definition.html

ユーザー更新例

  const whereCondition = {
    userId: 10000  //更新条件
  }
  const updateFields = ['lastName', 'firstName']  //指定したカラムのみ更新
  const updateData = { lastName: 'yamata', firstName: 'tarou' } //更新データ

  const result = await mysqlUser.update(updateData, whereCondition, updateFields)

updateのSQLを書くより楽です。

以上

19
24
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
19
24

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?