nhibernate, mapping attributes and spring.net LocalSessionFactoryObject

Wanted to use nhibernate with spring.net. Also wanted to annotate my entities with nhibernate attributes. But there was no LocalSessionFactoryObject that could understand mapping attributes. The class below understands attributes.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections;
using NHibernate.Mapping.Attributes;
using NHibernate.Cfg;
using NHibernate.Util;

namespace Spring.Data.NHibernate
{
///
/// Local session factory object implementation that understands
/// nhibernate attributed classes.
///

public class AnnotatedLocalSessionFactoryObject : LocalSessionFactoryObject
{
///
/// List of annotated classes that should be scanned for nhibernate attribute information.
/// The type and assembly should be listed for each entry.
///

public virtual ArrayList AnnotatedClasses { get; set; }

///
/// Whether the schemas are validated after serialization. The default is true.
///

public virtual bool ValidateAnnotatedClasses { get; set; }

public AnnotatedLocalSessionFactoryObject()
{
ValidateAnnotatedClasses = true;
}

///
/// Set the HbmDefaultAccess parameter e.g. field.camelcase
///

public virtual string DefaultAccess { get; set; }

///
/// Set the HbmDefaultLazy parameter true or false.
///

public virtual bool? DefaultLazy { get; set; }

///
/// Set the HbmDefaultNampsace parameter.
///

public virtual string DefaultNamespace { get; set; }

///
/// Set the HbmDefaultSchema parameter.
///

public virtual string DefaultSchema { get; set; }

///
/// Assembly to include
///

public virtual string Assembly { get; set; }

///
/// Add support for nhibernate attributes.
///

///
protected override void PostProcessConfiguration(Configuration cfg)
{
var s = new HbmSerializer();

s.Validate = ValidateAnnotatedClasses;

if (Assembly != null)
{
s.HbmAssembly = Assembly;
s.HbmAssemblyIsSpecified = true;
}

if (DefaultSchema != null)
{
s.HbmSchema = DefaultSchema;
s.HbmSchemaIsSpecified = true;
}

if (DefaultNamespace != null)
{
s.HbmNamespace = DefaultNamespace;
s.HbmNamespaceIsSpecified = true;
}

if (DefaultAccess != null)
{
s.HbmDefaultAccess = DefaultAccess;
s.HbmDefaultAccessIsSpecified = true;
}

if (DefaultLazy.HasValue)
{
s.HbmDefaultLazy = (bool)DefaultLazy.Value;
s.HbmDefaultLazyIsSpecified = true;
}

if (AnnotatedClasses != null)
{
foreach (string ac in AnnotatedClasses)
{
var t = ReflectHelper.ClassForName(ac);
var stream = s.Serialize(t);
if (stream != null)
{
stream.Position = 0;
try
{
cfg.AddInputStream(stream);
}
catch (Exception e)
{
log.Error("Could not add input stream from HBM serialized data", e);
throw e;
}
}
}
}
}
}
}

Comments

Popular posts from this blog

quick note on scala.js, react hooks, monix, auth

zio environment and modules pattern: zio, scala.js, react, query management

user experience, scala.js, cats-effect, IO