Created
July 7, 2015 08:44
-
-
Save RhysC/02e9396b6d7da57d1c11 to your computer and use it in GitHub Desktop.
NHibernate basics
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!-- enure this is copy always if you are going to use it --> | |
<?xml version="1.0" encoding="UTF-8"?> | |
<hibernate-configuration xmlns="urn:nhibernate-configuration-2.2"> | |
<session-factory name="NHibernate.Test"> | |
<property name="connection.driver_class">NHibernate.Driver.SQLite20Driver</property> | |
<property name="connection.connection_string">Data Source=test.db;Version=3;New=True</property> | |
<property name="dialect">NHibernate.Dialect.SQLiteDialect</property> | |
<property name="show_sql">true</property> | |
</session-factory> | |
</hibernate-configuration> |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.Collections.Generic; | |
using System.Data; | |
using System.Linq; | |
using System.Reflection; | |
using Autofac; | |
using NHibernate; | |
using NHibernate.Cfg; | |
using NHibernate.Connection; | |
using NHibernate.Dialect; | |
using NHibernate.Driver; | |
using NHibernate.Mapping.ByCode; | |
namespace NHibernateSpike | |
{ | |
public class SqliteInMemoryNHibernateModule : Autofac.Module | |
{ | |
// inspired by - http://gergroen.blogspot.com.au/2011/11/nhibernate-getting-started-guide.html | |
protected override void Load(ContainerBuilder builder) | |
{ | |
var modelMapper = new ModelMapper(); | |
modelMapper.AfterMapProperty += (inspector, member, customizer) => | |
{ | |
if (member.LocalMember.GetPropertyOrFieldType() == typeof(DateTime)) | |
{ | |
customizer.Type(NHibernateUtil.DateTime); | |
} | |
if (member.LocalMember.GetPropertyOrFieldType() == typeof(DateTime?)) | |
{ | |
customizer.Type(NHibernateUtil.DateTime); | |
} | |
}; | |
var domainAssembly = typeof(PersonMap).Assembly; | |
var mappers = NHibenateExtensions.GetMappingTypes(domainAssembly); | |
modelMapper.AddMappings(mappers); | |
var mapping = modelMapper.CompileMappingForAllExplicitlyAddedEntities(); | |
var configuration = new Configuration(); | |
ConfigureUsingHardCodedSqliteConfig(configuration); | |
configuration.AddMapping(mapping); | |
builder.RegisterInstance(configuration).AsSelf(); | |
builder.RegisterInstance(configuration.BuildSessionFactory()) | |
.As<ISessionFactory>(); | |
builder.Register(c => c.Resolve<ISessionFactory>().OpenSession()) | |
.As<ISession>() | |
.InstancePerDependency(); | |
builder.RegisterAssemblyTypes(GetType().Assembly) | |
.AsImplementedInterfaces() | |
.InstancePerLifetimeScope(); | |
} | |
private static void ConfigureUsingHardCodedSqliteConfig(Configuration configuration) | |
{ | |
configuration.DataBaseIntegration(db => | |
{ | |
db.ConnectionProvider<DriverConnectionProvider>(); | |
db.Dialect<SQLiteDialect>(); | |
db.Driver<SQLite20Driver>(); | |
db.KeywordsAutoImport = Hbm2DDLKeyWords.AutoQuote; | |
db.IsolationLevel = IsolationLevel.ReadCommitted; | |
db.ConnectionString = "data source=:memory:"; | |
db.Timeout = 10; | |
db.BatchSize = 20; | |
db.ConnectionReleaseMode = ConnectionReleaseMode.OnClose; | |
db.LogSqlInConsole = true; | |
}); | |
} | |
} | |
public class SqliteFileStorageNHibernateModule : Autofac.Module | |
{ | |
// inspired by - http://gergroen.blogspot.com.au/2011/11/nhibernate-getting-started-guide.html | |
protected override void Load(ContainerBuilder builder) | |
{ | |
var modelMapper = new ModelMapper(); | |
modelMapper.AfterMapProperty += (inspector, member, customizer) => | |
{ | |
if (member.LocalMember.GetPropertyOrFieldType() == typeof(DateTime)) | |
{ | |
customizer.Type(NHibernateUtil.DateTime); | |
} | |
if (member.LocalMember.GetPropertyOrFieldType() == typeof(DateTime?)) | |
{ | |
customizer.Type(NHibernateUtil.DateTime); | |
} | |
}; | |
var domainAssembly = typeof(PersonMap).Assembly; | |
var mappers = NHibenateExtensions.GetMappingTypes(domainAssembly); | |
modelMapper.AddMappings(mappers); | |
var mapping = modelMapper.CompileMappingForAllExplicitlyAddedEntities(); | |
var configuration = new Configuration(); | |
ConfigureUsingHardCodedSqliteConfig(configuration); | |
configuration.AddMapping(mapping); | |
builder.RegisterInstance(configuration).AsSelf(); | |
builder.RegisterInstance(configuration.BuildSessionFactory()) | |
.As<ISessionFactory>(); | |
builder.Register(c => c.Resolve<ISessionFactory>().OpenSession()) | |
.As<ISession>() | |
.InstancePerLifetimeScope(); | |
builder.RegisterAssemblyTypes(GetType().Assembly) | |
.AsImplementedInterfaces() | |
.InstancePerLifetimeScope(); | |
} | |
private static void ConfigureUsingHardCodedSqliteConfig(Configuration configuration) | |
{ | |
configuration.DataBaseIntegration(db => | |
{ | |
db.ConnectionProvider<DriverConnectionProvider>(); | |
db.Dialect<SQLiteDialect>(); | |
db.Driver<SQLite20Driver>(); | |
db.KeywordsAutoImport = Hbm2DDLKeyWords.AutoQuote; | |
db.IsolationLevel = IsolationLevel.ReadCommitted; | |
db.ConnectionString = "Data Source=test.db;Version=3;New=True"; | |
db.Timeout = 10; | |
db.BatchSize = 20; | |
db.ConnectionReleaseMode = ConnectionReleaseMode.OnClose; | |
db.LogSqlInConsole = true; | |
}); | |
} | |
} | |
public class MsSqliteNHibernateModule : Autofac.Module | |
{ | |
private readonly string _connectionString; | |
public MsSqliteNHibernateModule(string connectionString) | |
{ | |
_connectionString = connectionString; | |
} | |
// inspired by - http://gergroen.blogspot.com.au/2011/11/nhibernate-getting-started-guide.html | |
protected override void Load(ContainerBuilder builder) | |
{ | |
var modelMapper = new ModelMapper(); | |
var domainAssembly = typeof(PersonMap).Assembly; | |
var mappers = NHibenateExtensions.GetMappingTypes(domainAssembly); | |
modelMapper.AddMappings(mappers); | |
var mapping = modelMapper.CompileMappingForAllExplicitlyAddedEntities(); | |
var configuration = new Configuration(); | |
//Loads properties from hibernate.cfg.xml | |
//ConfigureUsingCfgFile(configuration); | |
//or in code using sql | |
ConfigUsingHardCodedMsSqlConfig(configuration); | |
configuration.AddMapping(mapping); | |
builder.RegisterInstance(configuration).AsSelf(); | |
builder.RegisterInstance(configuration.BuildSessionFactory()) | |
.As<ISessionFactory>(); | |
builder.Register(c => c.Resolve<ISessionFactory>().OpenSession()) | |
.As<ISession>() | |
.InstancePerLifetimeScope(); | |
builder.RegisterAssemblyTypes(GetType().Assembly) | |
.AsImplementedInterfaces() | |
.InstancePerLifetimeScope(); | |
} | |
private void ConfigUsingHardCodedMsSqlConfig(Configuration configuration) | |
{ | |
configuration.DataBaseIntegration(db => | |
{ | |
db.ConnectionProvider<DriverConnectionProvider>(); | |
db.Dialect<MsSql2012Dialect>(); | |
db.Driver<Sql2008ClientDriver>(); | |
db.KeywordsAutoImport = Hbm2DDLKeyWords.AutoQuote; | |
db.IsolationLevel = IsolationLevel.Serializable; | |
db.ConnectionString = _connectionString; | |
db.Timeout = 10; | |
db.BatchSize = 20; | |
}); | |
} | |
private static void ConfigureUsingCfgFile(Configuration configuration) | |
{ | |
//Loads properties from hibernate.cfg.xml (remember to copy ouput to bin!) | |
configuration.Configure(); | |
} | |
} | |
public class NHibenateExtensions | |
{ | |
public static IEnumerable<Type> GetMappingTypes(Assembly domainAssembly) | |
{ | |
var mappers = domainAssembly.GetTypes() | |
.Where(t => !t.IsAbstract) | |
.Where( | |
t => t.GetInterfaces().Any(i => i.IsGenericType && i.GetGenericTypeDefinition() == typeof(IClassMapper<>))); | |
var subclassMappers = domainAssembly.GetTypes() | |
.Where(t => !t.IsAbstract) | |
.Where( | |
t => | |
t.GetInterfaces() | |
.Any(i => i.IsGenericType && i.GetGenericTypeDefinition() == typeof(ISubclassMapper<>))); | |
return mappers.Union(subclassMappers); | |
} | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using Autofac; | |
using NHibernate; | |
using NHibernate.Cfg; | |
using NHibernate.Tool.hbm2ddl; | |
using NUnit.Framework; | |
namespace NHibernateSpike.Tests | |
{ | |
[TestFixture] | |
public class NHibernatePersonTest | |
{ | |
private ISession _session; | |
[SetUp] | |
public void CreateSchema() | |
{ | |
var builder = new ContainerBuilder(); | |
builder.RegisterModule<SqliteInMemoryNHibernateModule>(); | |
var container = builder.Build(); | |
var configuration = container.Resolve<Configuration>(); | |
_session = container.Resolve<ISession>(); | |
new SchemaExport(configuration).Execute( | |
useStdOut: false, | |
execute: true, | |
justDrop: false, | |
connection: _session.Connection, | |
exportOutput: null //Console.Out | |
); | |
} | |
[Test] | |
public void CanSavePerson() | |
{ | |
using (var transaction = _session.BeginTransaction()) | |
{ | |
_session.Save(new Person()); | |
transaction.Commit(); | |
} | |
Assert.AreEqual(1, _session.QueryOver<Person>().RowCountInt64()); | |
} | |
[Test] | |
public void CanGetPerson() | |
{ | |
var person = new Person(); | |
using (var transaction = _session.BeginTransaction()) | |
{ | |
_session.Save(person); | |
transaction.Commit(); | |
} | |
var person2 = _session.Get<Person>(person.Id); | |
Assert.AreSame(person, person2); | |
} | |
[Test] | |
public void CanUpdatePerson() | |
{ | |
var person = new Person(); | |
using (var transaction = _session.BeginTransaction()) | |
{ | |
_session.Save(person); | |
transaction.Commit(); | |
} | |
var person2 = _session.Get<Person>(person.Id); ; | |
person2.FirstName = "Test"; | |
using (var transaction = _session.BeginTransaction()) | |
{ | |
_session.Update(person2); | |
transaction.Commit(); | |
} | |
Assert.AreEqual(1, _session.QueryOver<Person>().RowCountInt64()); | |
Assert.AreEqual("Test", _session.Get<Person>(person.Id).FirstName); | |
} | |
[Test] | |
public void CanDeletePerson() | |
{ | |
var person = new Person(); | |
using (var transaction = _session.BeginTransaction()) | |
{ | |
_session.Save(person); | |
transaction.Commit(); | |
} | |
Assert.AreEqual(1, _session.QueryOver<Person>().RowCountInt64()); | |
using (var transaction = _session.BeginTransaction()) | |
{ | |
_session.Delete(person); | |
transaction.Commit(); | |
} | |
Assert.AreEqual(0, _session.QueryOver<Person>().RowCountInt64()); | |
} | |
[TearDown] | |
public void DeleteDatabaseIfExists() | |
{ | |
_session.Flush(); | |
_session.Clear(); | |
_session.Dispose(); | |
} | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?xml version="1.0" encoding="utf-8"?> | |
<packages> | |
<package id="Autofac" version="3.5.2" targetFramework="net451" /> | |
<package id="Iesi.Collections" version="4.0.0.4000" targetFramework="net451" /> | |
<package id="NHibernate" version="4.0.3.4000" targetFramework="net451" /> | |
<package id="NUnit" version="2.6.4" targetFramework="net451" /> | |
<package id="System.Data.SQLite.Core" version="1.0.97.0" targetFramework="net451" /> | |
</packages> |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using NHibernate.Mapping.ByCode; | |
using NHibernate.Mapping.ByCode.Conformist; | |
namespace NHibernateSpike | |
{ | |
public class Person | |
{ | |
public virtual Guid Id { get; set; } | |
public virtual string FirstName { get; set; } | |
public virtual string LastName { get; set; } | |
public virtual string GetFullName() | |
{ | |
return string.Format("{0} {1}", FirstName, LastName); | |
} | |
} | |
public class PersonMap : ClassMapping<Person> | |
{ | |
public PersonMap() | |
{ | |
Id(x => x.Id, m => m.Generator(Generators.GuidComb)); | |
Property(x => x.FirstName); | |
Property(x => x.LastName); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment