After too many hours of searching for a very clean, tight sample of Attribute-based CompositeId in NHibernate (I'd found this very clearly documented/exampled in Hibernate for Java), and a lot of headbanging (I bought the Kuate book, and though it's fine, this was not explicitly and covered in that book).
Making this work with XML-configurations is as easy as copy/pasting from dozens of examples on the web and in Kuate's book; I'm an annotations fanatic, and this was my quest.
As this snippet stands, it functions without any hbm.xml files - that was my goal all along
Hope someone finds this sample useful; I know that if I'd found a post like this one a few hours ago I'd have had a better day. I'd appreciate comments on how this could be improved.
What's in here that
I wasn't able to find clearly stated anywhere (I'm sure it's all out there somewhere in pieces, but not in one clear, concise place that I could find):
The Name-property in the CompositeId attribute is critical. Ok, ok - tell me it's obvious, but now it's also documented in a snippet that can save others who might also miss the obvious :D
it's essential to number the KeyProperty entries as shown if there's more than one KeyProperty
The class that has a UsuryPK "CompositeId" object:
Code:
namespace repo {
[Class(Name="repo.UsuryDecision, repoAPI", Table="usury_decision")]
public class UsuryDecision {
public UsuryDecision() { }
[CompositeId(Name = "PKey", Class = "repo.UsuryPK, repoAPI")]
[KeyProperty(1, Name = "Timestamp", Column = "timestamp")]
[KeyProperty(2, Name = "Id", Column = "id")]
private UsuryPK pKey;
[Property(Name = "State", Length = 3), Column(Name = "state")]
public virtual string State {<accessors elided for brevity>}
}
The PK-class (note that aside from the two KeyProperty attributes, there are no NHibernate Attribute markers)
Code:
namespace repo {
[Serializable]
public class UsuryPK{
private DateTime timestamp;
private int id;
public UsuryPK() {
}
public UsuryPK(DateTime timestamp, int id) {
this.timestamp = timestamp;
this.id = id;
}
[KeyProperty(Name="Timestamp")]
public virtual DateTime Timestamp {<accessors elided>}
[KeyProperty(Name="Id")]
public virtual int Id {<accessors elided>}
public override int GetHashCode() {<elided> }
public override bool Equals(object o) {<elided>}
}