摘要

上一篇文章只完成了简单的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. js中的offsetWidth岁的BUG

    ---恢复内容开始--- 在js使用offsetWidth来操作控件的运动是会遇到: var oDiv = document.getElementById('div1') oDiv.style.wid ...

  2. 【C++ STL编程】queue小例子

    STL是标准化组件,现在已经是C++的一部分,因此不用额外安装什么. #include <queue> #include <iostream> using namespace ...

  3. 加入Tomcat插件到ECLIPSE中的方法

    1.下载Tomcat插件com.sysdeo.eclipse.tomcat_3.3.1.jar 下载路径http://www.eclipsetotale.com/ 2.安装插件 把下载的插件放到E:\ ...

  4. leetcde37. Sudoku Solver

    Write a program to solve a Sudoku puzzle by filling the empty cells. Empty cells are indicated by th ...

  5. 腾讯优测优分享 | 这些年,我们追过的 fiddler

    腾讯优测是专业的移动云测试平台,提供全面兼容性测试,远程真机租用,漏洞分析等多维度的测试服务,旗下优分享提供大量的移动研发及测试相关的干货! 一.fiddler原理简介 fiddler是目前最强大最好 ...

  6. ✡ leetcode 161. One Edit Distance 判断两个字符串是否是一步变换 --------- java

    Given two strings S and T, determine if they are both one edit distance apart. 给定两个字符串,判断他们是否是一步变换得到 ...

  7. LeetCode【217. Contains Duplicate】

    Given an array of integers, find if the array contains any duplicates. Your function should return t ...

  8. ajax+php处理案例

    <div> <table> <tr> <th>状态</th> <th>信息</th> </tr> < ...

  9. JavaScript 装逼指南

    Summary 本文秉承着 你看不懂是你sb,我写的代码就要牛逼 的理念来介绍一些js的装逼技巧. 下面的技巧,后三个,请谨慎用于团队项目中(主要考虑到可读性的问题),不然,leader 干你没商量. ...

  10. WinForm中使用XML文件存储用户配置及操作本地Config配置文件

    大家都开发winform程序时候会大量用到配置App.config作为保持用户设置的基本信息,比如记住用户名,这样的弊端就是每个人一些个性化的设置每次更新程序的时候会被覆盖. 故将配置文件分两大类: ...