ORM是什么?
ORM(Object Relational Mapping,对象关系映射),是一种为了解决面向对象与关系数据库存在的互不匹配的现象的技术,通过描述对象和数据库之间映射的元数据,把程序中的对象自动持久化到关系数据库中。它的作用是在关系型数据库和对象之间作一个映射,这样,我们在具体的操作数据库的时候,就不需要再去和复杂的SQL语句打交道,只要像平时操作对象一样操作它就可以了 。这就好比入java的Mybatis, thinkphp的model类,通过映射数据库,简化数据库操作,使开发者不需要书写复杂的SQL语句,将更多的时间放在逻辑的书写上。
以下是实际案例
一般的封装
const mysql = require('mysql')
const connection = mysql.createConnection({
host: 'localhost',
port: '3306',
user: 'root',
password: '893100',
database: 'd_eam'
})
// 查找多条数据返回数组格式
const findAll = (sql, params) => {
return new Promise((resolve, reject) => {
connection.query(sql, params, (err, result) => {
if (err) {
reject(err)
}
console.log(result)
resolve(JSON.stringify(result))
})
})
}
// 查找单条数据 返回对象格式
const findOne = (sql, params) => {
if (!sql) return null
return new Promise((resolve, reject) => {
connection.query(sql, params, (err, result) => {
if (err) {
reject(err)
}
resolve(JSON.stringify(result[0]))
})
})
}
// 使用
// 查询数据
async getAdmin (ctx) {
const sql = "select * from student where 姓名='厉害'"
const params = []
const res = await connection.findAll(sql, params)
ctx.body = {
data: JSON.parse(res),
statusCode: 200,
message: '数据获取成功'
}
}
orm 封装
const Student = sequelize.define('student', {
// 这里定义模型属性
name: {
type: DataTypes.STRING,
allowNull: false
},
sex: {
type: DataTypes.STRING
// allowNull 默认为 true
},
QQ: {
type: DataTypes.STRING
// allowNull 默认为 true
},
id: {
type: DataTypes.STRING,
primaryKey: true
// allowNull 默认为 true
},
number: {
type: DataTypes.STRING
// allowNull 默认为 true
},
telphone: {
type: DataTypes.STRING
// allowNull 默认为 true
},
classe: {
type: DataTypes.STRING
// allowNull 默认为 true
}
}, {
freezeTableName: true
});
module.exports = Student
// 使用
const res = await Student.findAll()
orm 可以简化操作数据库,更好的约束数据类型
node 常用orm框架
- ORM2:https://github.com/dresende/node-orm2
- sequelize:本文要研究的框架,较常用
- Knex.js:官网:https://knexjs.org/
- TypeORM:采用 TypeScript 编写,支持使用 TypeScript 或 Javascript(ES5,ES6,ES7) 开发。目标是保持支持最新的 Javascript 特性来帮助开发各种用户数据库的应用 - 不管是轻应用还是企业级的
sequelize的基本使用
详细可以查看sequelize官网,获取更多详细配置
一、下载依赖包
下载sequelize
npm install --save sequelize
安装数据库驱动程序:
$ npm install --save pg pg-hstore # Postgres
$ npm install --save mysql2
$ npm install --save mariadb
$ npm install --save sqlite3
$ npm install --save tedious # Microsoft SQL Server
创建数据库配置
1、连接配置
const { Sequelize } = require('sequelize');
// 方法 1: 传递一个连接 URI
const sequelize = new Sequelize('sqlite::memory:') // Sqlite 示例
const sequelize = new Sequelize('postgres://user:pass@example.com:5432/dbname') // Postgres 示例
// 方法 2: 分别传递参数 (sqlite)
const sequelize = new Sequelize({
dialect: 'sqlite',
storage: 'path/to/database.sqlite'
});
// 方法 3: 分别传递参数 (其它数据库)
const sequelize = new Sequelize('database', 'username', 'password', {
host: 'localhost',
dialect: /* 选择 'mysql' | 'mariadb' | 'postgres' | 'mssql' 其一 */
});
2、连接测试
使用 .authenticate() 函数测试连接是否正常
try {
await sequelize.authenticate();
console.log('Connection has been established successfully.');
} catch (error) {
console.error('Unable to connect to the database:', error);
}
3、同步数据库
sequelize.sync() - 如果不存在,则创建该表(如果已经存在,则不执行任何操作)
sequelize.sync({ force: true }) - 将创建表,如果表已经存在,则将其首先删除
sequelize.sync({ alter: true }) - 这将检查数据库中表的当前状态(它具有哪些列,它们的数据类型等),然后在表中进行必要
sequelize.sync()
sequelize.sync({ alter: true });
sequelize.sync({ force: true });
实际案例
const sequelize = new Sequelize('admin', 'root', '893100', {
host: 'localhost',
port: 3306,
dialect: 'mysql'
});
try {
sequelize.authenticate();
// console.log('Connection has been established successfully.');
} catch (error) {
// console.error('Unable to connect to the database:', error);
}
sequelize.sync({ alter: true });
module.exports = sequelize
创建数据库模型
const { DataTypes } = require('sequelize');
const sequelize = require('../config/db')
const Student = sequelize.define('student', {
// 这里定义模型属性
name: {
type: DataTypes.STRING,
allowNull: false
},
sex: {
type: DataTypes.STRING
// allowNull 默认为 true
},
QQ: {
type: DataTypes.STRING
// allowNull 默认为 true
},
id: {
type: DataTypes.STRING,
primaryKey: true
// allowNull 默认为 true
},
number: {
type: DataTypes.STRING
// allowNull 默认为 true
},
telphone: {
type: DataTypes.STRING
// allowNull 默认为 true
},
classe: {
type: DataTypes.STRING
// allowNull 默认为 true
}
}, {
freezeTableName: true
});
module.exports = Student
模型查询
// controller层
const Student = require('../model/students')
async getAdmin (ctx) {
const res = await Student.findAll()
console.log(res)
ctx.body = {
data: res,
statusCode: 200,
message: '数据获取成功'
}
}
其他查询方法可以查看sequelize的文档,查看文档