TE
科技回声
首页24小时热榜最新最佳问答展示工作
GitHubTwitter
首页

科技回声

基于 Next.js 构建的科技新闻平台,提供全球科技新闻和讨论内容。

GitHubTwitter

首页

首页最新最佳问答展示工作

资源链接

HackerNews API原版 HackerNewsNext.js

© 2025 科技回声. 版权所有。

What ORMs Have Taught Me: Just Learn SQL (2014)

348 点作者 IA21超过 4 年前

73 条评论

Philip-J-Fry超过 4 年前
I&#x27;m a Go developer and I notice a lot of other Go developers instantly suggest things like GORM to noobs writing applications. Whereas I always suggest against it.<p>I&#x27;m a big advocate of understand your data model at the database level. Need to join on too many tables is too easy to do with an ORM.<p>My go-to strategy for SQL is simple. Abstract your SQL as far away from your application as possible. Not just by using interfaces in your application, but by using stored procedures in your database.<p>In my mind SQL is just another service your application depends on. And you want that interface to be as simple as possible for your application. If you need to tweak SQL performance it should not need any input from your application. I could completely migrate to a new table relationship structure without the application realising if that was what was needed. You could even go as far as to unit test just your SQL code if you wanted, something you can&#x27;t do too easily when it&#x27;s in your application.<p>Yes, if you need to return new data then you need to update your stored proc and code. But that&#x27;s so worth it in my opinion for that extra layer of abstraction.<p>My opinion is slightly skewed from a decently sized business perspective, but I do still follow this pattern in personal projects. When migrating applications to different tech stacks (like Java to Go, or C# to Go) this abstraction has meant the world to us.
评论 #24845705 未加载
评论 #24845731 未加载
评论 #24845470 未加载
评论 #24845632 未加载
评论 #24845502 未加载
评论 #24845994 未加载
评论 #24845598 未加载
评论 #24845554 未加载
评论 #24845819 未加载
评论 #24845788 未加载
评论 #24847946 未加载
评论 #24845875 未加载
评论 #24845771 未加载
评论 #24854684 未加载
评论 #24846042 未加载
评论 #24845570 未加载
评论 #24845434 未加载
评论 #24846652 未加载
评论 #24845579 未加载
评论 #24845835 未加载
marcan_42超过 4 年前
Everyone here is arguing for their favorite side. As often is the case, the best solution is often somewhere in the middle, using the best tools for the job.<p>I authored a complete rewrite of an ancient and rotting PHP+MySQL web ticket reservation app in Python+SQLAlchemy+PostgreSQL. I use an ORM - except where it doesn&#x27;t make sense because a SQL query expresses what I need to do more concisely and effectively. I don&#x27;t use stored procedures - except where I do because I need one specific atomic DB operation to be performant and not bottlenecked on the app. I use relational storage - except almost every table in the database has a big JSON column for everything I don&#x27;t need to ever join, filter on, or index in production codepaths (though I can still do that with PG&#x27;s native json support, which is great for the rare case I have to move something to a real column). And I use triggers, stored procedures, and notifies to implement live change notifications for a table, that eventually get fed via WebSockets server to users.<p>This hybrid approach has served me extremely well, resulting in very readable and maintainable code, minimal DB schema migration pain (most upgrades only touch JSON fields and thus require no migration), and much better performance than the old app, especially in that hot path using the SP, while keeping table column bloat down, and avoiding the join spam that results from keeping everything religiously normalized even in cases where that doesn&#x27;t buy you anything.<p>Of course, that does mean you need to know all the relevant technologies involved, SQL, ORMs, etc.<p>YMMV, but consider that if you think a single solution is the right solution in all cases, you&#x27;re most likely wrong.
评论 #24848087 未加载
评论 #24848275 未加载
评论 #24847845 未加载
sopromo超过 4 年前
I do not agree and this is coming from someone that loves SQL. I only experienced the problems that this article describes with people that do not know how the ORM works.<p>You can use an ORM and it works flawless for most cases. There might be some cases where I need to write SQL to generate a custom function or some weird edge case but that is why the ORM gives you the possibility to write your own SQL if you want.<p>I forgot to mention that having to write raw SQL queries and mantain them, doing migrations and keeping up with the changes is kind of a pain when most of the time the ORM takes care of everything.
评论 #24845469 未加载
评论 #24846252 未加载
评论 #24845669 未加载
jeswin超过 4 年前
There are many reasons why ORMs work better than it did earlier. For one, people prefer simpler database schema these days - and what used to be larger monolithic apps are often broken into micro services. Earlier, you&#x27;d have one big database - today you&#x27;ll have many. And ORMs are great with simple queries and joins.<p>The language plays a big role in whether an ORM is actually useful or not. In the .Net world, ORMs work quite well because querying capabilities are integrated into the language. Queries and schema are verified at compile-time, and I wouldn&#x27;t trade it for slightly better performance or control. On the other hand, with Python (or say Node), or with Java and Hibernate the wins are smaller.<p>Of course, there will be some queries which are just better written in plain SQL. If you&#x27;re willing to accept that, ORMs are a good tool in your toolbox.
评论 #24845457 未加载
评论 #24848162 未加载
评论 #24845442 未加载
drbawb超过 4 年前
The last bit of the article reminds me of an experience I had recently working w&#x2F; another group of developers. They write in C# w&#x2F; Entity Framework, but they just use it to map stored procedures to C# data-types. All queries to their database go through a stored procedure w&#x2F;o exception.<p>They push as much of the business logic as possible to the database. Their reasoning being that if the client insists on a separation between the DB &amp; application servers: you should do as much computation as close to the data as possible. Then just send the end result over the wire.<p>Due to my own ORM-induced brain damage I found it hard to wrap my head around this at first: a data type in the application no longer represented a table, but the result of a query. Once you realize the database is just another API though it clicks really nicely into your architecture.<p>I think I still prefer things like Linq, jOOq, Arel, Ecto, etc. where you can write the query in your programming language and have it translated to SQL. It&#x27;s just nice to see your query right next to the code when debugging. The author is absolutely right though you still have to <i>know SQL</i> to use tools like that effectively, so you might as well just learn it early instead of wasting effort learning the quirks of a specific ORM.
评论 #24848222 未加载
评论 #24848244 未加载
nodamage超过 4 年前
IMO people discussing this topic really need to clarify what type of applications they are working on because the cost&#x2F;benefit analysis changes quite significantly based on use case. If you&#x27;re building a web-based reporting tool where you simply query records out of a database to dump to HTML and your objects are short lived, you might not get as much value out of an ORM compared to a client-side app where objects stick around for the entire lifetime of the application and you have to worry about things like object identity and staleness.
评论 #24845772 未加载
unklefolk超过 4 年前
I personally have found that how to approach data access has been a real bone of contention on projects and quite damaging. It seems half the team want to use an ORM and have a long list of reasons not to use SQL&#x2F;Stored Procs (slower to develop, out dated, not testable, business logic in the wrong place). The other half of the team wants to avoid ORMs and would rather use SQL&#x2F;Stored Procs (performance, ORMs start off okay but soon aren&#x27;t up to the job, more control and power with direct SQL). In fact, you can see these two standpoints in this very discussion.<p>I find both have valid points and there isn&#x27;t really a compromise. Whichever approach is taken you end up with half the team feeling not listened to and disenfranchised.<p>I have found few things to be more divisive than the ORM vs No ORM debate and I am not sure what the answer is.
评论 #24847244 未加载
评论 #24846142 未加载
评论 #24846152 未加载
评论 #24846180 未加载
评论 #24846169 未加载
mattmanser超过 4 年前
Just to be explicitly clear to newer programmers.<p>This is an extremely niche view, ORMs save you a huge amount of time, and the days before ORMs were a real pain in the arse.<p>As a noob you are much more likely to introduce a massive security hole by rolling your own solution. Don&#x27;t do it!<p>So this article is sorta true, and you should learn SQL, but for trivial queries ORMs are actually a massive time saver and really useful in maintaining a system, especially in strongly typed languages (Java&#x2F;C#&#x2F;etc.).
评论 #24848898 未加载
eNTi超过 4 年前
I&#x27;m currently in the process of porting api code from .net 3.2 soap where the code is a mixture of string based SQL queries and stored procedures to a .net core 3.1 webapi mvc + ef.<p>Let me tell you... readability and type saftey are a boons. Not a curse.<p>Things still get convoluted but boy the errors that can sneak into a complex sql statement are painful to debug.<p>As always the pendulum in this &quot;article&#x2F;rant&quot; is swinging in the other direction (&quot;everything was better in the past&quot;). Also it&#x27;s fricking (almost) 7 years old. That&#x27;s a lifetime in software development.
评论 #24845895 未加载
评论 #24845780 未加载
mmatczuk超过 4 年前
Not all ORMs are like hibernate and gorm. I&#x27;m author of a lightweight ORM for Go and Scylla &#x2F; Cassandra [1] so I may be biased. In my view use of a good ORM makes your code more resilient to change, refactorings are simple and stupid mistakes largely eliminated. A benchmark of usefulness of an ORM can be how many lines need to be changed to add a new field to a struct &#x2F; class. In a good ORM this should be about 1, it should still work be ~1 if you use a hand crafted SQL &#x2F; CQL.<p>The worst thing that ORMs try to do is handling relations (eager &#x2F; lazy loading) and handling sessions &#x2F; object lifetime. This is mainly because it&#x27;s impossible to have one-fit-all solution for all usecases even in one application.<p>[1] <a href="https:&#x2F;&#x2F;github.com&#x2F;scylladb&#x2F;gocqlx" rel="nofollow">https:&#x2F;&#x2F;github.com&#x2F;scylladb&#x2F;gocqlx</a>
评论 #24846125 未加载
wodenokoto超过 4 年前
When working directly with SQL instead of an ORM, how do you elegantly handle things like parameterizing table names or having flags that turns on or off filters?<p>In non-ORM codebasese I am seeing patterns where sql queries are &quot;copy-pasted&quot; together and I am not sure I like it.<p>Just imagine the following example had hundreds of lines of SQL and several optional filters, some of which could themselves be several lines long:<p><pre><code> def get_data(table1, table1, use_subset=True): if use_subset: filter_query = &quot;AND column2=&quot;subset_value&quot; else: filter_query = &quot;&quot; query = f&quot;&quot;&quot; SELECT * FROM {table1} JOIN {table2} WHERE column1=&quot;value&quot; {filter_query} &quot;&quot;&quot;</code></pre>
评论 #24845796 未加载
评论 #24846436 未加载
评论 #24845767 未加载
评论 #24858804 未加载
评论 #24846112 未加载
izietto超过 4 年前
The point of ORMs is not avoiding SQL, it is avoiding concatenating strings in order to build complex queries. In our app we have very complex query logics depending on the request params, and I can hardly imagine how dirty the code would be without the relational algebra abstraction.
评论 #24845593 未加载
fabian2k超过 4 年前
I like ORMs for routine queries, there&#x27;s a lot of stuff that is just much nicer and less tedious to write that way. It&#x27;s also generally much less annoying to have some dynamic aspects in your queries with an ORM, e.g. adding different WHERE clauses depending on some parameters.<p>But even with relatively small and simple things you can run into issues very quickly if you don&#x27;t know what kind of queries the ORM will create. ORMs are very leaky abstractions, they&#x27;re useful but unless you understand SQL and understand their quirks you&#x27;re likely to create some weird and monstrous queries at times.<p>You should know how your ORM handles related entities if you query them, there are some big footguns there with some strategies. And of course you should know how to use the ORM so that it doesn&#x27;t do a &quot;SELECT *&quot; everywhere (which can be trickier than I&#x27;d like in some cases).<p>I would also not hesitate to drop to plain SQL for some cases, if your query doesn&#x27;t fit neatly into the capabilities of your ORM.
评论 #24845775 未加载
tekkk超过 4 年前
I would like developers to learn SQL first before picking ORM to actually understand what the ORM is doing for them. Sure they&#x27;ll be doing their share of sub-optimal subqueries and head bumping trying to write group by queries. But in the end I think this would make them better developers who knew the underlying software and application logic, not just the API of the ORM.<p>Yet we don&#x27;t really live in that kind of ideal world and there are many factors that people have to consider. If everybody else in the company is using ORM, why shouldn&#x27;t you. Or, if you just need to ship products and don&#x27;t necessarily enjoy learning SQL. Or, if you don&#x27;t know how to properly abstract the structured SQL queries without making it a huge mess. Saying that ORM is better&#x2F;worse is like saying everybody likes music.<p>If I&#x27;m building a Nodejs app I would choose not to use ORM. For other languages and frameworks I&#x27;d probably reconsider and evaluate my options.<p>To me however, the biggest benefit of using no ORM is the learning of SQL. Time and time again that proves itself so invaluable, and I&#x27;m immensely happy I&#x27;ve learnt the quirks of SQL instead of some language specific API. If I can code faster with ORM that&#x27;s great, but in ideal world I would much rather learn SQL and become a master of it rather than of some ORM.
dep_b超过 4 年前
This.<p>Everything else that does more than mapping SQL results 1-1 to a query result and maybeeeee helps you with atomic actions like INSERT, UPDATE and DELETE ends up being a chore. They all have their own quirks like around threading and usually end up forcing you to design your application around it unless you take some measures to isolate it from your main application, which means you&#x27;re now writing code while you wanted to type less code.<p>Add to insult a ton of the them seem really resistant to map the results of hand-written queries to an object. Also SQL dependency trees and object dependency trees never really seem to map that well. And don&#x27;t try to do more complex queries with the built in query language in Django or .Net. I have sometimes spent hours trying to get an SQL query working in an optimal way that would not cost me more than 5 minutes two write and map with simpler ORM&#x27;s.<p>The other day I talked to a dev that was otherwise a very strong iOS developer in a discussion why I always used SQLite directly with a simple wrapper that said &quot;I really should learn SQL sometimes&quot;.<p>There probably hasn&#x27;t been a skill more universally useful in my career as a developer than SQL apart from HTTP? But it also made me think about why I never really learned to write C (I can read and futz with it).<p>For anybody new in the trade reading this, the following things have been or could have been useful at any step in my career:<p>* HTTP<p>* HTML<p>* SQL<p>* JavaScript (blegh but true)<p>* C<p>* Unix<p>The rest were just passing by for a while, like Windows, Flash, PHP or any god damn JS framework out there.
dimeatree超过 4 年前
My project has no ORM, and now that other developers are coming on it is hard to work with - the readability of an ORM far surpasses writing your own queries and I can see that the benefits far outweigh the cons.<p>And what&#x27;s not to say you can&#x27;t write your own lightweight ORM to abstract the database if you can&#x27;t find a tool that suits your goals - and as always it all depends on your use case.
评论 #24845525 未加载
rbirkby超过 4 年前
Perfect example of the trough of disillusionment. The ORM slope of enlightenment comes when you realise the power of the unit of work, not just a single query. But that was then, and microservices mean we no longer use large units of work. So ORMs without complex UoW make less sense.
评论 #24846022 未加载
imhoguy超过 4 年前
Instead of polarizing between massive native queries in ORM strings vs DB-specific imperative stored procedures I would suggest a middle ground which are table VIEWs [0]. They are trivial to design (just SELECTs), stay declarative like tables, can be materialized for efficiency [1]. Finally they can be easily handled in ORMs as both static and dynamic entities, with all read-only benefits, with no need of any non-standard mapping or native queries.<p>[0] <a href="https:&#x2F;&#x2F;www.postgresql.org&#x2F;docs&#x2F;current&#x2F;sql-createview.html" rel="nofollow">https:&#x2F;&#x2F;www.postgresql.org&#x2F;docs&#x2F;current&#x2F;sql-createview.html</a><p>[1] <a href="https:&#x2F;&#x2F;www.postgresql.org&#x2F;docs&#x2F;current&#x2F;rules-materializedviews.html" rel="nofollow">https:&#x2F;&#x2F;www.postgresql.org&#x2F;docs&#x2F;current&#x2F;rules-materializedvi...</a>
评论 #24846103 未加载
mumblemumble超过 4 年前
So, I&#x27;m typically not a lover of ORMs as they&#x27;re typically implemented, and tend to also favor doing something close to the sproc-based method that Philip-J-Fry proposes in another comment.<p>It&#x27;s always struck me as odd that, as a profession, we generally agree with, and can be quite fanatical about, the idea that different modules and services should try to hide their implementation details as much as possible, and instead speak over well-defined, constrained protocols such as APIs or interfaces; but as soon as an SQL database comes into the mix, we happily throw all that hard-earned discipline out the window and go back to directly swizzling the internal state of external collaborators.<p>That said, there are some use cases where I&#x27;m not sure how you get around something like an ORM. One is when you need to allow users to execute arbitrary searches against the data. If that&#x27;s your situation, then, any way you cut it, you&#x27;re going to end up with some system that takes an abstract representation of a query and compiles it to SQL. The only question is if you want to use something off-the-shelf to do it, or if you&#x27;d rather hack it together yourself. In my experience, there are few things on this earth that present a greater maintenance burden than a homegrown ORM-type library does once the original author has moved on to other things.<p>And there are others where avoiding an ORM is over-engineering. If your database is just an honest entity store, and you&#x27;re just doing fairly straightforward CRUD operations against it, and it belongs to a single application, go ahead and punch the easy button and have a happy life.
评论 #24847982 未加载
评论 #24848214 未加载
jtolmar超过 4 年前
I&#x27;d really like some sort of macro that takes my random SQL query (with arguments), looks at the names and types of the returned columns, constructs some sort of struct&#x2F;pojo&#x2F;whatever to match, and gives me a function(my, args) -&gt; array&lt;that&gt;.
yen223超过 4 年前
Application code have one way of describing data and their relationships. RDBMSes have a very different way of describing data and their relationships. At some point, you are going to have to reconcile the differences between the two worlds - this is the so-called &quot;object-relational impedence mismatch&quot;.<p>Unfortunately, even if you choose to reject ORMs and go SQL, you&#x27;re still going to have solve this problem at some point, and it will not be pleasant.
评论 #24845751 未加载
lmm超过 4 年前
If you half-ass using an ORM then you get the worst of both worlds. To get value out of it you have to embrace it completely: write all the queries in the ORM (so that the ORM&#x27;s caching functionality etc. can actually work for you), define the schema in the ORM and generate the tables and migrations from that. Working with an ORM and avoiding SQL is not just doable, it&#x27;s easy, but you have to actually try.
评论 #24845422 未加载
gmac超过 4 年前
I agree with most of this, but once you’ve learned SQL, how do you integrate it with your code?<p>I find value in libraries that occupy a middle ground between nothing but raw SQL and a full-blown ORM.<p>In TypeScript (and with apologies for hawking my own project): <a href="https:&#x2F;&#x2F;jawj.github.io&#x2F;zapatos&#x2F;" rel="nofollow">https:&#x2F;&#x2F;jawj.github.io&#x2F;zapatos&#x2F;</a>
评论 #24845549 未加载
baq超过 4 年前
also read the manual for your DB.<p>it&#x27;s probably a thousand pages. likely more. i understand it isn&#x27;t the most thrilling reading of your life. it might just be once you have an issue in prod, though.<p>if you really don&#x27;t have time for that, i also understand. i was you. but really please read the table of contents in that case.
thrownaway954超过 4 年前
yeah, no... ORMs are A LOT more than just mashing strings together to perform a query.<p>they are there to take care of all of the crap that you don&#x27;t want or need to worry about. for instance, parametrizing string against sql injections, handling transactions properly, concatenating joins, proper pagination and sql syntax discrepancies to name a few. and let&#x27;s not to forget to mention things that go BEYOND the database interactions that are built on top of the ORM like data validations, custom properties, callbacks and so on.<p>there are way more benefits to using an ORM than not using one. a good ORM (like ActiveRecord) will let you break out of it and write raw sql when you need the perform boost while preventing yourself from shooting yourself in the foot.<p>* i&#x27;ve written and contributed to a couple of ORMs in my lifetime
评论 #24847519 未加载
noisy_boy超过 4 年前
Like everything else, use the tool but understand the inner workings too. E.g. Hibernate allows logging of the SQLs being executed so when I make changes, I review that the SQL being executed is as expected + performance is acceptable. From that point of view, understanding SQL performance is important. However, I don&#x27;t really want to write boilerplate SQLs when the ORMs can basically form the query for me using query method name - that is super convenient and I don&#x27;t want to give that up.<p>Selecting * from a table with 200 columns isn&#x27;t performant but if the table had 200 columns, I won&#x27;t be blindly relying on the ORM generated query anyway since most provide the escape hatch of executing direct SQL.
bovermyer超过 4 年前
I&#x27;ll use an ORM until I start running into performance bottlenecks. Then I&#x27;ll write raw SQL for those specific instances, and continue to use the ORM elsewhere.<p>This approach has worked so far.
kumarvvr超过 4 年前
The &quot;Vietnam&quot; article referenced in the post makes some very valid points about ORMs and their marriage to Relational data.<p>When using Object Oriented Languages, like C# &#x2F; Java &#x2F; C++ etc., the programmer is forced to represent data into objects. True, representing table and relations between tables as objects is difficult, but do OO programmers have any choice at all?<p>Afterall, the issue is not a single table (a row can very well be represented in OO constructs), it&#x27;s the relation between tables that causes headaches.<p>Even when using languages like Python, I have to inevitable gather related pieces of data together, in a dict say, and it still feels like mapping related tables to objects.<p>Another contention with the &quot;vietnam&quot; article is that the author assumes that OO programmers will want to use inheritance to model relations between tables. This seems outdated in my view. Composition is more suitable and powerful and is almost always used in ORMs, for ex Entity Framework.<p>The original post also claims that ORMs tend to gravitate towards &quot;select *&quot; queries. This is true, but has many solutions. Many ORMs optimize queries based on required columns. But there is also another issue with this. Say you have a table with 100 columns, but are only querying 5 at a time, isn&#x27;t it prudent to separate out those 5 columns into another table? Or perhaps create a view? If the use case demands just 5 columns, but the table has 100, isn&#x27;t there a problem with the data modeling rather than the ORM?
bullen超过 4 年前
ORMs thought me to build my own ORM, I even ported the thing to MySQL, Oracle and Postgres! It&#x27;s available to try if you use my own &quot;wordpress&quot;: <a href="https:&#x2F;&#x2F;github.com&#x2F;tinspin&#x2F;sprout" rel="nofollow">https:&#x2F;&#x2F;github.com&#x2F;tinspin&#x2F;sprout</a><p>But the source is not all there: <a href="http:&#x2F;&#x2F;rupy.se&#x2F;util.zip" rel="nofollow">http:&#x2F;&#x2F;rupy.se&#x2F;util.zip</a> (bunch of helpers) <a href="http:&#x2F;&#x2F;rupy.se&#x2F;memory.zip" rel="nofollow">http:&#x2F;&#x2F;rupy.se&#x2F;memory.zip</a> (I called the ORM memory!?) and <a href="http:&#x2F;&#x2F;rupy.se&#x2F;test.zip" rel="nofollow">http:&#x2F;&#x2F;rupy.se&#x2F;test.zip</a> (my first test of any software, more of a tutorial) is where you find all the details.<p>Also the thing has a graphical editor: <a href="http:&#x2F;&#x2F;move.rupy.se&#x2F;file&#x2F;logic.html" rel="nofollow">http:&#x2F;&#x2F;move.rupy.se&#x2F;file&#x2F;logic.html</a><p>All of this is very complex for something I later solved with JSON files over HTTP instead: <a href="http:&#x2F;&#x2F;root.rupy.se" rel="nofollow">http:&#x2F;&#x2F;root.rupy.se</a> but parts of it can be reused for other useful things; like logic was used to build game dialogue trees.
jillesvangurp超过 4 年前
ORMs have their place but they are IMHO overused and frequently fail for reasons that have to do with the good old object impedance mismatch; which is a pitfall that lots of junior developers fall into where they over engineer their database schema to make it resemble some platonic ideal of some class hieararchy. When that hierarchy inevitably starts changing, the schema erodes along with it.<p>Some symptoms that I&#x27;ve seen in multiple projects:<p>- requests are slow because every request triggers dozens to hundreds of joins.<p>- overuse of the @Transactional annotation (spring&#x2F;hibernate) because of developers slapping it on anything that looks like it might be doing anything with a database while neither understanding transactional semantics or aspect oriented programming (which causes some funny behavior)<p>- Attempts to implement class inheritance via database tables and corresponding hacks and complexity to query because of that.<p>- Lack of a coherent database design. IMHO, a good use of ORM should start with a good old database design. A 1 to 1 mapping of your domain to tables is typically not it.<p>- Over and under use of database constraints, indices, etc. because of a lack of knowledge of how databases actually work resulting in unenforced referential integrity constraints, poor performance, and weak transactional semantics.<p>I&#x27;ve used lots of different styles of databases over the years. I generally break things down into:<p>- simple key value stores like redis, memcached, etc.<p>- document databases like couchdb, elasticsearch. These tend to have schemas and fields<p>- SQL databases (mysql, postgres, mssql, oracle, ....)<p>- Nosql object databases (mongodb, firestore, etc.<p>I tend to mix these styles and would happily use postgres as a document store. IMHO if I&#x27;m not going to query on it, putting it in separate column adds little or no value. If I am going to query on it; it should have an index.<p>Years of using document stores have taught me the value of de-normalizing stuff like user names and other things that rarely change but are a part of pretty much everything. I&#x27;ve ripped out hibernate in favor of JDBCTemplate + TransactionTemplate on several projects where hibernate was causing more problems than it solved. Hand crafted joins are pretty easy to do.
slotrans超过 4 年前
ORMs ultimately serve no purpose.<p>If your data model is small, they save you very little work.<p>If your data model is large, they collapse and you have to abandon them.<p>There is no middle ground.
petepete超过 4 年前
I&#x27;ve seen this post and similar ones many times. ORMs don&#x27;t fit all scenarios, but most of the time it&#x27;s a question of when you fall back to something more flexible&#x2F;powerful. In Rails, writing the crud part of your app with SQL is pointless. Trying to get AR to do dashboard gymnastics is equally pointless. Pick the best tool for the job.
XVincentX超过 4 年前
I&#x27;m not an expert in databases, but I am starting to think that building an interface primarily designed for humans (that&#x27;s what SQL is) as the main medium to interact with the database maybe in retrospective was not a winning idea.<p>I&#x27;m not criticising anybody here (I am literally not in a position of critiquing anything); SQL was created probably 40 years ago and it probably made sense back in the times.<p>My point is that you can always build a human interface from a machine one; the reverse is not that easy. ORMs are a (failed?) attempt to do so.<p>I would very much push for computer-language integrated query support — (such as Datalog or Linq), and that is what the database server should be accepting as input, instead of a raw string.<p>Although a lot of people hate MongoDB, I&#x27;ve personally felt way more productive expressing queries with their query document system rather than using SQL.<p>Fixing design flaws with other software ain&#x27;t gonna bring us that far maybe.
tehlike超过 4 年前
Somewhat flawed reasonings.<p>Re: identities. Use of db generated identity has the downside, but n&#x2F;hibernate has a bunch of other Id generators to mitigate the problems. You can use sequential guid, hilo, guid, or whatever. I use sequential guid because it helps with a bunch of other things. So it&#x27;s not really a leaky abstraction. It&#x27;s not really an orm problem, you need to do that regardless.<p>Re queries: I think linq showed the true power of orm in some sense. Query your database as if you are querying your objects. It has problems like n+1 or exploding cartesian but postgres and the likes fixes it nicely with json_agg. I have to agree though that I like graphql way too. For nodejs compile time linq is not an option, so graphql it is.<p>Transactions: I don&#x27;t know how this is related to orms?<p>Disclaimer: former nhibernate developer that was around when ayende was building linq for nhibernate and my view is probably dated and biased.
评论 #24845404 未加载
gls2ro超过 4 年前
My main reason to use ORM and why I recommend to others to use it (specially if they are juniors) is because it usually (depending on the language&#x2F;framework) comes with great support for protecting against SQL Injection.<p>Of course not all ORMs will protect against SQL Injection completely and some of them will only implement partial protection. But it is a good start.<p>What I recommend strongly is not to mix ORM with plain SQL in the same line of code.<p>The code should either be full ORM or plain SQL so that it is clear where the responsibility of protecting against SQL injection should be.<p>Edit:<p>Also it is easier to add extra layers of protection after a while if using an ORM then when using plain SQL. Because with an ORM I can redefine lets say the Repo.all or Query.all method to add extra layers of protection. But with plain SQL I need to edit every single line where the SQL statement is present.
ganonm超过 4 年前
I&#x27;m surprised more people aren&#x27;t recommending e.g. JDBI<p><a href="https:&#x2F;&#x2F;jdbi.org&#x2F;" rel="nofollow">https:&#x2F;&#x2F;jdbi.org&#x2F;</a><p>I&#x27;ve used it on several projects and it seems to be the perfect balance between &#x27;close to the DB&#x27; and &#x27;close to the domain&#x2F;application&#x27;.
gigatexal超过 4 年前
I understand the usefulness of an ORM and how much its use can clean up a codebase but... truly performant queries (that take advantage of every aspect of your DB not just some vanilla lowest common denominator provided by an ORM abstraction) are done in SQL. In the end one has to make the tradeoffs between development speed (something an ORM has going for it) and performance and the eventual issue of having to handle the object impedence mismatch. For me it&#x27;s just so much more clear to read a handful of queries and see how things work. You can even create user defined functions and call them like an API from your codebase (a sort of ORM) and get the best of both worlds. It&#x27;s not a easy choice to ORM or not but SQL should be a skill everyone learns.
评论 #24845818 未加载
brunojppb超过 4 年前
&gt; I work on the principle that the database’s data definitions aren’t things you should manipulate in the application. Instead, manipulate the results of queries.<p>Following this principle will definitely make your life easier. I have been using Slick[1] and the Play Framework[2] for my backends for a good while and having the freedom to define my migration scripts in pure SQL is a big plus. My application models are very lean and don&#x27;t get mixed up with DDL. I can also fully understand what goes in the db migrations, zero magic there.<p>- [1] <a href="http:&#x2F;&#x2F;scala-slick.org&#x2F;" rel="nofollow">http:&#x2F;&#x2F;scala-slick.org&#x2F;</a> - [2] <a href="https:&#x2F;&#x2F;www.playframework.com&#x2F;" rel="nofollow">https:&#x2F;&#x2F;www.playframework.com&#x2F;</a>
klausjensen超过 4 年前
My preference is currently ORM + drop back to SQL when you need something that is complicated or inefficient using the ORM. I have been writing SQL for 20 years.<p>I currently use dotNet Core and Entity Framework + Dapper.<p>It has these benefits: - Strong types! - My schema+migrations are part of the source code and I never have to worry about if my schema is in sync - with migrations it just is - Simple, straightforward tasks as super easy (insert, update, delete, simple select) - I can fall back to Dapper (straight SQL) when I need to do something that doesnt fit well with Entity Framework.<p>I recently worked on a project where EF was not allowed - and we spent so much time doing all the simple stuff, especially when the data model was still not completely locked down.
评论 #24849822 未加载
roenxi超过 4 年前
I&#x27;ll put it in the mix of ideas that the problem isn&#x27;t ORMs, it is trying to build ORMs <i>on top of SQL</i>.<p>Languages could be placed on a spectrum of how easy it is to build a DSL over the top of the language. Lisp is on one extreme, where it is easy to write a new language over the top of it.<p>SQL is pretty close to the other end of the spectrum. I&#x27;ve <i>never</i> seen a DSL that can compile to the full breadth of SQL dialects out there. DSLs generally handle the trivial well then fall apart when they hit complicated SQL statements.<p>If an ORM just had to fit over the top of a relational model it would probably work fine. The problem is, in the middle of all this, something has to be constructed in performant &amp; parseable SQL.
wonnage超过 4 年前
Whether or not you use an ORM, you ideally have your own abstraction on top of it, defining a set of known queries. This avoids the classic Rails problem where the User model has a million methods, and you don&#x27;t know which of them might make a SQL query.<p>Also, ORM caching always finds a way to become a huge pain. It&#x27;s easy to wind up with multiple objects representing the same underlying DB row, but updating one in memory won&#x27;t update the others, so you update them all from DB just to be safe... You might say &quot;find a better ORM&quot; but I&#x27;m pretty sure they all run into this problem at some point. IMO you&#x27;re better off doing it yourself and making it explicit.
kuon超过 4 年前
I have been using ecto for some time now, and its approach is very good. It is just some syntax sugar to help to write safe SQL from elixir. There is no magic like cache or anything from complex ORM and it has been the best experience in many years.
csnweb超过 4 年前
What I found to work really well (esp. with GraphQL &#x2F; Dataloaders) is using something like postloader by gajus [1]. It generates a slim interface from the database schema. For the simple run off the mill things you get an easy interface to get certain rows of a table or load related data, which is a huge part of what you will need when writing GraphQL resolvers. We extended the idea to generate simple wrappers for creating and updating tables as well, if anyone is interested in that I may dump the code for that in some gist.<p>[1] <a href="https:&#x2F;&#x2F;github.com&#x2F;gajus&#x2F;postloader" rel="nofollow">https:&#x2F;&#x2F;github.com&#x2F;gajus&#x2F;postloader</a>
preommr超过 4 年前
You start using an orm when you&#x27;re basically rewriting a crappier version of one.<p>You stop using an orm when you&#x27;re wasting time going through it&#x27;s documentation trying to figure out how to do something tricky for some obscure ad-hoc execution.
zby超过 4 年前
The title suggests that you would be better with no ORM, just SQL. I have not been coding for years - but still remember why ORMs came into being - before them there was lots and lots of repetitive code with the query preparation and execution with long ugly constant strings and string manipulation. With ORMs (and query builders) it all became much more compact (and looking better without the uppercase SQL). As every programming abstraction it is not perfect and you still probably need to learn SQL if you use ORM - so you need to learn both.
ThePhysicist超过 4 年前
SQLAlchemy is pretty sweet in the sense that you don&#x27;t have to use the ORM, it has a non-ORM part that lets you write almost arbitrary SQL statements programmatically. This often results in cleaner code than when writing those queries by hand (which you can also do in SQLAlchemy), so I prefer it to raw SQL. For things like database migrations I prefer raw SQL files though, as it&#x27;s a bit painful to get edge cases right with tools like Alembic (haven&#x27;t used if for two years though so maybe things got better).
Tomis02超过 4 年前
My experience is that most developers are really bad with SQL. Because of that, they would rather use an ORM because they think they can avoid internalising the relational paradigm. But, guess what - if you don&#x27;t speak relational then your table design will suck, which in turn will impact DB performance. Given a long enough time, you&#x27;ll either switch jobs before this becomes a problem or you&#x27;ll be forced to learn SQL properly. Most developers just switch jobs.
keithnz超过 4 年前
I&#x27;m an advocate of lightweight ORMs, in C# world, I&#x27;ve used Dapper a lot, and now using RepoDB. Lightweight means I can easily craft SQL and quickly map it to types, and things like CRUD on simple entities is very straightforward. But I generally agree with learning SQL, and avoid mapping it to types if you are just going to pipe into json for the front end. SQL is good for query and projecting data into new forms, complete waste going through a type if not needed
jbjohns超过 4 年前
What I don&#x27;t see a lot of mention here is database selection. If you really need an Object-&gt;? mapping, why not just use a document store or the like? I don&#x27;t know how many remember but in the earlier days of Java everyone was talking about OO-databases. I think they didn&#x27;t work out because they tended to be language specific but now you could serialise your object tree to JSON and store it in a document store if you wanted to.
projektfu超过 4 年前
I’ve found a lot of programmer friends are apprehensive about SQL. I’m not sure why, but they see it as a wizard language instead of a friendly DSL like I do.
kumarvvr超过 4 年前
The development speed with ORM&#x27;s is ridiculous fast and easy on the mind.<p>I do agree that for large, complex performant queries, ORMs might not work out, but I would say that those queries are better written as SQL procedures &#x2F; functions because they are bound to be modified or changed anyway.<p>Having said that, most LOB apps, small apps, apps that have in-frequent access of the DB, etc, can benefit from using ORMs.
shoesdontfit超过 4 年前
I can never really decide the answer to this question and I have been programming a long time. I end up just not thinking about it too much and doing what I feel like because getting things done is more important than standing around thinking about the millions of different options.<p>There are various arguments that seem to have flaws of their own. For example, &quot;use ORMs for all the simple things, and raw SQL for the complex things&quot;. The problem with this is that even simple things like &quot;insert this into the database&quot; often require checking that the foreign keys you insert are within the domain of the user trying to insert them, and various other constraints like that. So with SQL, you can do this all in one query, but with an ORM, you often create a query for each check.<p>Related to that is the idea of &quot;premature optimisation&quot;. The problem with this concept is that all queries add up together to determine how much hardware you need, which determines your costs. You can argue the opposite of premature optimisation, depending on your case. Why not spend 5 minutes extra writing a manual query that will be run hundreds of thousands of times for years?<p>Are your goals about reducing infrastructure costs as much as possible? Is &quot;developer time&quot; really a thing, or are you doing this in your own time for a startup or something?<p>Then there is the fact that doing simple things faster isn&#x27;t much of a selling point because they are already simple. It is very obvious though that ORMs are much, much more readable than raw SQL.<p>Then another question starts to come up, if you are using this abstraction like an ORM or GraphQL as an ORM, why are you even using a SQL database when none of the features are really available to you?<p>SQL has has interesting new features in that you can do the object mapping inside the queries now. For example:<p><pre><code> select post.id, post.content, json_agg(comments), json_build_object(&#x27;id&#x27;, a.id, &#x27;name&#x27;, a.name) as &quot;author&quot; from posts, comments, authors group by etc... </code></pre> Still, it is nowhere near as easy as using an ORM. The other thing is that when you start using an ORM, you really do end up having a different approach to querying your data in every situation. You don&#x27;t use all of the various features of SQL. It ends up being a lot slower, but maybe in some cases that is worth it.
评论 #24845580 未加载
xupybd超过 4 年前
Yes ORMs are terrible but there is a middle ground required. Something to nicely pool connections and handle all the boilerplate involved in binding parameters to prepared statements. I normally roll my own but would love to find a good library that does it all.<p>One problem I&#x27;ve yet to find a good solution to is automatic reconnect on database errors with proper transaction support.
zimpenfish超过 4 年前
Whilst I have long railed against ORMs, I do appreciate `pg-orm` (and for my own stuff, `crud`) in Go because it means I don&#x27;t have to write Nx100 (177 distinct structs at $WORK) versions of &quot;scan the results into this struct type-safely&quot;.<p>But that&#x27;s less of an ORM and more of a data mapper?
mozey超过 4 年前
The sqlc lib &quot;generates fully type-safe idiomatic Go code from SQL&quot;. It makes sense to generate code from SQL and not the other way around. <a href="https:&#x2F;&#x2F;github.com&#x2F;kyleconroy&#x2F;sqlc" rel="nofollow">https:&#x2F;&#x2F;github.com&#x2F;kyleconroy&#x2F;sqlc</a>
Traubenfuchs超过 4 年前
Just use a mature ORM where you can easily combine ORM capabilities and raw SQL, like Hibernate &#x2F; Spring Data. There you can do raw-raw calls to the SQL driver, map your optimized by hand query to an object or let Hibernate fetch a whole graph of stuff by itself.<p>Use the right tool for the job.
评论 #24845853 未加载
syspec超过 4 年前
Rails with Arel is really special, the queries it creates are really impressive coming out of an ORM. I would be curious to hear an updated version of this critique which focuses on Arel.<p>Now of course learning SQL is still a good thing to do, but for some a good ORM can be a way of doing that
chmod600超过 4 年前
Much is said about <i>what</i> to learn, but <i>when</i> you learn it is just as important and I&#x27;d like to see more written about that.<p>Is an ORM good to help onramp beginners, or is it some syntactic sugar for experts who already know SQL very well? Or both? Or neither?
dkarp超过 4 年前
ORMs should not be sold as &quot;Now you don&#x27;t need to learn SQL&quot;. Like any abstraction, it pays to know about the layer below even if you&#x27;re being saved from directly using it. In the case of SQL and ORMs, this is particularly true.
nickik超过 4 年前
Going from Hibernate to JOOQ for the DB managment has been the best change ever.<p>JOOQ is a wunderful SQL abstraction that is very nice to work with.<p>What I would really like is a Datomic style Database and have a JOOQ like Datalog, but I can&#x27;t have everything at the moment.
qwerty456127超过 4 年前
I couldn&#x27;t agree more. We all should just learn and use SQL. In case it really really really (because avoid multiplying standards) doesn&#x27;t fit a significant portion of the real life tasks well we should just design a new SQL.
revskill超过 4 年前
That&#x27;s why in my last Ruby On Rails projects, all my query and mutation are just sql query. No ORM, no callback.<p>The reason is that, not all our Rails devs understand well ActiveRecord, but they know SQL enough to make things work.
BMSmnqXAE4yfe1超过 4 年前
Why article writers always assume everyone knows all their abbreviations?
banq超过 4 年前
ORM +DDD = business!
评论 #24845490 未加载
mmcnl超过 4 年前
This article hits the nail on the head. ORMs rarely solve a problem but they almost always add complexity. I always advise against ORM.
stuaxo超过 4 年前
ORMs are good if you already know SQL.<p>Not all ORMs are created equally.<p>I enjoy the Django ORM and it&#x27;s composability, OTOH I was really not keen on earlier ORMs.
INTPenis超过 4 年前
I&#x27;m glad I learned to program in the late 90s because ORMs were a new thing I had to learn in the mid 2000s.
aww_dang超过 4 年前
1)Clearly state the goals of the project.<p>2)Use the minimum amount of technology necessary to solve the problem.
joshsyn超过 4 年前
Micro-ORMS for boilerplate sql - RepoDb. Rest just use Query Builder or raw sql.
UK-Al05超过 4 年前
I don&#x27;t mind very simple stored procs for queries, saving data, and the application just has lightweight abstraction around them.<p>Putting core business logic in stored procs though is a big no no.
throwaway4good超过 4 年前
Just say no to ORMs.
02020202超过 4 年前
yeah, the thing is that at the beginning you just don&#x27;t know what you&#x27;ll need later. so sticking to anything strict will become a limitation sooner rather than later. it is pain to do the manual work in every project over and over again but &quot;this is the way&quot;, unfortunately.<p>i have done two event-sourced project in a row and i am trying to make a reusable library that i can use from now on, which will allow me to write projections so i am not tied to any schema and can build any data structures i&#x27;ll need.
评论 #24845403 未加载
ozim超过 4 年前
That is such no discussion.. and articles from 2014 are not having any valid arguments anymore.<p>I put it along the discussions about which OS is the best. Which does not matter at all. Please stop wasting everyone time with those arguments. Do what is best for your project and shut the f up.
评论 #24848930 未加载