Skip to content
kostat edited this page Nov 22, 2019 · 1 revision

Java can do SQL LINQ better than C#

While being the most beloved language feature in .Net, it's commonly considered as "unneeded" in Java. Is there a mistake?

With Java 8, Java provided the best LINQ feature - collection querying using Stream API. We clearly see that with that release the pressure to have more LINQ features in Java had disappeared. It means that other LINQ features are actually not a so big success.

The most prominent among them, SQL querying, sounds like a good idea. After all, we obviously need to run SQL queries. And what are the options? Writing a String and give up on type safety, auto completion, refactoring?

The tough answer is yes. Except the trivial cases, it's simpler to write an SQL query as a string rather than a LINQ query. Because it's

  • not trivial and requires deep LINQ specific knowledge
  • has so many limitations, that most people prefer not even try

Hmm, why is it so limited? After all LINQ has been introduced in 2007. Enough time to tackle even the most complex problem.

Usually, when I see such a contradiction, I'm starting to look for a design mistake rather than an implementation problem (considering that in case of MS, they definitely have enough resources and expertise). Looking at it from the design perspective, the issue is obvious: they try to map the entire SQL world to the generic relational algebra concept of LINQ. Dear friends, it's hard to impossible! Not only SQL has many dialects, quirks and proprietary extensions; today it has features that are far beyond the relational algebra concepts: SQL-99 Common Table Expressions (WITH clause), SQL-2003 Window Functions (OVER clause), SQL-2003 MERGE (UPSERT clause).

So does it mean that the whole concept of LINQ to SQL is wrong? I don't think so. It's the concept of bringing SQL to the generic relational algebra basis is problematic. But the other parts are great:

  • using native language expressions to write the query (e.g. variables, methods, properties and operators)
  • hiding low level ORM mapping details
  • taking advantage of all the language-IDE integration, from auto-completion to refactoring

Just need to give up on the MS idea of LINQ being abstract concept and make it SQL (or other domain) specific. By saying that we make it easy to read (easy to write) and simple to convert to SQL. All because of 1:1 feature mapping. This is exactly the approach FluentJPA for SQL and FluentMongo for MongoDB has chosen.