How to tell castor to marshall a null field to an empty tag? - marshalling

I'm marshalling an object that can have some field set to null. I'm using castor with a xml-mapping file for the configuration. The class I'm marshalling is like this:
class Entity {
private int id;
private String name;
private String description; // THIS CAN BE NULL
/* ... getters and setters follow ... */
}
...and a mapping file like this:
<mapping>
<class name="Entity">
<field name="id" type="integer"/>
<field name="name" type="string"/>
<field name="description" type="string"/>
</class>
</mapping>
What I'm getting at the moment if the field is null (simplified example):
<entity>
<id>123</id>
<name>Some Name</name>
</entity>
while I want to have an empty tag in the resulting XML, even if the description field is null.
<entity>
<id>123</id>
<name>Some Name</name>
<description /> <!-- open/close tags would be ok -->
</entity>

One way to do this is with a GeneralizedFieldHandler. It's a bit of a hack but it will work for other fields that are Strings.
Example:
<mapping>
<class name="Entity">
<field name="id" type="integer"/>
<field name="name" type="string"/>
<field name="description" type="string" handler="NullHandler"/>
</class>
</mapping>
public class NullHandler extends GeneralizedFieldHandler {
#Override
public Object convertUponGet( Object arg0 )
{
if( arg0 == null )
{
return "";
}
return arg0;
}
#Override
public Object convertUponSet( Object arg0 )
{
return arg0;
}
#Override
public Class getFieldType()
{
return String.class;
}
}

Related

NHibernate issue : persistent class not known

I have two tables Person and PassportInfo with a structure as given below:
Table Person
(
PersonID uniqueidentifier not null, (PK)
Name varchar(100) not null,
Email varchar(100) not null
)
Table PassportInfo
(
ID int identity(1,1) not null Primary Key,
personID uniqueidentifier null, (FK to PersonID in Person table)
PassportNumber varchar(100) not null
)
Also this is the mapping for Person
<?xml version="1.0" encoding="utf-8" ?>
<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2" assembly="Project" namespace="Project">
<class name="classperson" table="Person" >
<id name="ID" type="System.Guid" column="personID">
<generator class="Guid"/>
</id>
<property name="Name" column="Name" type="System.String" length="100" not-null="true" />
<property name="Email" column="Email" type="System.String" length="100" not-null="true" />
<one-to-one name="classpassportinfo" class="classpassportinfo" constrained="true" />
</class>
</hibernate-mapping>
This is the mapping for PassportInfo
<?xml version="1.0" encoding="utf-8" ?>
<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2" assembly="Project" namespace="Project">
<class name="classpassportinfo" table="PassportInfo" >
<id name="ID" type="System.Int32" column="ID">
<generator class="identity"/>
</id>
<property name="PassportNumber" column="PassportNumber" type="System.String" length="100" not-null="true" />
<one-to-one name="classperson" class="classperson" />
</class>
</hibernate-mapping>
This is the Object Class for Person
namespace Project
{
[Serializable]
public class classperson : Base<System.Guid>
{
private System.String _Name;
private System.String _Email;
private classpassportinfo _classpassportinfo;
public classperson()
{
}
public classperson(System.Guid id)
{
base.ID = id;
}
public virtual System.String Name {
get { return _Name; }
set { _Name = value;}
}
public virtual System.String Email {
get { return _Email; }
set { _Email = value;}
}
public virtual classpassportinfo classpassportinfo {
get { return _classpassportinfo; }
set { _classpassportinfo = value;}
}
}
}
Finally this is the object class for PassportInfo
namespace Project
{
[Serializable]
public class classpassportinfo :Base<Systme.Int32>
{
private System.String _PassportNumber;
private classpassportinfo _classpassportinfo;
public classpassportinfo()
{
}
public classpassportinfo(System.Int32 id)
{
base.ID = id;
}
public virtual System.String PassportNumber {
get { return _PassportNumber; }
set { _PassportNumber = value;}
}
public virtual classperson classperson {
get { return _classperson; }
set { _classperson = value;}
}
}
}
When I execute above code, i am getting and error saying persistent class not known: Project.classpassportinfo. I am new to nhibernate. Any help in this appreciated.
To elaborate and clarify #Fran's comment for anyone else struggling with this problem...
For me, in Visual Studio this issue was resolved by:
Open the solution explorer (Project structure navigator)
Locate the mapping file passportinfo.hbm.xml
Right click and choose properties
Under the advanced tab, make sure "Build Action" is set to "Embedded Resource"
The issue should be resolved now. Good luck

Cascade Save - StaleObjectStateException: Row was updated or deleted by another transaction

Having an issue with updating the NHibernate version. Current version is 3.3.1.4000 and trying to update to 4.
After updating the unit test which does save with cascade fails with:
NHibernate.StaleObjectStateException: Row was updated or deleted by another transaction (or unsaved-value mapping was incorrect): [NHibernateTests.TestMappings.ProductLine#cdcaf08d-4831-4882-84b8-14de91581d2e]
The mappings:
<?xml version="1.0" encoding="utf-8" ?>
<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2" assembly="NHibernateTests" namespace="NHibernateTests.TestMappings">
<class name="Product" lazy="false" table="UserTest">
<id name="Id">
<generator class="guid"></generator>
</id>
<version name="Version" column="Version" unsaved-value="0"/>
<property name="Name" not-null="false"></property>
<property name="IsDeleted"></property>
<bag name="ProductLines" table="ProductLine" inverse="true" cascade="all" lazy="true" where="IsDeleted=0" >
<cache usage="nonstrict-read-write" />
<key column="UserId" />
<one-to-many class="ProductLine" />
</bag>
</class>
</hibernate-mapping>
<?xml version="1.0" encoding="utf-8" ?>
<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2" assembly="NHibernateTests" namespace="NHibernateTests.TestMappings">
<class name="ProductLine" where="IsDeleted=0" lazy="false">
<cache usage="nonstrict-read-write" />
<id name="Id">
<generator class="guid"></generator>
</id>
<version name="Version" column="Version" unsaved-value="0"/>
<property name="IsDeleted"></property>
<many-to-one name="Product" class="Product" column="UserId" not-null="true" lazy="proxy"></many-to-one>
</class>
</hibernate-mapping>
Classes:
public class Product
{
public Guid Id { get; set; }
public int Version { get; set; }
public bool IsDeleted { get; set; }
public string Name { get; set; }
public bool IsActive { get; set; }
public IList<ProductLine> ProductLines { get; private set; }
public Product()
{
ProductLines = new List<ProductLine>();
}
}
public class ProductLine
{
public Guid Id { get; set; }
public int Version { get; set; }
public bool IsDeleted { get; set; }
public Product Product { get; set; }
}
The test:
[TestMethod]
public void CascadeSaveTest()
{
var product = new Product
{
Id = Guid.NewGuid(),
Name = "aaa",
IsActive = true
};
var productLine = new ProductLine
{
Id = Guid.NewGuid(),
Product = product,
};
product.ProductLines.Add(productLine);
using (var connection = new RepositoryConnection())
{
using (var repositories = new Repository<Product>(connection))
{
repositories.Create(product);
//the below just calls the Session.Transaction.Commit();
connection.Commit(); //NH3.3.1.400 passes, NH4 fails
}
}
}
Thanks for you ideas in advance.
Well, I guess I have now understood what causes the error with NH 4. And If I am right, that is a bit contrived case causing this behavior to be hard to qualify as a bug.
In your example, products lines are mapped through a bag. A bag can contains duplicates, which requires an intermediate table between Product and ProductLine. (Something like a ProductProductLine table with an UserId (ProductId) column, and a ProductLineId column.)
You have set this intermediate table as being the ProductLine table. I suspect the commit to db causes NHibernate to insert the product, then the product line, then to try to insert the relationship by inserting again in ProductLine table. (You may check that by profiling SQL queries on your db.)
Things are a bit muddy, since doc states (emphasis is mine):
table (optional - defaults to property name) the name of the
collection table (not used for one-to-many associations)
But then, how to honor the bag semantics allowing duplicates in the collection? From the same doc:
A bag is an unordered, unindexed collection which may contain the same
element multiple times.
Anyway, within your example, you really should map your one-to-many with a set, as shown in doc.
<?xml version="1.0" encoding="utf-8" ?>
<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2" assembly="NHibernateTests" namespace="NHibernateTests.TestMappings">
<class name="Product" lazy="false" table="UserTest">
<id name="Id">
<generator class="guid"></generator>
</id>
<version name="Version" column="Version" unsaved-value="0"/>
<property name="Name" not-null="false"></property>
<property name="IsDeleted"></property>
<set name="ProductLines" inverse="true" cascade="all" lazy="true" where="IsDeleted=0" >
<cache usage="nonstrict-read-write" />
<key column="UserId" />
<one-to-many class="ProductLine" />
</set>
</class>
</hibernate-mapping>
And change your collection type for using .Net fx 4 System.Collections.Generic.ISet<T>.
public ISet<ProductLine> ProductLines { get; private set; }
public Product()
{
ProductLines = new HashSet<ProductLine>();
}
If this causes your trouble to disappear, it would mean something has changed in bag handling in NH 4. But should we consider this change as being a bug? Not sure, since using a bag in this case does not look right for me.
Drilling it further down turned out that NHibernate4 has problems identifying whether it is a new entity or an already existent when concerned with Cascade.
With the scenario in question it was calling a SQL Update for the ProductLine, rather than Create.
It works fine with the below changes, however I'm quite puzzled with such a changes in between NHibernate versions.
Change to ProductLine Mapping
<?xml version="1.0" encoding="utf-8" ?>
<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2" assembly="NHibernateTests" namespace="NHibernateTests.TestMappings">
<class name="ProductLine" where="IsDeleted=0" lazy="false">
<cache usage="nonstrict-read-write" />
<!-- here comes the updated line -->
<id name="Id" type="guid" unsaved-value="00000000-0000-0000-0000-000000000000">
<generator class="guid"></generator>
</id>
<version name="Version" column="Version" unsaved-value="0"/>
<property name="IsDeleted"></property>
<many-to-one name="Product" class="Product" column="UserId" not-null="true" lazy="proxy"></many-to-one>
</class>
</hibernate-mapping>
Change to test method
[TestMethod]
public void CascadeSaveTest()
{
var product = new Product
{
Id = Guid.NewGuid(),
Name = "aaa",
IsActive = true
};
var productLine = new ProductLine
{
Id = Guid.Empty, //The updated line
Product = product,
};
product.ProductLines.Add(productLine);
using (var connection = new RepositoryConnection())
{
using (var repositories = new Repository<Product>(connection))
{
repositories.Create(product);
connection.Commit();
}
}
}

Fluent NHibernate - joined subclass ForeignKey Name

I am looking at moving to Fluent NHibernate - the only issue I have encounter so far is that you can not specify a foreign key name on a joined sub class mapping.
Has anyone got a solution for this, or a workaround?
I found this post but the suggestion clearly was not added to the code.
I would like to avoid customising the code myself if possible.
Any help would be great...
Example:
public class Product
{
public string Name { get; set; }
}
public class Hammer : Product
{
public string Description { get; set; }
}
public class ProductMap : ClassMap<Product, long>
{
public ProductMap()
{
Polymorphism.Implicit();
Map(x => x.Name);
}
}
public class HammerMap : SubclassMap<Hammer>
{
public HammerMap()
{
Extends<Product>();
}
}
This generates something like:
<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2" default-access="field.camelcase-underscore" auto-import="false" default-cascade="none" default-lazy="true">
<class xmlns="urn:nhibernate-mapping-2.2" dynamic-insert="true" dynamic-update="true" mutable="true" polymorphism="implicit" optimistic-lock="version" name="Domain.Product, Domain" table="Product">
<id name="Id" type="System.Int64">
<column name="Id" />
<generator class="native">
<param name="sequence">ProductId</param>
</generator>
</id>
<property name="Name" type="System.String">
<column name="Name" />
</property>
<joined-subclass name="Domain.Hammer, Domain" table="Hammer">
<key>
<column name="Product_Id" />
</key>
<property name="Description" type="System.String">
<column name="Description" />
</property>
</joined-subclass>
</class>
</hibernate-mapping>
Note that there is no foreign key name specified in the mapping hbm file - as in:
<joined-subclass name="Domain.Hammer, Domain" table="Hammer">
<key column="Product_Id" foreign-key="FK_Hammer_Product"/>
</joined-subclass>
Try something like this
public class JoinedSubclassForeignKeyConvention : IJoinedSubclassConvention
{
public void Apply(IJoinedSubclassInstance instance)
{
instance.Key.ForeignKey(string.Format("FK_{0}_{1}",
instance.EntityType.Name, instance.Type.Name));
}
}

Doubly connected ordered tree mapping using NHibernate

We need to map simple class using NHibernate:
public class CatalogItem
{
private IList<CatalogItem> children = new List<CatalogItem>();
public Guid Id { get; set; }
public string Name { get; set; }
public CatalogItem Parent { get; set; }
public IList<CatalogItem> Children
{
get { return children; }
}
public bool IsRoot { get { return Parent == null; } }
public bool IsLeaf { get { return Children.Count == 0; } }
}
There are a batch of tutorials in the internet on this subject, but none of them cover little nasty detail: we need order to be preserved in Children collection. We've tried following mapping, but it led to strange exeptions thrown by NHibernate ("Non-static method requires a target.").
<?xml version="1.0" encoding="utf-8" ?>
<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2" namespace="Domain.Model" assembly="Domain">
<class name="CatalogItem" lazy="false">
<id name="Id" type="guid">
<generator class="guid" />
</id>
<property name="Name" />
<many-to-one name="Parent" class="CatalogItem" lazy="false" />
<list name="Children" cascade="all">
<key property-ref="Parent"/>
<index column="weight" type="Int32" />
<one-to-many not-found="exception" class="CatalogItem"/>
</list>
</class>
</hibernate-mapping>
Does anyone have any thoughts?
I'm no expert, but <key property-ref=...> looks strange to me in this usage. You should be able to do <key column="ParentID"/>, and NHibernate will automatically use the primary key of the associated class -- itself, in this case.
You may also need to set the list to inverse="true", since the relationship is bidirectional. [See section 6.8 in the docs.]

Inheritance Mapping with Fluent NHibernate

Given the following scenario, I want map the type hierarchy to the database schema using Fluent NHibernate.
I am using NHibernate 2.0
Type Hierarchy
public abstract class Item
{
public virtual int ItemId { get; set; }
public virtual string ItemType { get; set; }
public virtual string FieldA { get; set; }
}
public abstract class SubItem : Item
{
public virtual string FieldB { get; set; }
}
public class ConcreteItemX : SubItem
{
public virtual string FieldC { get; set; }
}
public class ConcreteItemY : Item
{
public virtual string FieldD { get; set; }
}
See image
The Item and SubItem classes are abstract.
Database Schema
+----------+ +---------------+ +---------------+
| Item | | ConcreteItemX | | ConcreteItemY |
+==========+ +===============+ +===============+
| ItemId | | ItemId | | ItemId |
| ItemType | | FieldC | | FieldD |
| FieldA | +---------------+ +---------------+
| FieldB |
+----------+
See image
The ItemType field determines the concrete type.
Each record in the ConcreteItemX table has a single corresponding record in the Item table; likewise for the ConcreteItemY table.
FieldB is always null if the item type is ConcreteItemY.
The Mapping (so far)
public class ItemMap : ClassMap<Item>
{
public ItemMap()
{
WithTable("Item");
Id(x => x.ItemId, "ItemId");
Map(x => x.FieldA, "FieldA");
JoinedSubClass<ConcreteItemX>("ItemId", MapConcreteItemX);
JoinedSubClass<ConcreteItemY>("ItemId", MapConcreteItemY);
}
private static void MapConcreteItemX(JoinedSubClassPart<ConcreteItemX> part)
{
part.WithTableName("ConcreteItemX");
part.Map(x => x.FieldC, "FieldC");
}
private static void MapConcreteItemY(JoinedSubClassPart<ConcreteItemY> part)
{
part.WithTableName("ConcreteItemX");
part.Map(x => x.FieldD, "FieldD");
}
}
FieldB is not mapped.
The Question
How do I map the FieldB property of the SubItem class using Fluent NHibernate?
Is there any way I can leverage DiscriminateSubClassesOnColumn using the ItemType field?
Addendum
I am able to achieve the desired result using an hbm.xml file:
<class name="Item" table="Item">
<id name="ItemId" type="Int32" column="ItemId">
<generator class="native"/>
</id>
<discriminator column="ItemType" type="string"/>
<property name="FieldA" column="FieldA"/>
<subclass name="ConcreteItemX" discriminator-value="ConcreteItemX">
<!-- Note the FieldB mapping here -->
<property name="FieldB" column="FieldB"/>
<join table="ConcreteItemX">
<key column="ItemId"/>
<property name="FieldC" column="FieldC"/>
</join>
</subclass>
<subclass name="ConcreteItemY" discriminator-value="ConcreteItemY">
<join table="ConcreteItemY">
<key column="ItemId"/>
<property name="FieldD" column="FieldD"/>
</join>
</subclass>
</class>
How do I accomplish the above mapping using Fluent NHibernate?
Is it possible to mix table-per-class-hierarchy with table-per-subclass using Fluent NHibernate?
I know this is really old, but it is now pretty simple to set up fluent to generate the exact mapping you initially desired. Since I came across this post when searching for the answer, I thought I'd post it.
You just create your ClassMap for the base class without any reference to your subclasses:
public class ItemMap : ClassMap<Item>
{
public ItemMap()
{
this.Table("Item");
this.DiscriminateSubClassesOnColumn("ItemType");
this.Id(x => x.ItemId, "ItemId");
this.Map(x => x.FieldA, "FieldA");
}
}
Then map your abstract subclass like this:
public class SubItemMap: SubclassMap<SubItemMap>
{
public SubItemMap()
{
this.Map(x => x.FieldB);
}
}
Then map your concrete subclasses like so:
public class ConcreteItemXMap : SubclassMap<ConcreteItemX>
{
public ConcretItemXMap()
{
this.Join("ConcreteItemX", x =>
{
x.KeyColumn("ItemID");
x.Map("FieldC")
});
}
}
Hopefully this helps somebody else looking for this type of mapping with fluent.
Well, I'm not sure that it's quite right, but it might work... If anyone can do this more cleanly, I'd love to see it (seriously, I would; this is an interesting problem).
Using the exact class definitions you gave, here are the mappings:
public class ItemMap : ClassMap<Item>
{
public ItemMap()
{
Id(x => x.ItemId);
Map(x => x.ItemType);
Map(x => x.FieldA);
AddPart(new ConcreteItemYMap());
}
}
public class SubItemMap : ClassMap<SubItem>
{
public SubItemMap()
{
WithTable("Item");
// Get the base map and "inherit" the mapping parts
ItemMap baseMap = new ItemMap();
foreach (IMappingPart part in baseMap.Parts)
{
// Skip any sub class parts... yes this is ugly
// Side note to anyone reading this that might know:
// Can you use GetType().IsSubClassOf($GenericClass$)
// without actually specifying the generic argument such
// that it will return true for all subclasses, regardless
// of the generic type?
if (part.GetType().BaseType.Name == "JoinedSubClassPart`1")
continue;
AddPart(part);
}
Map(x => x.FieldB);
AddPart(new ConcreteItemXMap());
}
}
public class ConcreteItemXMap : JoinedSubClassPart<ConcreteItemX>
{
public ConcreteItemXMap()
: base("ItemId")
{
WithTableName("ConcreteItemX");
Map(x => x.FieldC);
}
}
public class ConcreteItemYMap : JoinedSubClassPart<ConcreteItemY>
{
public ConcreteItemYMap()
: base("ItemId")
{
WithTableName("ConcreteItemY");
Map(x => x.FieldD);
}
}
Those mappings produce two hbm.xml files like so (some extraneous data removed for clarity):
<class name="Item" table="`Item`">
<id name="ItemId" column="ItemId" type="Int32">
<generator class="identity" />
</id>
<property name="FieldA" type="String">
<column name="FieldA" />
</property>
<property name="ItemType" type="String">
<column name="ItemType" />
</property>
<joined-subclass name="ConcreteItemY" table="ConcreteItemY">
<key column="ItemId" />
<property name="FieldD">
<column name="FieldD" />
</property>
</joined-subclass>
</class>
<class name="SubItem" table="Item">
<id name="ItemId" column="ItemId" type="Int32">
<generator class="identity" />
</id>
<property name="FieldB" type="String">
<column name="FieldB" />
</property>
<property name="ItemType" type="String">
<column name="ItemType" />
</property>
<property name="FieldA" type="String">
<column name="FieldA" />
</property>
<joined-subclass name="ConcreteItemX" table="ConcreteItemX">
<key column="ItemId" />
<property name="FieldC">
<column name="FieldC" />
</property>
</joined-subclass>
</class>
It's ugly, but it looks like it might generate a usable mapping file and it's Fluent! :/
You might be able to tweak the idea some more to get exactly what you want.
This is how I resolved my inheritance problem:
public static class DataObjectBaseExtension
{
public static void DefaultMap<T>(this ClassMap<T> DDL) where T : IUserAuditable
{
DDL.Map(p => p.AddedUser).Column("AddedUser");
DDL.Map(p => p.UpdatedUser).Column("UpdatedUser");
}
}
You can then add this to your superclass map constructor:
internal class PatientMap : ClassMap<Patient>
{
public PatientMap()
{
Id(p => p.GUID).Column("GUID");
Map(p => p.LocalIdentifier).Not.Nullable();
Map(p => p.DateOfBirth).Not.Nullable();
References(p => p.Sex).Column("RVSexGUID");
References(p => p.Ethnicity).Column("RVEthnicityGUID");
this.DefaultMap();
}
}
The line of code: if (part.GetType().BaseType.Name == "JoinedSubClassPart1")
can be rewritten as follows:
part.GetType().BaseType.IsGenericType && part.GetType().BaseType.GetGenericTypeDefinition() == typeof(JoinedSubClassPart<>)