NHibernate的简单例子

@(编程)

因为项目需求,搭了一个NHibernate的例子,中间遇到了一些问题,通过各种方法解决了,在这里记录一下最后的结果。

1. 需要的dll

Common.Logging.dll 		     1.2.0.0
Common.Logging.Log4Net.dll 1.2.0.2
log4net.dll 1.2.10.0
MySql.Data.dll 6.9.8.0
NHibernate.dll 3.0.0.400
Spring.Aop.dll 1.3.1.40711
Spring.Core.dll 1.3.1.40711
Spring.Data.dll 1.3.1.40711
Spring.Data.NHibernate30.dll 1.3.1.40711

2.需要安装的程序

MySQL-connector-net

如果不安装,则报错,大致如下:

Error thrown by a dependency of object 'MySql-5.0' defined in 'assembly [Spring.Data, Version=1.1.2.20125, Culture=neutral, PublicKeyToken=65e474d141e25e07], resource [Spring.Data.Common.dbproviders.xml]' :
2.Unsatisfied dependency expressed through constructor argument with index 2 of type [System.Type] :
3.Could not convert constructor argument value [MySql.Data.MySqlClient.MySqlConnection, MySql.Data, Version=5.0.7.0, Culture=neutral, PublicKeyToken=c5687fc88969c44d] to required type [System.Type] :
4.Cannot convert property value of type [System.String] to required type [System.Type] for property ''.
5.while resolving 'constructor argument with name dbmetadata' to '(inner object)' defined in 'assembly [Spring.Data, Version=1.1.2.20125, Culture=neutral, PublicKeyToken=65e474d141e25e07], resource [Spring.Data.Common.dbproviders.xml]'

另外这个版本一定要与上面的mysql.data.dll版本相同。

3. 数据库SQL

CREATE TABLE `account` (
`id` varchar(45) NOT NULL,
`name` varchar(45) DEFAULT NULL,
`code` varchar(45) DEFAULT NULL,
`balance` double DEFAULT NULL,
`exchange` varchar(45) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

4. 实体与映射文件

Account


namespace NHibernateDemo
{
/// <summary>
/// 用户账户
/// </summary>
public class Account
{
public virtual string Id { get; set; }
/// <summary>
/// 账户名称
/// </summary>
public virtual string Name { get; set; }
/// <summary>
/// 账户编码
/// </summary>
public virtual string Code { get; set; }
/// <summary>
/// 账户当前余额
/// </summary>
public virtual double Balance { get; set; }
/// <summary>
/// 交易所
/// </summary>
public virtual string Exchange { get; set; }
}
}

Account.hbm.xml

要设置为嵌入的资源

<?xml version="1.0" encoding="utf-8" ?>
<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2" assembly="NHibernateDemo">
<class name="NHibernateDemo.Account" table="account" lazy="false" >
<id name="Id" unsaved-value="null" column="id" type="string" />
<property name="Name" column="name" length="40" not-null="true" />
<property name="Code" column="code" length="30" not-null="false"/>
<property name="Balance" column="balance" length="30" not-null="false"/>
<property name="Exchange" column="exchange" length="60" not-null="false"/>
</class>
</hibernate-mapping>

5. DAO

IAccountDao

using System.Collections.Generic;

namespace NHibernateDemo
{
public interface IAccountDao
{
IList<Account> GetAll();
}
}

AccountDaoImpl

using Spring.Data.NHibernate;
using System;
using System.Collections.Generic; namespace NHibernateDemo
{
[Spring.Stereotype.Repository]
public class AccountDaoImpl : IAccountDao
{
public HibernateTemplate HibernateTemplate { set; get; } public IList<Account> GetAll()
{
try
{
Account entity = new Account();
entity.Id = Guid.NewGuid().ToString();
entity.Balance = 0;
entity.Code = "a";
entity.Exchange = "b";
entity.Name = "c";
this.HibernateTemplate.Save(entity);
var result = this.HibernateTemplate.LoadAll(typeof(Account)); foreach (Account item in result)
{
Console.WriteLine(item.Name);
}
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
} return null;
}
}
}

6. BLL

SpringFactory

using NHibernate;

namespace NHibernateDemo
{
public sealed class SpringFactory
{
public static IAccountDao GetAccountDao()
{
return SpringHelper<IAccountDao>.GetObject("AccountDao");
} }
}

SpringHelper

namespace NHibernateDemo
{
using Common.Logging;
using Spring.Context;
using Spring.Context.Support;
using System;
using System.Reflection; public sealed class SpringHelper<T>
where T : class
{ #region Static Fields private static readonly ILog Log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); #endregion #region Public Methods and Operators /// <summary>
/// 传入objId 通过Spring得到对应实体
/// </summary>
/// <param name="objId"></param>
/// <param name="withLog"></param>
/// <returns></returns>
public static T GetObject(string objId, bool withLog = true)
{
if (string.IsNullOrEmpty(objId))
{
return default(T);
}
try
{
IApplicationContext ctx = ContextRegistry.GetContext();
return ctx.GetObject(objId) as T;
}
catch (Exception ex)
{
if (withLog)
{
Log.Error("", ex);
}
return default(T);
}
} #endregion
}
}

7.配置文件

App.config

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<configSections>
<sectionGroup name="spring">
<section name="context" type="Spring.Context.Support.ContextHandler, Spring.Core"/>
<section name="objects" type="Spring.Context.Support.DefaultSectionHandler, Spring.Core"/>
</sectionGroup>
<sectionGroup name="common">
<section name="logging" type="Common.Logging.ConfigurationSectionHandler, Common.Logging"/>
</sectionGroup>
</configSections> <common>
<logging>
<factoryAdapter type="Common.Logging.Log4Net.Log4NetLoggerFactoryAdapter, Common.Logging.Log4Net">
<arg key="configType" value="FILE-WATCH"/>
<arg key="configFile" value="config/Log4Net.xml"/>
</factoryAdapter>
</logging>
</common> <spring>
<context>
<resource uri="config/ApplicationContext.xml"/>
</context>
</spring>
</configuration>

ApplicationContext.xml

<?xml version="1.0" ?>
<objects default-autowire="byName" default-lazy-init="true" xmlns:db="http://www.springframework.net/database" xmlns:tx="http://www.springframework.net/tx" xmlns="http://www.springframework.net">
<!--描述-->
<description>
数据访问的配置信息 包括:DbProvider NHibernate
</description> <!-- 通过主应用程序的上下文配置文件引用 -->
<object type="Spring.Objects.Factory.Config.PropertyPlaceholderConfigurer, Spring.Core">
<property name="ConfigSections" value="spring/databaseSettings"/>
</object> <object id="HibernateTransactionManager" type="Spring.Data.NHibernate.HibernateTransactionManager, Spring.Data.NHibernate30">
<property name="DbProvider" ref="DbProvider"/>
<property name="SessionFactory" ref="NHibernateSessionFactory"/>
</object> <object id="HibernateTemplate" type="Spring.Data.NHibernate.HibernateTemplate">
<property name="SessionFactory" ref="NHibernateSessionFactory"/>
<property name="TemplateFlushMode" value="Auto"/>
<property name="CacheQueries" value="true"/>
</object> <!-- 数据库的配置 -->
<db:provider connectionString="Data Source=localhost;User Id=root;Password=password;database=test" id="DbProvider" provider="MySql-5.1"/> <!-- NHibernate 配置 --> <!-- 可以通过 name 为其指定别名 name="SessionFactory" -->
<object id="NHibernateSessionFactory" type="Spring.Data.NHibernate.LocalSessionFactoryObject,Spring.Data.NHibernate30"> <!-- 关于数据库连接的配置,直接使用 DbProvider 中的设置,这样,不需要为 Hibernate 再提供连接串和驱动 -->
<property name="DbProvider" ref="DbProvider"/> <!-- 包含有映射文件的程序集,需要分析的hbm程序集名称 -->
<property name="MappingAssemblies">
<list>
<value>NHibernateDemo</value>
</list>
</property> <!-- 其他的参数 -->
<property name="HibernateProperties">
<dictionary>
<!-- 方言 -->
<entry key="dialect" value="NHibernate.Dialect.MySQLDialect"/>
<entry key="connection.driver_class" value="NHibernate.Driver.MySqlDataDriver"/>
<entry key="use_proxy_validator" value="false"/>
<entry key="show_sql" value="true"/>
</dictionary>
</property> <!-- 必须增加此项说明,与 Spring 的声明式事务集成 -->
<property name="ExposeTransactionAwareSessionFactory" value="true"/> </object>
<object id="AccountDao" type="NHibernateDemo.AccountDaoImpl,NHibernateDemo">
<property name="HibernateTemplate" ref="HibernateTemplate"></property>
</object>
</objects>

Log4Net.xml

<?xml version="1.0" encoding="utf-8"?>
<configuration>
<configSections>
<section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler,log4net, Version=1.2.11.0, Culture=neutral, PublicKeyToken=669e0ddf0bb1aa2a"/>
</configSections>
<log4net>
<!-- Console部分log输出格式的设定 -->
<appender name="ConsoleAppender" type="log4net.Appender.ConsoleAppender">
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%date %-5level [%file] [ %line行 ] - %message%newline"/>
</layout>
</appender> <!-- 日志文件部分log输出格式的设定 -->
<appender name="RollingLogFileAppender" type="log4net.Appender.RollingFileAppender">
<lockingModel type="log4net.Appender.FileAppender+MinimalLock"/>
<file value="log.txt"/>
<appendToFile value="true"/>
<maxSizeRollBackups value="10"/>
<maximumFileSize value="1MB"/>
<rollingStyle value="Size"/>
<staticLogFileName value="true"/>
<layout type="log4net.Layout.PatternLayout">
<header value=""/>
<footer value=""/>
<ConversionPattern value="%date %-5level [%file] [%line行] - %message%newline"/>
</layout>
</appender>
<!-- Setup the root category, add the appenders and set the default level -->
<root>
<level value="ALL"/>
<appender-ref ref="ConsoleAppender"/>
<appender-ref ref="RollingLogFileAppender"/>
</root>
</log4net>
</configuration>

8.调用代码

using System;

namespace NHibernateDemo
{
class Program
{
static void Main(string[] args)
{
IAccountDao dao = SpringFactory.GetAccountDao();
dao.GetAll();
Console.Read();
}
}
}

9.下载地址

http://files.cnblogs.com/files/wardensky/NHibernateDemo.zip

NHibernate的简单例子的更多相关文章

  1. NHIBERNATE的简单框架的设计

    NHIBERNATE的简单框架的设计 上次的 NHibernate的Session管理策略和NHibernateHelper 发布并提供下载,给NHibernate刚入门的同学们带来很多便利. 最近有 ...

  2. Hibernate4.2.4入门(一)——环境搭建和简单例子

    一.前言 发下牢骚,这段时间要做项目,又要学框架,搞得都没时间写笔记,但是觉得这知识学过还是要记录下.进入主题了 1.1.Hibernate简介 什么是Hibernate?Hibernate有什么用? ...

  3. AgileEAS.NET SOA 中间件平台.Net Socket通信框架-简单例子-实现简单的服务端客户端消息应答

    一.AgileEAS.NET SOA中间件Socket/Tcp框架介绍 在文章AgileEAS.NET SOA 中间件平台Socket/Tcp通信框架介绍一文之中我们对AgileEAS.NET SOA ...

  4. spring mvc(注解)上传文件的简单例子

    spring mvc(注解)上传文件的简单例子,这有几个需要注意的地方1.form的enctype=”multipart/form-data” 这个是上传文件必须的2.applicationConte ...

  5. ko 简单例子

    Knockout是在下面三个核心功能是建立起来的: 监控属性(Observables)和依赖跟踪(Dependency tracking) 声明式绑定(Declarative bindings) 模板 ...

  6. mysql定时任务简单例子

    mysql定时任务简单例子 ? 1 2 3 4 5 6 7 8 9     如果要每30秒执行以下语句:   [sql] update userinfo set endtime = now() WHE ...

  7. java socket编程开发简单例子 与 nio非阻塞通道

    基本socket编程 1.以下只是简单例子,没有用多线程处理,只能一发一收(由于scan.nextLine()线程会进入等待状态),使用时可以根据具体项目功能进行优化处理 2.以下代码使用了1.8新特 ...

  8. 一个简单例子:贫血模型or领域模型

    转:一个简单例子:贫血模型or领域模型 贫血模型 我们首先用贫血模型来实现.所谓贫血模型就是模型对象之间存在完整的关联(可能存在多余的关联),但是对象除了get和set方外外几乎就没有其它的方法,整个 ...

  9. [转] 3个学习Socket编程的简单例子:TCP Server/Client, Select

    以前都是采用ACE的编写网络应用,最近由于工作需要,需要直接只用socket接口编写CS的代码,重新学习这方面的知识,给出自己所用到的3个简单例子,都是拷贝别人的程序.如果你能完全理解这3个例子,估计 ...

随机推荐

  1. web工程中web.xml元素加载顺序以及配置实例

    简介 web.xml是web工程的配置文件,容器加载web工程时,会首先从WEB-INF中查询web.xml,并加载其中的配置信息,可以将web.xml认为是web工程的入口. web.xml中包含有 ...

  2. XManager介绍、安装、使用

    简介 Xmanager是一款小巧.便捷的浏览远端X窗口系统的工具.在工作中经常使用Xmanager来登录远端的Linux系统,在X窗口系统上作图形化的操作.Xmanager可以将PC变成X Windo ...

  3. UVa 839 (递归方式读取二叉树) Not so Mobile

    题意: 递归的方式输入一个树状天平(一个天平下面挂的不一定是砝码还可能是一个子天平),判断这个天平是否能满足平衡条件,即W1 * D1 == W2 * D2. 递归的方式处理输入数据感觉很巧妙,我虽然 ...

  4. Codeforces 435 A Queue on Bus Stop

    题意:给出n队人坐车,车每次只能装载m人,并且同一队的人必须坐同一辆车,问最少需要多少辆车 自己写的时候想的是从前往后扫,看多少队的人的和小于m为同一辆车,再接着扫 不过写出来不对 后来发现把每一队的 ...

  5. Web程序员最常用的11款PHP框架

    PHP框架是Web程序员和开发人员最为有用的工具. PHP框架可以帮助用户更快地开发项目. 今天我将为开发人员带来几款最好的PHP框架,希望能对你有用. 1.Agavi Agavi是一款强大的,可扩展 ...

  6. phpstorm10.0.1和webstorm11注册

    webstorm11 for win 注册时选择“License server”输入“http://15.idea.lanyus.com/”点击“OK” phpstorm10.0.1 for win ...

  7. acdream 1686 梦醒(时钟重合)

    Problem Description 娜娜离开了这个王国,走向远方,在旷野上,娜娜看到了一个大时钟,上面的时针分针秒针都在缓缓转动,那只挥着翅膀的天使又出现了,天使说:“外面天已经亮了,娜娜你别睡过 ...

  8. HDU 1496 Train Problem I 火车问题1(桟,水)

    题意: 给出两个串,串中的数字i 代表编号为i的火车进入车站的顺序,车站如桟一样,先进后出.第二个串是火车出站的顺序,问若按照第一个串那样进站,是否有可能如第二个串一样的出站顺序?火车顶多9辆,即1- ...

  9. HDU5463 Clarke and minecraft

    解题思路:此题刚开始,觉得好繁琐,好混乱,理清思路后,发现很简单.   具体见代码分析. #include<cstdio> #include<cstring> #include ...

  10. ORACLE CONTROL FILE 笔记

    控制文件包含的信息:   1.数据库的名字   2.联机重做日志文件和数据文件的名字和位置   3.数据库创建的时间戳   4.当前日志的序列号   5.检查点信息   6.备份信息   TIP:数据 ...