Node.js关于ORM框架以及sequelize模块的使用

什么是ORM框架

ORM(Object Relational Mapping)即对象关系映射,是一种为了解决面向对象关系数据库存在的互不匹配的现象的技术,通过描述对象和数据库之间映射的元数据,把程序中的对象自动持久化到关系数据库中。

作用:是在关系型数据库和对象之间作一个映射,这样,我们在具体的操作数据库的时候,就不需要再去写复杂的SQL语句,只要像平时操作对象一样操作它就可以了 。

持久化(Persistence):即把数据(如内存中的对象)保存到可永久保存的存储设备中(如磁盘),持久化的主要应用是将内存中的数据存储在关系型的数据库中,当然也可以存储在磁盘文件中、XML数据文件中等等。

ORM特点:

  • 提高了开发效率
  • ORM提供了对数据库的映射,不用sql语句直接编码

sequelize模块
基于promise的关系型数据库ORM框架,这个库完全采用JavaScript开发并且能够用在Node.JS环境中, sequelize是实现了ORM思想的一个模块

类 ---- 表
属性 — 列
类的对象 — 表的行(元祖)

sequelize模块实现ORM框架

安装sequelize模块 必须要安装mysql启动模块

	npm install sequelize

配置sequelize

// 导入sequelize模块
const Sequelize = require('sequelize')
// 创建sequelize对象 四个参数分别是 数据库名 用户名 密码 配置
var MySequelize = new Sequelize('dbms','root','123456',{
    host: 'localhost',
    port: 3306,
    dialect: 'mysql',//数据库类型
    pool:{// 数据库连接池
        max: 20,// 最大连接对象的个数
        min: 5,// 最少连接对象的个数
        idle: 10000,// 最长等待时间  单位是毫秒
    }
});
module.exports = MySequelize;

创建模型

const Sequelize = require('sequelize')
const MySequelize = require('../config/ORM.js')

// 创建StudentModel模型 该模型的表名是student
var StudentModel = MySequelize.define('student',{
    sid:{
        type: Sequelize.INTEGER,// 表示属性的数据类型
        field: 's_id', // 属性对应的列名 若不定义field 则表中的列名就是属性名
        primaryKey: true,// 表示主键
        autoIncrement: true // 表示主键自增
    },
    sname:{
        type: Sequelize.STRING(50),
        field: 's_name',
        allowNull: false,// 表示该列不能为空
        unque: true // 表示该列的值必须唯一
    },
    sgender:{
        type: Sequelize.STRING(4),
        field: 's_gender',
        allowNull: false
    },
    sbirthday:{
        type: Sequelize.DATE,
        field: 's_birthday',
        alowNull: false
    },
    saddress:{
        type: Sequelize.STRING(100),
        field: 's_address',
        allowNull: false
    }
},{
    freezeTableName: true, // true表示使用给定表名 false表示模型名加s组为表名
    timestamps: false, // true表示给模型带上时间戳属性(creatAt,updateAt) false表示不带时间戳属性
})

var student = StudentModel.sync({force:false}); // 同步数据库 force为true表示先删除后创建 默认为false
module.exports = StudentModel;

对数据库进行增删改查

插入数据

A.插入数据:  模型名.create({
                            属性名:,
                            属性名2:}).then((result)=>{
                            插入成功后的代码; 参数result中放的是插入的数据
                        }).catch(error){
                            插入失败后的代码; 参数error中放的是错误信息
                        }

删除数据

B.删除数据:  模型名.destroy({
                            where:{
                                属性名:}
                        }).then((result)=>{
                            删除成功后的代码; 参数result中放的是删除的行数
                        }).catch(error)=>{
                            删除失败的处理代码, 参数error放的是错误信息
                        }

更新数据

C.更新数据:  模型名.update({
                            where:{
                                属性名:}
                        }).then((result)=>{ // 参数result中放的是查找到的数据
                            result.update({
                                属性值:,
                                属性值2:,
                            }).then((data)=>{ // 参数data中放的是更新后的数据
                                处理代码
                            }).catch((error)=>{
                                处理代码
                            })
                        })

查询结果

D.查询数据:  模型名.findAll({
                                where:{
                                    属性:}
                            }).then(result=>{
                                参数result放的是查询的结果
                            }).catch(error=>{
                                参数error放的是错误信息
                            })

下面导入模型进行实例演示

// 导入模型
const StudentModel = require('./model/StudentModel')
// 插入数据
StudentModel.create({
    sname:'张三',
    sgender:'男',
    sbirthday:'2021-8-01',
    saddress:'南京'
}).then( result =>{
    console.log('插入成功!',result)
}).catch( err => {
    console.log('插入失败!',err)
})

//查询数据
StudentModel.findAll({
    raw: true // 不显示拆线呢结果集合中的多余数据
}).then(data=> {
    console.log(data);
})

//删除记录
StudentModel.destroy({
    where:{
        sid:2
    }
}).then(result=>{
    console.log('删除成功',result)
}).catch(err=>{
    console.log('删除失败!',err)
})

//更新记录
StudentModel.findOne({
    where:{
        sid:8,
    }
}).then(stu=>{
    stu.update({
        sname:'潇潇',
        sgender:'girl'
    }).then(result=>{
        console.log('成功',result)
    }).catch(er=>{
        console.log('失败',err)
    })
})

//查询部分字段
StudentModel.findAll({
    attributes: ['sname','saddress'],
    raw: true,
}).then(result=>{
    console.log(result)
}).catch(err=>{
    console.log(err)
})

// 聚合函数
const Sequelize = require('sequelize')
StudentModel.findAll({
    attributes:[[Sequelize.fn('COUNT',Sequelize.col('s_name')),'记录总数']],
    raw: true
}).then(data=>{
    console.log(data)
})
  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值