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. WCF常见异常-The maximum string content length quota (8192) has been exceeded while reading XML data

    异常信息:The maximum string content length quota (8192) has been exceeded while reading XML data 问题:调用第三 ...

  2. UVa 514 (stack的使用) Rails

    练习一下stack的使用,还有要注意一下输入的格式,看了好长时间没懂. //#define LOCAL #include <iostream> #include <cstdio> ...

  3. 字符集设置为UTF-8

    vi /etc/my.cnf [mysqld] character-set-server=utf8 [mysql] default-character-set=utf8 来自为知笔记(Wiz)

  4. HDU 5339 Untitled (暴力枚举)

    题意:给定一个序列,要求从这个序列中挑出k个数字,使得n%a1%a2%a3....=0(顺序随你意).求k的最小值. 思路:排个序,从大的数开始模起,这是因为小的模完还能模大的么? 每个元素可以选,也 ...

  5. zipline

    history 多只股票时会返回某几只股票停牌没数据 if not symbol(stock) in data: 聚宽 多只股票如果某几只没有发行 600485: nan 多只股票如果某几只停牌 60 ...

  6. Dom对象的方法应用一getElementById技巧、getElementsByName() IE,firefox兼容

    在document对象中有以下三个方法,对于程序员来说,真可谓无人不知,无人不晓,他们分别是: 1.getElementById()                  返回对拥有指定 id 的第一个对 ...

  7. Asp.net动态调用WebService

    Public Class WebServiceHelper #Region "InvokeWebService" '动态调用web服务 Public Shared Function ...

  8. Cadence Allegro导网表的错误问题解决

    在Allegro导入网表的时候,有时候会出现这样一个错误问题,如下: ------ Oversights/Warnings/Errors ------ #1   ERROR(SPMHNI-235): ...

  9. PHP String函数分类

    1.查找字符位置函数: strpos  ($str,search,[int]):    查找search在$str中的第一次位置从int开始: stripos ($str,search,[int]): ...

  10. library cache lock和cursor: pin S wait on X等待

    1.现象: 客户10.2.0.4 RAC环境,出现大量的library cache lock和cursor: pin S wait on X等待,经分析是由于统计信息收集僵死导致的.数据库在8点到9点 ...