Using nHibern开发者_运维知识库ate 2.
In our system we have a table that stores records which may point to any of the other tables in the system, as well as some additional fields. e.g.
class PointerTable
{
public int ID;
public string ObjectName;
public int RecordID;
... additional fields
}
The ObjectName and RecordID fields point to the name of another table in the system, and the ID of the record in that table that this record points to. There are no relationships between this table and the other tables in the system.
I need to be able to join to this table when I retrieve records from the other tables in the system, as I need to determine if a table has any records in PointerTable that point to it. i.e. get the count of the records in the PointerTable for this record.
I've tried to do this in HQL:
select a.ID, e.Field1, a.Field2, a.Field3,
count(select *
from PointerTable p
where p.ObjectName = "Table1"
and p.RecordID = a.ID)
from Table1 a
where a.ParentTable.ID = :ID
I've also looked into putting a mapping into the XML configuration files for all the entities in the system which will be pointed to by this table. So I could have a collection of PointerTable records in each of my other entities. Though I'm not sure if this is possible. I can't find how to set the mapping to map on 2 fields rather than the primary key.
Something like:
<bag name="PointerRecords" table="PointerTable" lazy="true" inverse="true">
<key>
<column name="ThisEntityID" />
<column name="ObjectName" /> ?? Hard coded
</key>
<one-to-many class="PointerTable" not-found="ignore"/>
</bag>
Is this even possible?
Basically all I'm trying to do is the following SQL query. But ideally we'd like to do this through HQL or mappings.
SQL
select a.ID, e.Field1, a.Field2, a.Field3, Count(d.ID)
from Table1 a
inner join Table2 e on a.ParentID=e.ID
left outer join PointerTable d on d.ObjectName = 'Table1' and d.RecordID = a.ID
where c.ID = @ID
group by a.ID, e.Field1, a.Field2, a.Field3
the idea here would be to map this collection with a where clause
using fluentmapping:
public SomeEntityMap(){
Table("SomeTable");
HasMany(x => x.PointerRecords)
.Table("PointerTable")
.KeyColumn("ThisEntityID")
.Where("ObjectName = 'SomeTable'")
}
Begin Edit
using xml-mapping
<bag name="PointerRecords" table="PointerTable" lazy="true" inverse="true" where ="ObjectName = 'SomeTable'">
<key column="ThisEntityID"/>
<one-to-many class="PointerTable" not-found="ignore"/>
</bag>
End Edit
and query like
object[] results = session.CreateCriteria<SomeEntity>()
.Add(Restrictions.Eq("Id", id))
.SetProjection(Projections.ProjectionList()
.Add(Projections.Property("Field1"))
...
.Add(Projections.Count("PointerRecords")));
.List()
or
var entities = session.CreateCriteria<SomeEntity>()
.Add(Restrictions.Eq("Id", id)
.SetFetchMode("PointerRecords", NHibernate.FetchMode.Eager)
.List<SomeEntity>();
entities[0].PointerRecords.Count
精彩评论