SQL constructs translated to OOP
As someone who comes from the world of Object Orientation, I find it rather difficult to wrap my head around SQL. Recently, however, I realized that the classical SQL construct
select X from Y where Z
is basically equivalent to the following OOP construct:
List<SomeType> results = db.query(new Match开发者_StackOverflower<SomeType> () {
public boolean match(SomeType candidate) {
return ...; // checks condition Z on candidate, returns true for match
}
};
So my question is: What are the OOP equivalents for other SQL constructs, such as joins?
I think Microsoft's LINQ (Language Independent Query) has made an attempt at creating a language that can be used as an object-oriented version of SQL. Hibernate's HQL would be another. I'd recommend exploring both of those if SQL is giving you problems. Maybe they can make it clearer to you.
What are the OOP equivalents for other SQL constructs, such as joins?
Imagine that we have a query like following:
SELECT * FROM tableA JOIN tableB ON tableA.b_id = tableB.id WHERE tableA.someFld < 50;
So you need to fetch every record from tableA
that match condition from WHERE
clause (tableA.someFld < 50
). Then for every record from result set check whole tableB
to find records that match ON
clause.
// Pseudo-code
Query query = new Query();
query.where(new Matcher....);
query.join(new Matcher<SomeType>() {
public boolean match(SomeType tableACandidate, SomeType tableBCandidate) {
return tableACandidate.getBId() == tableBcaididate.getId();
}
});
ResultSet result = query.execute();
精彩评论