by red_admiral · 3mo ago · 0 comments
Some ORMs let you specify the extent of the data that you want, like Hibernate has its own Hibernate Query Language.
At some point you are better off just writing SQL yourself, though. Even without join problems, if you ask an ORM to get the person with user id 123 and all you want is their name, the ORM cannot know that unless to tell it, and so you end up with a 'SELECT *' type query.
Not saying you never need bare SQL on Django sites, but the Django ORM does have some sophisticated APIs to prevent this problem.
> Even without join problems, if you ask an ORM to get the person with user id 123 and all you want is their name, the ORM cannot know that unless to tell it
So ... tell it! You can specify in a query to fetch only certain data, and not the whole object.
var name = dbContext.Users .Where(u => u.Id == 123) .Select(u => u.Name) .First();
I ask because `Where(u => ComplicatedBooleanFunction(u))` can't in general be transformed into something you can do in SQL, especially if it's stateful, but maybe there's a trick if the function is simple enough?
Some ORMs get around this problem with methods like .WhereEqual(User::id, 123) so you don't need to parse anything to know the semantics.
PS. I have in the past got praised at work for massively speeding up database access, when I fixed something like `List<User> userList = UserDAO.fetchAll(); return userList.length();`. You need a minimal understanding of databases to use an ORM correctly. The DAO even had a `.count()` method, but you need to know a little about databases to know to look for that in the first place.
Certain methods like First() in this case materialize expressions. Only those trigger a DB query.
An ORM in the traditional sense abstracts the details of the query itself fully away in favor of an object-oriented interface.
I'm not a C# user in my professional life so I'm happy to be corrected, BTW, just citing the source of my misinterpretation
I have a WIP PR that addresses exactly this: