NHibernate系列文章三:简单的增删改查询
摘要
上一篇文章只完成了简单的NHibernate安装、配置和连接数据库。这篇文章介绍怎样实现最简单的数据库读写操作。
1. 重构ISessionFactory生成过程
将生成ISessionFactory的代码从main函数中移除,变成使用属性控制。
private static ISessionFactory _sessionFactory;
public static ISessionFactory SessionFactory
{
get
{
if (_sessionFactory == null)
{
var cfg = new Configuration();
cfg.DataBaseIntegration(x =>
{
x.ConnectionString = "Data Source=localhost;Initial Catalog=NHibernateDemoDB;Integrated Security=True;Connect Timeout=15;Encrypt=False;TrustServerCertificate=False;ApplicationIntent=ReadWrite;MultiSubnetFailover=False";
x.Driver<SqlClientDriver>();
x.Dialect<MsSql2008Dialect>();
});
cfg.AddAssembly(Assembly.GetExecutingAssembly());
_sessionFactory = cfg.BuildSessionFactory();
}
return _sessionFactory;
}
}
SessionFactory的创建很占用系统资源,一般在整个应用程序中只创建一次。因此,这里通过判断if (_sessionFactory == null)实现一个最简单的单例模式。
2. GetAll和GetById函数代码
private static IList<Customer> GetAll()
{
using (var session = SessionFactory.OpenSession())
{
IList<Customer> list = session.CreateCriteria<Customer>().List<Customer>();
return list;
}
} private static Customer GetById(int id)
{
using (var session = SessionFactory.OpenSession())
{
Customer customer = session.Get<Customer>(id);
return customer;
}
}
使用using子句,在using代码块完成后,将自动调用ISession的Dispose方法关闭Session
3. 增删改函数代码
private static int Insert(Customer customer)
{
using (var session = SessionFactory.OpenSession())
{
var identifier = session.Save(customer);
session.Flush();
return Convert.ToInt32(identifier);
}
} private static void Update(Customer customer)
{
using (var session = SessionFactory.OpenSession())
{
session.SaveOrUpdate(customer);
session.Flush();
}
} private static void Delete(int id)
{
using (var session = SessionFactory.OpenSession())
{
var customer = session.Load<Customer>(id);
session.Delete(customer);
session.Flush();
}
}
- session.Save: 插入新记录,返回新纪录主键值
- session.SaveOrUpdate: 如果被调用的Customer对象在数据库里不存在(新记录),则插入新记录,否则修改该记录
- session.Delete: 传入Customer对象进行删除
- 增删改操作完成之后需要调用session.Flush()方法,将对象持久化写入数据库。如果不调用此方法,方法结束后修改记录不能写入到数据库
4. 添加方法CreateCustomer
private static Customer CreateCustomer()
{
var customer = new Customer
{
FirstName = "Daniel",
LastName = "Tang",
Points = ,
HasGoldStatus = true,
MemberSince = new DateTime(, , ),
CreditRating = CustomerCreditRating.Good,
AverageRating = 42.42424242,
Street = "123 Somewhere Avenue",
City = "Nowhere",
Province = "Alberta",
Country = "Canada"
}; return customer;
}
5. 修改main函数
static void Main(string[] args)
{
Customer newCustomer = CreateCustomer();
int customerId = Insert(newCustomer);
Console.WriteLine("new customer id: {0}", customerId); IList<Customer> list = GetAll();
Console.WriteLine("customer list count: {0}", list.Count);
foreach(var item in list)
{
Console.WriteLine("{0} {1}", item.FirstName, item.LastName);
} var customer = GetById(customerId);
Console.WriteLine("GetById: {0} {1}", customer.FirstName, customer.LastName); customer.LastName = "Chen";
Update(customer);
var updatedCustomer = GetById(customerId);
Console.WriteLine("updated: {0} {1}", updatedCustomer.FirstName, updatedCustomer.LastName); Delete(customerId);
var existedCustomer = GetById(customerId);
Console.WriteLine("after deleted: existing: {0}", existedCustomer != null); Console.ReadLine();
}
6. 完整的代码
using NHibernate;
using NHibernate.Cfg;
using NHibernate.Dialect;
using NHibernate.Driver;
using System;
using System.Collections.Generic;
using System.Reflection; namespace NHibernateDemoApp
{
class Program
{
private static ISessionFactory _sessionFactory; public static ISessionFactory SessionFactory
{
get
{
if (_sessionFactory == null)
{
var cfg = new Configuration(); cfg.DataBaseIntegration(x =>
{
x.ConnectionString = "Data Source=localhost;Initial Catalog=NHibernateDemoDB;Integrated Security=True;Connect Timeout=15;Encrypt=False;TrustServerCertificate=False;ApplicationIntent=ReadWrite;MultiSubnetFailover=False";
x.Driver<SqlClientDriver>();
x.Dialect<MsSql2008Dialect>();
});
cfg.AddAssembly(Assembly.GetExecutingAssembly());
_sessionFactory = cfg.BuildSessionFactory();
}
return _sessionFactory;
}
} static void Main(string[] args)
{
Customer newCustomer = CreateCustomer();
int customerId = Insert(newCustomer);
Console.WriteLine("new customer id: {0}", customerId); IList<Customer> list = GetAll();
Console.WriteLine("customer list count: {0}", list.Count);
foreach(var item in list)
{
Console.WriteLine("{0} {1}", item.FirstName, item.LastName);
} var customer = GetById(customerId);
Console.WriteLine("GetById: {0} {1}", customer.FirstName, customer.LastName); customer.LastName = "Chen";
Update(customer);
var updatedCustomer = GetById(customerId);
Console.WriteLine("updated: {0} {1}", updatedCustomer.FirstName, updatedCustomer.LastName); Delete(customerId);
var existedCustomer = GetById(customerId);
Console.WriteLine("after deleted: existing: {0}", existedCustomer != null); Console.ReadLine();
} private static Customer CreateCustomer()
{
var customer = new Customer
{
FirstName = "Daniel",
LastName = "Tang",
Points = ,
HasGoldStatus = true,
MemberSince = new DateTime(, , ),
CreditRating = CustomerCreditRating.Good,
AverageRating = 42.42424242,
Street = "123 Somewhere Avenue",
City = "Nowhere",
Province = "Alberta",
Country = "Canada"
}; return customer;
} private static IList<Customer> GetAll()
{
using (var session = SessionFactory.OpenSession())
{
IList<Customer> list = session.CreateCriteria<Customer>().List<Customer>();
return list;
}
} private static Customer GetById(int id)
{
using (var session = SessionFactory.OpenSession())
{
Customer customer = session.Get<Customer>(id);
return customer;
}
} private static int Insert(Customer customer)
{
using (var session = SessionFactory.OpenSession())
{
var identifier = session.Save(customer);
session.Flush();
return Convert.ToInt32(identifier);
}
} private static void Update(Customer customer)
{
using (var session = SessionFactory.OpenSession())
{
session.SaveOrUpdate(customer);
session.Flush();
}
} private static void Delete(int id)
{
using (var session = SessionFactory.OpenSession())
{
var customer = session.Load<Customer>(id);
session.Delete(customer);
session.Flush();
}
}
}
}
7. 执行结果

NHibernate系列文章三:简单的增删改查询的更多相关文章
- MongoDB系列(三):增删改查(CURD)
上篇讲了MongoDB的基础知识,大家应该对MongoDB有所了解了,当然真正用的还是curd操作,本篇为大家讲解MongoDB的curd操作. 1.数据库操作 #.增 use config #如果数 ...
- NHibernate系列文章目录
第一章:NHibernate基础 NHibernate介绍 第一个NHibernate工程 简单的增删改查询 运行时监控 NHibernate配置 数据类型映射 Get/Load方法 NHiberna ...
- ElasticSearch6(三)-- Java API实现简单的增删改查
基于ElasticSearch6.2.4, Java API创建索引.查询.修改.删除,pom依赖和获取es连接 可查看此文章. package com.xsjt.learn; import java ...
- BitAdminCore框架应用篇:(二)创建一个简单的增删改查模块
NET Core应用框架之BitAdminCore框架应用篇系列 框架演示:http://bit.bitdao.cn 框架源码:https://github.com/chenyinxin/cookie ...
- 通过JDBC进行简单的增删改查
通过JDBC进行简单的增删改查(以MySQL为例) 目录 前言:什么是JDBC 一.准备工作(一):MySQL安装配置和基础学习 二.准备工作(二):下载数据库对应的jar包并导入 三.JDBC基本操 ...
- SpringMVC之简单的增删改查示例(SSM整合)
本篇文章主要介绍了SpringMVC之简单的增删改查示例(SSM整合),这个例子是基于SpringMVC+Spring+Mybatis实现的.有兴趣的可以了解一下. 虽然已经在做关于SpringMVC ...
- 初试KONCKOUT+WEBAPI简单实现增删改查
初试KONCKOUT+WEBAPI简单实现增删改查 前言 konckout.js本人也是刚刚接触,也是初学,本文的目的是使用ko和asp.net mvc4 webapi来实现一个简单增删改查操作.Kn ...
- MVC3.0+knockout.js+Ajax 实现简单的增删改查
MVC3.0+knockout.js+Ajax 实现简单的增删改查 自从到北京入职以来就再也没有接触MVC,很多都已经淡忘了,最近一直在看knockout.js 和webAPI,本来打算采用MVC+k ...
- 通过JDBC进行简单的增删改查(以MySQL为例) 目录
通过JDBC进行简单的增删改查(以MySQL为例) 目录 前言:什么是JDBC 一.准备工作(一):MySQL安装配置和基础学习 二.准备工作(二):下载数据库对应的jar包并导入 三.JDBC基本操 ...
随机推荐
- CSS总结 最后的选择符和字体、元素常见样式
在伪类选择符中,还有很多,其中比较有意思的是E:target 当我们想做出点击超链接后链接变色且其他链接变回原来的颜色时,就可以用到这个选择符 <a href="#a1" i ...
- 2016 - 1- 24 大文件下载 关于NSOutStream 的使用补充
// // ViewController.m // 大文件下载 // // Created by Mac on 16/1/24. // Copyright © 2016年 Mac. All right ...
- DIY FSK RFID Reader
This page describes the construction of an RFID reader using only an Arduino (Nano 3.0 was tested, b ...
- xpcall 安全调用
-- xpall (调用函数f, 错误函数fe[, 参数]) function fun(a,b) -- 这里的参数没什么实际作用,就是展示下用法 return a / bend -- xpc ...
- 修改FastColoredTextBox控件完成选择
//判断是否是中文 public bool IsChina(char c) { bool BoolValue = false; if (Convert ...
- centos7 查询jdk安装路径
- 如何在JBoss WildFly 8 自定义log4j日志
最近在 JBoss WildFly 8 下部署 Web应用,自定义的 log4j 日志不工作.console下无日志输出,用System.out.println都不输出内容到console. 原因是J ...
- 有向图强连通分量 Tarjan算法
[有向图强连通分量] 在有向图G中,如果两个顶点间至少存在一条路径,称两个顶点强连通(strongly connected).如果有向图G的每两个顶点都强连通,称G是一个强连通图.非强连通图有向图的极 ...
- VC2010 MFC中实现printf调试功能,即MFC程序利用控制台输出调试信息。
1.在项目自动生成的stdafx.h文件中添加下面头文件 #include <io.h> #include <fcntl.h> #include <stdio.h> ...
- linux项目-之系统安装部署-cobbler
http://cobbler.github.io/manuals/2.6.0/1/1_-_Release_Notes.html http://www.osyunwei.com/archives/760 ...