目录
写在前面
上篇文章一个小插曲,分析了延迟加载是如何解决N+1 select查询问题的。这篇开始介绍在nhibernate中如何使用存储过程,同时也介绍如何使用代码生成器,提高开发效率。
文档与系列文章
[NHibernate]持久化类(Persistent Classes)
[NHibernate]集合类(Collections)映射
[NHibernate]缓存(NHibernate.Caches)
[NHibernate]NHibernate.Tool.hbm2net
[NHibernate]Nhibernate如何映射sqlserver中image字段
[NHibernate]条件查询Criteria Query
Nhibernate中使用存储过程
这里使用MyGeneration Code来生成针对TB_Customer数据表的增删改的存储过程。MyGeneration Code是一款开源的代码生成器,下载地址MyGeneration Code。
安装完成后,打开MyGeneration,如果第一次使用MyGeneration会自动弹出“默认设置”对话框,需要你对MyGeneration设置数据库连接字符串、模板语言、数据库驱动、模板存放路径等信息。
然后选择“save”对默认配置进行保存。然后MyGenration主界面就会弹出。如图
展开Microsoft SQL Server节点,找到“Script Insert/Update/Delete Procedures for SQL Server”模板,右击选择执行,我们利用这个模板为Customer表生成增删改存储过程。
打开后,这个模板界面如下,选择输出路径和数据库表,这里我输入路径为桌面,选择TB_Customer表,点击OK。截图如下:
此时在桌面“C:\Users\Wolfy\Desktop\Customer”中就会生成sql_procs_TB_Customer.sql文件,打开数据库,然后执行该文件中的sql脚本。
USE [Shop]
GO --|--------------------------------------------------------------------------------
--| [TB_CustomerInsert] - Insert Procedure Script for TB_Customer
--|--------------------------------------------------------------------------------
IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = object_id (N'[dbo].[TB_CustomerInsert]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1) DROP PROCEDURE [dbo].[TB_CustomerInsert]
GO CREATE PROCEDURE [dbo].[TB_CustomerInsert]
(
@CustomerID uniqueidentifier = NEWID() OUTPUT,
@CustomerName nvarchar(16) = NULL,
@CustomerAddress nvarchar(128) = NULL,
@Version int
)
AS
SET NOCOUNT ON INSERT INTO [TB_Customer]
(
[CustomerID],
[CustomerName],
[CustomerAddress],
[Version]
)
VALUES
(
@CustomerID,
@CustomerName,
@CustomerAddress,
@Version
) RETURN @@Error
GO --|--------------------------------------------------------------------------------
--| [TB_CustomerUpdate] - Update Procedure Script for TB_Customer
--|--------------------------------------------------------------------------------
IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = object_id (N'[dbo].[TB_CustomerUpdate]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1) DROP PROCEDURE [dbo].[TB_CustomerUpdate]
GO CREATE PROCEDURE [dbo].[TB_CustomerUpdate]
(
@CustomerID uniqueidentifier,
@CustomerName nvarchar(16) = NULL,
@CustomerAddress nvarchar(128) = NULL,
@Version int
)
AS
SET NOCOUNT ON UPDATE [TB_Customer]
SET
[CustomerID] = @CustomerID,
[CustomerName] = @CustomerName,
[CustomerAddress] = @CustomerAddress,
[Version] = @Version
WHERE
[CustomerID] = @CustomerID RETURN @@Error
GO --|--------------------------------------------------------------------------------
--| [TB_CustomerDelete] - Update Procedure Script for TB_Customer
--|--------------------------------------------------------------------------------
IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = object_id (N'[dbo].[TB_CustomerDelete]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1) DROP PROCEDURE [dbo].[TB_CustomerDelete]
GO CREATE PROCEDURE [dbo].[TB_CustomerDelete]
(
@CustomerID uniqueidentifier
)
AS
SET NOCOUNT ON DELETE
FROM [TB_Customer]
WHERE
[CustomerID] = @CustomerID RETURN @@Error
GO
sql_procs_TB_Customer.sql
我使用的是sql server2012的版本,在执行脚本的时候,生成添加Customer的存储过程,有问题
将NewId()函数去掉。修改后的存储过程
USE [Shop]
GO
--|--------------------------------------------------------------------------------
--| [TB_CustomerInsert] - Insert Procedure Script for TB_Customer
--|--------------------------------------------------------------------------------
IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = object_id (N'[dbo].[TB_CustomerInsert]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1) DROP PROCEDURE [dbo].[TB_CustomerInsert]
GO CREATE PROCEDURE [dbo].[TB_CustomerInsert]
(
@CustomerID uniqueidentifier OUTPUT,
@CustomerName nvarchar(16) = NULL,
@CustomerAddress nvarchar(128) = NULL,
@Version int
)
AS
SET NOCOUNT ON INSERT INTO [TB_Customer]
(
[CustomerID],
[CustomerName],
[CustomerAddress],
[Version]
)
VALUES
(
NEWID(),
@CustomerName,
@CustomerAddress,
@Version
) RETURN @@Error
生成的存储过程如下:
一个例子
在NHibernate的映射文件中,在Class元素中提供了<sql-delete>、<sql-insert>、<sql-update>元素用于删除、新建、更新对象,注意这三个元素顺序唯一,就是下图显示的顺序,在根元素提供了<sql-query>元素用来查询对象,下图显示在Class元素中的增删改存储过程元素。
删除对象
修改映射文件添加存储过程,打开Customer.hbm.xml映射文件,在Class元素下添加<sql-delete>节点,调用TB_CustomerDelete存储过程,TB_CustomerDelete存储过程有一个CustomerID参数,这里用一个问号表示:
<!--存储过程,check参数:none/rowcount/param-->
<sql-delete>exec TB_CustomerDelete ?</sql-delete>
测试
/// <summary>
/// 通过存储过程方式删除客户信息
/// </summary>
/// <param name="customer"></param>
/// <returns></returns>
public bool DeleteCustomerByIDWithProcedure(Customer customer)
{
var session = NHibernateHelper.GetSession();
using (ITransaction trans = session.BeginTransaction())
{
try
{
session.Delete(customer);
session.Flush();
trans.Commit();
return true;
}
catch (Exception)
{
trans.Rollback();
throw;
}
}
}
此时会有一个异常“Row was updated or deleted by another transaction (or unsaved-value mapping was incorrect): [Wolfy.Shop.Domain.Entities.Customer#b0720295-9541-40b3-9994-610066224db8]”。这个错误是存储过程写法错误,我们修改TB_CustomerDelete存储过程,去掉SET NOCOUNT ON,代码片段如下:
ALTER PROCEDURE [dbo].[TB_CustomerDelete]
(
@CustomerID uniqueidentifier
)
AS
--SET NOCOUNT ON DELETE
FROM [TB_Customer]
WHERE
[CustomerID] = @CustomerID RETURN @@Error
再次运行进行测试,测试成功,查看生成的sql语句
你会发现在sql语句里面多了一个@p1的参数。这个参数为之前添加的Version参数,nhibernate中乐观并发控制添加的。
如何解决?
修改存储过程,将版本号添加上。
ALTER PROCEDURE [dbo].[TB_CustomerDelete]
(
@CustomerID uniqueidentifier,
@Version int
)
AS
--SET NOCOUNT ON DELETE
FROM [TB_Customer]
WHERE
[CustomerID] = @CustomerID and [Version]=@Version RETURN @@Error
不要忘了,此时的存储过程有两个参数了,版本号在映射文件中已经处理了,存储过程中已经帮咱们自动添加上了,如果是其他的参数可在映射文件通过"?,?..."添加多个参数。
<!--存储过程,check参数:none/rowcount/param-->
<sql-delete check="rowcount" >exec TB_CustomerDelete ?</sql-delete>
再次运行进行测试,成功,生成的sql语句
exec sp_executesql N'exec TB_CustomerDelete @p0',N'@p0 uniqueidentifier,@p1 int',@p0='3727A133-C079-4DF9-B31E-7625B03F95DF',@p1=1
当然了,如果你不想使用存储过程,也可以直接在<sql-delete>中写SQL语句,像这样,照样用。
<sql-delete>DELETE FROM [TB_Customer] WHERE [CustomerID] = ? and [Version] =?</sql-delete>
生成的sql语句为
exec sp_executesql N'DELETE FROM [TB_Customer] WHERE [CustomerID] = @p0 and [Version] =@p1',N'@p0 uniqueidentifier,@p1 int',@p0='64C35DEE-84D9-4C2D-ABAF-7D53631E3EAA',@p1=1
总结
这篇文章主要介绍了代码生成器的简单使用及nhibernate中使用存储过程删除数据的过程。
参考文章:http://www.cnblogs.com/lyj/archive/2008/11/03/1325291.html