开发者

While designing ORM, what is the best approach to represent relationship, performance-wise?

While开发者_高级运维 designing ORM, what is the best approach to represent the relationship, performance-wise? I mean, out of the following two, which approach is best considering performance?

class Employee
{
     int ID { get; set; }

     String Name { get; set; }

     int DepartmentID { get; set; } //This approach uses DepartmentID
}

--- OR ---

class Employee
{
     int ID { get; set; }

     String Name { get; set; }

     Department Department { get; set; } //This approach uses Department class 
}

From my perspective, the second approach is nice. It is object oriented, too. And that should be the main purpose of ORM; to convert relationship from RDBMS to Object Oriented. But doing this, we would be required to load the entire Department object in an employee one, even though it is not required.

How should you represent or what should be the best approach, in your view?


Most ORM frameworks will handle the second case with equivalent performance to the first case. Taking Hibernate as the reference example here, they would tell you in no uncertain terms to never ever do the first option. They're kind of snarky about it, actually.

In fact, I believe that the first option would not technically be considered ORM, since the relationships are handled at the ID level in your OOP code.

Hibernate (like most others) has lazy loading, which means that you can load your Employee and it will not fetch the Department. But then if you say employee.getDepartment(), it will at that point go do the simple select statement to get the department data.

This also happens to be configurable either at mapping time or query time, so if you have some use cases where you know you will need the Department you can save the second SQL call by telling it to fetch both Employee and Department in one join query.

Check out Hibernate's "Small Primer on Fetch Strategies" for more info.


You are forgetting that related items can be loaded lazily.

That is, when you create your Employee object, you don't have to populate the Department field. That can be populated when the get accessor is called.


this isn't so much a difference in performance, its actually just one is easier to implement than the other.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜