NHibernate Tips - composite-id behaviors different after 1.0
Just encountered this problem. in previous projects when using a composite-id tag to map a table with composite keys, it's just as simple as to write the mapping with key-property tag for the keys in table. after starting using 1.0 release, it's now different. there will be error message said:
composite-id class must override Equals()
A search to Google got some information about this.
if one just ignores composite primary keys in the table and mapping one of the composite keys in the mapping file as primary key, the returning objects after query will be missing data with the same primary key specified in mapping file and only return one of them, means it will group the data with the primary key specified in mapping file and return only one row.
Seems now if one is going to map a composite-id , the composite-id keys must self-form to a component that implements Serializable, Equals(), and HashCode() to self-identify itself as a key. as showing in articles here , here , and here .
Sounds like not very convenient to map a composite-primary-keys-table to object now, even just for retriving data out of database. to fast workaround this. just came out a quick way to avoid using a composite-id mapping.
Using a view to form the primary key field which containing the string of those composite primary keys with seperator. for example, if the composite primary keys are field1 and field2 , just create a view with all the fields of original table plus a field, namely like "PKey", which contains concat of field1 + "_" + field2 , that can uniquely identify a row in the view, just like what a composite primary keys did. for a quick mapping of how to write sql in different database server to concat string of different fields, check out this article.
by using this quick workaround, the mapping file back to the simple form, just have a id tag with the PKey field as primary key, and the objects back from HQL query go normal just as expected.
This quick workaround should only be ok for doing functions that just retrive data out from a data store to map to the domain objects. this should not be a good way for mapping data that need writing data back to the data store. be cautious about this!
Technorati Tags: hibernate , nhibernate , orm , database , programming