There are cases where a set of properties are used repeatedly. These properties may even have their own business logic, but they don't represent an entity in your application. They are value objects. In this recipe, I'll show you how we can separate these properties and business logic into a component class without creating a separate entity.
ComponentExamples
.Address
class with the following properties:public virtual string Lines { get; set; } public virtual string City { get; set; } public virtual string State { get; set; } public virtual string ZipCode { get; set; }
customer
class with the following properties:public virtual string Name { get; set; } public virtual Address BillingAddress { get; set; } public virtual Address ShippingAddress { get; set; }
<?xml version="1.0" encoding="utf-8" ?> <hibernate-mapping xmlns="urn:nhibernate-mapping-2.2" assembly="ComponentExamples" namespace="ComponentExamples"> <class name="Customer"> <id name="Id"> <generator class="guid.comb" /> </id> <property name="Name" not-null="true" /> <component name="BillingAddress" class="Address"> <property name="Lines" not-null="true" /> <property name="City" not-null="true" /> <property name="State" not-null="true" /> <property name ="ZipCode" not-null="true" /> </component> <component name="ShippingAddress" class="Address"> <property name="Lines" not-null="true" column="ShippingLines" /> <property name="City" not-null="true" column="ShippingCity" /> <property name="State" not-null="true" column="ShippingState" /> <property name ="ZipCode" not-null="true" column="ShippingZipCode" /> </component> </class> </hibernate-mapping>
In this recipe, we can use the Address
component class throughout our model without the overhead of maintaining a separate entity. We've used it in our Customer
class for both billing and shipping address. The resulting database table will appear as shown in the next screenshot:
Our model looks like this:
We get all the reuse benefits without the database work. The Address fields are included in every query for Customer, and are automatically loaded.