Is it possible to map a database column to a constant value without the need for a property in the entity class? This basically is a workaround for a missing default value on that column in the database in combination with a NOT NULL constrained. The database is external and can't be changed but I don't need all of the columns in that table and thus don't want to have corresponding properties in my entity class.
I am asking basically the same as described in this Hibernate JIRA issue.
If you don't want to introduce property in your entity class the only solution I see is to create custom property accessor which will always return constant value. Here is possible implementation:
Here how to use it:
Property "Value" doesn't need to exist in your entity. It is here because attribute "name" is required.
My implementation takes the same idea as hival but goes a lot further. the basis is an implementation of IPropertyAccessor
Based on Firos answer I solved the problem. However, I didn't quite like the syntax to be used and the fact that I would have to create a new class for the default values for each entity.
The syntax I got now looks like this:
I created the following extension methods for it:
The important differences are:
The first of those extension methods returns a
PropertyPart
and has to be used in conjunction with theColumn
method to specify which column the constant value should be mapped to. Because of this, the column name is not known when the extension method is executed and we need to create one ourselves. This is done byCreateUniqueMemberName
:Because you can only specify a type as access strategy and not an instance, I couldn't create an
IPropertyAccessor
implementation allowed me to simply pass anIGetter
instance in the constructor. That's whatConstantValueAccessor.RegisterGetter(typeof(TType), getter);
solves.ConstantValueAccessor
has a static collection of getters:The implementation of
ConstantValueGetter<T>
is the same as the one from the provided link.Because it wasn't that much fun to implement
GetterSetterPropertyInfo
, here it is. One important difference is, that this implementation doesn't have any dependencies on (Fluent) NHibernate.