摘要

上一篇文章只完成了简单的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系列文章三:简单的增删改查询的更多相关文章

  1. MongoDB系列(三):增删改查(CURD)

    上篇讲了MongoDB的基础知识,大家应该对MongoDB有所了解了,当然真正用的还是curd操作,本篇为大家讲解MongoDB的curd操作. 1.数据库操作 #.增 use config #如果数 ...

  2. NHibernate系列文章目录

    第一章:NHibernate基础 NHibernate介绍 第一个NHibernate工程 简单的增删改查询 运行时监控 NHibernate配置 数据类型映射 Get/Load方法 NHiberna ...

  3. ElasticSearch6(三)-- Java API实现简单的增删改查

    基于ElasticSearch6.2.4, Java API创建索引.查询.修改.删除,pom依赖和获取es连接 可查看此文章. package com.xsjt.learn; import java ...

  4. BitAdminCore框架应用篇:(二)创建一个简单的增删改查模块

    NET Core应用框架之BitAdminCore框架应用篇系列 框架演示:http://bit.bitdao.cn 框架源码:https://github.com/chenyinxin/cookie ...

  5. 通过JDBC进行简单的增删改查

    通过JDBC进行简单的增删改查(以MySQL为例) 目录 前言:什么是JDBC 一.准备工作(一):MySQL安装配置和基础学习 二.准备工作(二):下载数据库对应的jar包并导入 三.JDBC基本操 ...

  6. SpringMVC之简单的增删改查示例(SSM整合)

    本篇文章主要介绍了SpringMVC之简单的增删改查示例(SSM整合),这个例子是基于SpringMVC+Spring+Mybatis实现的.有兴趣的可以了解一下. 虽然已经在做关于SpringMVC ...

  7. 初试KONCKOUT+WEBAPI简单实现增删改查

    初试KONCKOUT+WEBAPI简单实现增删改查 前言 konckout.js本人也是刚刚接触,也是初学,本文的目的是使用ko和asp.net mvc4 webapi来实现一个简单增删改查操作.Kn ...

  8. MVC3.0+knockout.js+Ajax 实现简单的增删改查

    MVC3.0+knockout.js+Ajax 实现简单的增删改查 自从到北京入职以来就再也没有接触MVC,很多都已经淡忘了,最近一直在看knockout.js 和webAPI,本来打算采用MVC+k ...

  9. 通过JDBC进行简单的增删改查(以MySQL为例) 目录

    通过JDBC进行简单的增删改查(以MySQL为例) 目录 前言:什么是JDBC 一.准备工作(一):MySQL安装配置和基础学习 二.准备工作(二):下载数据库对应的jar包并导入 三.JDBC基本操 ...

随机推荐

  1. window2008 r2 负载均衡

    两台服务器win2008 r2  ,iis7.5  ip地址192.168.5.16,  192.168.5.18  虚拟ip 192.168.5.30 设置过程: 1.在两台服务器上安装负载均衡模块 ...

  2. windows server域的概念以及wmic(centos上命令)

    wmic访问在域中的计算机.其中ops\administrator为域用户名,也可以写作ops.com\administrator.ops是域名ops.com的简写,是MS的NetBIOS一套吗? . ...

  3. rpm软件包管理

    RPM 有五种基本的操作方式(不包括创建软件包): 安装, 卸载, 升级, 查询,和验证. 下面我们就来逐一的讲解吧. 一. 安装RPM包 RPM 软件包通常具有类似foo-1.0-1.i386.rp ...

  4. Nested List Weight Sum -- LeetCode 339

    Given a nested list of integers, return the sum of all integers in the list weighted by their depth. ...

  5. Oracle数据库初级学习

    第一天 SQL查询语句 CMD——SQLPLUS----账号 soctt 密码 tiger,输入完成后进入SQL数据库,如图显示即连接成功. 连接成功后 ,我们首先设置一下基本界面, --设置 每列显 ...

  6. Android 学习第6课,循环功能

    package ch02; public class jiujiuchengfa { public static void main(String[] args) { // TODO 自动生成的方法存 ...

  7. RSS(Residual Sum of Squares)的自由度为什么是n-1呢

    [转载请注明出处]http://www.cnblogs.com/mashiqi 在回归问题中,偶尔我们会遇到求方差的估计的情况.举了例子,我们常常通过Gaussian分布${\cal N}(\mu , ...

  8. 16年青岛网络赛 1001 I Count Two Three

    题目链接:http://acm.hdu.edu.cn/contests/contest_showproblem.php?pid=1001&cid=723 I Count Two ThreeTi ...

  9. ASP代码审计 -4.命令执行漏洞总结

    命令执行漏洞: 保存为cmd.asp,提交链接: http://localhost/cmd.asp?ip=127.0.0.1 即可执行命令 <%ip=request("ip" ...

  10. crontabs Permission denied

    问题 jack@somemachine /data/jack $ crontab -e crontabs/jack: Permission denied 解决办法 sudo chown root:cr ...