一、什么是ORM

对象关系映射(Object Relational Mapping,简称ORM)是通过使用描述对象和数据库之间映射的元数据,将面向对象语言程序中的对象自动持久化到关系数据库中。本质上就是将数据从一种形式转换到另外一种形式。 这也同时暗示着额外的执行开销;然而,如果ORM作为一种中间件实现,则会有很多机会做优化,而这些在手写的持久层并不存在。 更重要的是用于控制转换的元数据需要提供和管理;但是同样,这些花费要比维护手写的方案要少;而且就算是遵守ODMG规范的对象数据库依然需要类级别的元数据。

ORM 技术是在对象和数据库之间提供了一条桥梁,前台的对象型数据和数据库中的关系型的数据通过这个桥梁来相互转化。

不同的编程语言,有不同的ORM框架。例如Java,它的ORM框架就有:Hibernate,Ibatis/Mybatis等等。在Node Web开发中,Sequelize 就是一款比较流行的 ORM 框架。

二、安装相关插件

  • npm i sequelize mysql2 -d

三、Sequelize的使用

1. 创建连接对象, 并模块化

  1. /* seq.js */
  2. const Sequelize = require('sequelize')
  3. const conf = {
  4. host: 'localhost',
  5. dialect: 'mysql'
  6. }
  7. const seq = new Sequelize('koa2_weibo_db', 'root', '1233456', conf)
  8. module.exports = seq

2. 定义数据表结构

  1. /* model.js */
  2. const Sequelize = require('sequelize')
  3. const seq = require('./seq')
  4. // 创建 User 模型,数据表的名字是users
  5. const User = seq.define('user', {
  6. // id会自动创建,并设为主键、自增
  7. userName: {
  8. type: Sequelize.STRING, // varchar(255)
  9. allowNull: false
  10. },
  11. password: {
  12. type: Sequelize.STRING,
  13. allowNull: false
  14. },
  15. nickName: {
  16. type: Sequelize.STRING,
  17. comment: '昵称' // 注释
  18. }
  19. // 会自动创建 createdAt 和 updatedAt
  20. })
  21. // 创建 Blog 模型
  22. const Blog = seq.define('blog', {
  23. title: {
  24. type: Sequelize.STRING,
  25. allowNull: false
  26. },
  27. content: {
  28. type: Sequelize.STRING,
  29. allowNull: false
  30. },
  31. userId: {
  32. type: Sequelize.INTEGER,
  33. allowNull: false
  34. }
  35. })
  36. // 外键关联
  37. Blog.belongsTo(User, {
  38. // 创建外键 Blog.userId -> User.id
  39. foreignKey: 'userId'
  40. })
  41. User.hasMany(Blog, {
  42. // 创建外键 Blog.userId -> User.id
  43. foreignKey: 'userId'
  44. })
  45. module.exports = {
  46. User,
  47. Blog
  48. }

3. 同步数据表结构

  1. /* sync.js */
  2. const seq = require('./seq')
  3. require('./model')
  4. // 测试连接
  5. seq.authenticate().then(() => {
  6. console.log('ok')
  7. }).catch(() => {
  8. console.log('err')
  9. })
  10. // 同步表结构
  11. seq.sync({
  12. force: true // 强制同步,先删除表,然后新建
  13. }).then(() => {
  14. console.log('sync ok')
  15. process.exit()
  16. })