Node.js ORM框架 sequelize模块、应用、对数据库内的数据进行增删改查操作
一、什么是ORM框架
- ORM(Object Relational Mapping,对象关系映射):是一种为了解决面向对象与关系数据库存在的互不匹配的现象的技术,通过描述对象和数据库之间映射的元数据,把程序中的对象自动持久化到关系数据库中。它的作用是在关系型数据库和对象之间作一个映射,这样,我们在具体的操作数据库的时候,就不需要再去和复杂的SQL语句打交道,只要像平时操作对象一样操作它就可以了 。
类 ----- 表
属性 ---- 列
对象 ---- 行
- 持久(Persistence)化,即把数据(如内存中的对象)保存到可永久保存的存储设备中(如磁盘)。持久化的主要应用是将内存中的数据存储在关系型的数据库中,当然也可以存储在磁盘文件中、XML数据文件中等等。
- ORM就是把业务实体中的对象与关系数据库中的关系数据关联起来。
对象-关系映射(ORM)系统一般以中间件的形式存在。
- ORM技术特点:
1、提高了开发效率。ORM可以自动对Entity对象与数据库中的Table进行字段与属性的映射,所以我们实际可能已经不需要一个专用的、庞大的数据访问层。
2、ORM提供了对数据库的映射,不用sql直接编码,能够像操作对象一样从数据库获取数据。
二、什么是Sequelize
- 基于promise的关系型数据库ORM框架,这个库完全采用JavaScript开发并且能够用在Node.JS环境中,易于使用,支持多SQL方言(dialect),。它当前支持MySQL、MariaDB、SQLite、PostgreSQL、Sql
- Sequelize的特色:
- 强大的模型定义,支持虚拟类型。
- 支持完善的数据验证,减轻前后端的验证压力。
- Sequelize的查询非常全面和灵活
三、Sequelize应用示例
- 安装MySQL:npm install mysql2
- 安装Sequelize:npm install sequelize
连接数据库配置(dbconfig.js)
//配置sequelize(dbconfig.js):
//导入mysql模块
const mysql = require('mysql2')
//导入sequelize模块
const Sequelize = require('sequelize')
//创建squelize对象,初始化连接(支持连接池):四个参数:数据库名称,用户名,密码,配置
var MySequelize = new Sequelize('dbms','root','123456abc',{
host: 'localhost', //数据库地址
port: 3306,
dialect: 'mysql', //数据库类型
pool:{
max:20, //最大连接对象的个数
min:5, //最少连接对象的个数
idle:10000 //最长等待时间,单位是毫秒
}
})
module.exports = MySequelize;
创建模型(Model):actorModel.js
const Sequelize = require('sequelize');
const MySequelize = require('../config/dbconfig');
//定义模型 创建actorModle模型,该模型对的表名是actor
var actorModle = MySequelize.define('actor',{
sid:{
type: Sequelize.INTEGER, //表示属性的数据类型
field: 's_id', //属性对应的列名,若不定义field,则表中的列名就是属性名
primaryKey: true, //表示主键
autoIncrement: true //表示主键自增
},
sname:{
type: Sequelize.STRING(50),
field: 's_name',
allowNull: false, //表示该列不能为空
//unique:true //表示该列的值必须唯一
},
sgender:{
type:Sequelize.STRING(5),
field:'s_gender',
allowNull: false
},
sbirthday:{
type:Sequelize.DATE,
field: 's_birthday',
allowNull: false
},
saddress:{
type: Sequelize.STRING(100),
field: 's_address',
allowNull: false
}
},
{
freezeTableName: true, //true表示使用给定表名,false表示模型名加s作为表名
timestamps: false //true表示给模型带上时间戳属性(createAt、updateAt),false表示不带时间戳属性,多出两列
}
);
//var student = StudentModle.sync({force: false}); //同步数据库,force的值为false,表若存在先删除后创建,force的值为true,表示表如果存在则不创建
module.exports = actorModle;
对数据库进行增删改查(CURD)操作模板
A、插入数据:模型名.create( {
属性名1:值
属性名2:值
...........
}).then((result)=>{
插入成功后代码;参数 'result' 中放的是插入成功的数据
}).catch((error)=>{
插入失败后的代码;参数 'error'中放的是插入失败的信息
})
B、删除数据:模型名.destroy({
where : { //删除条件
属性名:值
}
}).then((result)=>{
删除成功后代码,参数 'result '中放的是删除的行数(整数)
}).catch((error)=>{
删除失败的处理代码,参数 'error'中放的是删除失败的信息
})
C、更新数据:模型名.findOne({
where:{ //要更新的元组
属性名:值
}
}).then((result)=>{ //参数'result'中放的是查找到的信息
result.update({
属性名:值
属性名:值
}).then((data)=>{ //'data'中放的是更新后的数据
处理代码
}).catch((error)=>{
处理代码
})
}).catch((error)=>{
处理代码
})
D、查询数据:模型名.findAll({
where:{ //可有可无 条件
属性名:值
}
}).then((result)=>{
插入成功后代码;参数 'result' 中放的是查询的结果集
}).catch((error)=>{
插入失败后的代码;参数 'error'中放的是失败的信息
})
应用实例:
const Sequelize = require('sequelize');
const actorModel = require('../modle/actorModle');
//插入数据
actorModel.create({
sname:'张三',
sgender:'男',
sbirthday:'2021-08-01',
saddress:'江苏南京'
}).then(result=>{
console.log("插入成功!",result);
}).catch(err=>{
console.log("插入失败!",err);
})
//查询数据
actorModel.findAll({
raw: true //不显示查询结果中的多余数据
}).then(data=>{
console.log(data);
});
//删除记录
actorModel.destroy({
where:{
sid:4
}
}).then(result=>{
console.log("删除成功",result)
}).catch(err=>{
console.log("删除失败!",err)
})
//更新记录
actorModel.findOne({
where: {
sid:5
}
}).then(stu=>{
stu.update({
sname:"林彦俊",
sgender:"男"
}).then(result=>{
console.log("更新成功!",result)
raw: true;
}).catch(err=>{
console.log("更新失败",err)
})
}).catch(error=>{
console.log("查无此人",error)
})
四、Sequelize查询
- 只查询部分列(字段):
actorModel.findAll({
attributes: ['sname','saddress'],
raw: true
}).then((result)=>{
console.log(result);
}).catch(err=>{
console.log(err)
})
结果:
2. 聚合函数
//聚合函数
actorModel.findAll({
attributes: [[Sequelize.fn('count',Sequelize.col('s_id')),'记录总数']], //此时col所对应的必须是列名
raw: true
}).then(result=>{
console.log(result)
}).catch(err=>{
console.log(err)
})
结果:
3. 模糊查询like
//模糊查询,查询表中姓贾的记录
actorModel.findAll({
where:{
sname: {
[Op.like]:'贾%'
}
},
raw: true
}).then(result=>{
console.log(result)
}).catch(err=>{
console.log(err)
})
结果:
4. between查询
//between
actorModel.findAll({
where: {
sage: {
[Op.between]:[18,21] //年龄在18~21之间
}
},
raw: true
}).then(result=>{
console.log(result)
}).catch(err=>{
console.log(err)
})
结果(不全,但能知全意):