开发者

How to map a read only property backed by a query in Hibernate

I'm wondering how to best implement a property (here, LatestRequest) which is read-only, backed by a query.

Here, I have an Export, which can be requested to happen multiple times. I'd like to have a property on the Export to get the latest ExportRequest. At the moment, I've got a many-to-one mapping with a formula, like this:

 <class name="Export" table="Exports">
   <id name="Id">
     <generator class="guid" />
   </id>
   <property name="Name" />
   <bag name="Requests" cascade="all,delete-orphan" inverse="true" access="field.camelcase" order-by="CreationDate desc">
     <key column="ExportId"/>
     <one-to-many class="ExportRequest"/>
   </bag>
   <many-to-one name="LatestRequest"
                class="ExportRequest"
                formula="(select top 1 ExportRequests.Id from ExportRequests order by ExportRequests.CreationDate desc)"/>
 </class>

 <class name="ExportRequest" table="ExportRequests">
   <id name="Id">
     <generator class="native" />
   </id>
   <many-to-one name="Export"
       class="Export"
       column="ExportId"
       not-null="true" />
   <property name="CreationDate" />
   <property name="Tag" />
 </class>

However, since the ExportRequests.Id for LatestRequest is fetched when the Export is fetched, this access pattern returns stale data:

var export = session.Get<Export>(exportId);

export.AddRequest(new ExportRequest(DateTime.Now, "Foo"));

Assert.AreEqual("Foo", export.LatestRequest.Tag); // fails due to stale data

session.Update(export);

So, what's the best way to implement the LatestRequest property?

I could change the getter for LatestRequest so that it execut开发者_JS百科es a Find query, which should be up to date, but I'm not sure how to make the Export aware of the session.


There are several ways to solve this. I would probably not try to make it "automatic" this way. To enhance performance and simplicity, I would just make it a normal reference and manage it in the business logic or the entity like this:

class Export
{
  private IList<ExportRequest> requests;

  ExportRequest LatestRequest { get; private set; }

  public void AddRequest (ExportRequest request)
  { 
    requests.Add(request);
    LatestRequest  = request;
  }
}

So you don't need any special mappings nor any additional queries to get the latest request. And, most importantly, the entity is consistent in memory and does not depend on the persistency.

However you solve it, it is very important that the entity and the business logic is managing the data (in memory). It should be "persistence ignorant". The database and the data access layer are not responsible to manage relations and logic of the entities.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜