摘要

上一篇文章只完成了简单的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. javascript笔记8-表单脚本、JSON、AJAX

    通过表单提交,很方便的可以从界面把参数传递给后台. 如果前后台我们有大量数据需要交互,JSON方便我们传递和读取. 如果需要更新一个界面的某一部分数据,并不想刷新界面,就要用到Ajax. 1. 表单脚 ...

  2. php通用安装程序,导入数据文件(.sql)的安装程序

    php通用安装程序,导入数据文件(.sql)的安装程序 该程序只需要1个php文件 和 1个数据文件,很方便调用.install/index.php         程序文件install/mycms ...

  3. 【Avalon源码】iterator

    function iterator(vars, body, ret) { var fun = 'for(var ' + vars + 'i=0,n = this.length; i < n; i ...

  4. Sublime Text 3开启自动换行

    在Submine Text 3中要开启自动换行功能只需要两个步骤: 1.找到查看(View) 2.点击弹出菜单中的自动换行即可 但是如果是在2中的话就相对麻烦少少,现在也说下其开启自动换行功能的步骤: ...

  5. Erlang 102 Erlang并发编程

    笔记系列 Erlang环境和顺序编程Erlang并发编程Erlang分布式编程YawsErlang/OTP 日期              变更说明 2014-11-02 A outline 2014 ...

  6. 关于只针对ie7浏览器的css问题

    如代码: .centerDiv .search_k2{ margin-left: 18px; *margin-left: 9px; margin-top: 10px; height: 40px;} 中 ...

  7. 转--Oracle 审计和测试操作

    http://blog.itpub.net/21605631/viewspace-759640/转 Oracle 审计和测试操作 :: 分类: Linux 1.1 相关参数 AUDIT_SYS_OPE ...

  8. nginx配置rewrite

    1. uri  和 url读取区别 区别就是URI定义资源,而URL不单定义这个资源,还定义了如何找到这个资源. 比如说,一个服务器上,到一个文件夹/网页的绝对地址(absolute path)就是U ...

  9. Nginx php-fpm php mysql

    rpm -ivh http://nginx.org/packages/centos/6/noarch/RPMS/nginx-release-centos-6-0.el6.ngx.noarch.rpm ...

  10. Windows环境下使用Redis缓存工具的图文详细方法

    一.简介 redis是一个key-value存储系统.和Memcached类似,它支持存储的value类型相对更多,包括string(字符串).list(链表).set(集合)和zset(有序集合). ...