96 points · by stemlaur · 5y ago · 189 comments
In return you get reduced performance, overly complex and difficult to read SQL code generation, an inflexible entity model, and non optimal database access patterns.
JPA is an extremely complex framework whose benefits, in my opinion, outweigh the costs in only a small number of relatively simple use cases. And even in those simple use cases, in my experience it is far less performant (and double the LOC) than using SQL directly.
I’m not saying you can’t use JPA in large, complex applications, because you obviously can. But those applications are harder to write, much larger, less maintainable and less performant than the equivalent applications written with simpler frameworks or libraries.
I personally found MyBatis annotated interfaces to be the ideal way to map SQL to Java, but perhaps ApacheDB is better for smaller projects.
JPA is one of those fabulous engineering experiments that, sadly, didn’t work out. It breaks every rule in the engineering book in order to make SQL work like Java, but it doesn’t succeed, and I could never recommend it to anyone.
I'm a firm believer in leaky abstractions [1]. I often found with JPA that I would be fighting the framework to get it to produce the SQL that I wanted. I encountered (then) ibatis and it was a breath of fresh air. It took care of much of the tedious column-to-Java mapping and didn't introduce another DSL.
As soon as anyone tells you "you don't need to learn X with our framework Y that sits on top of it", all that means is you have to learn X, Y and the X->Y and Y->X translations and all but the first is proprietary.
This was my core issue with GWT (Google Web Toolkit) too. Too many engineers who weren't interested in learning Javascript saw it as a way of avoiding learning Javascript.
It's been many years at this point since I've used it so this may have changed but I recall that query verification was a runtime error issue and there wasn't a good way to essentially check that all your queries were valid. I mean you could write this yourself but it seems like some CI/automation could've done a lot of the heavy-lifting.
IIRC the same went for integration testing and stub databases for reading and writing via ibatis/mybatis.
[1]: https://www.joelonsoftware.com/2002/11/11/the-law-of-leaky-a...
I don’t mind leaky abstractions but the killer with JPA was the cache. IIRC, mixing pure SQL with JPA was really tricky because you’d end up with cache inconsistencies. So the JPA abstraction was leaky but the the framework effectively assumed that it wasn’t, which lead to all kinds for workarounds.
Exactly, except it's not just about language Y being proprietary. (I am using term "language" instead of "framework", because they are, in the broad sense, conceptual languages.)
It gives you a hint when the language Y is worth having in addition to language X - only if the language Y makes it significantly easier to model problem in your domain. Therefore, by definition, the language Y has to have some limitations that X doesn't. If Y is as a general language as X is (it can express same problems with similar effort), you end up doing busywork translating between X and Y.
And this problem plagues ORM frameworks of all sorts - it's not clear what is more easily expressed in the language of the ORM, which is not already expressed in the relational algebra (and SQL), and conversely, what are you giving up by using ORM. Although it happens in all sorts of DSLs.
So they turn on logging, get the SQL, and email that unreadable mess. In most of the cases I have seen, the SQL is fetching much more from the database than what the code really needs.
The first step when optimising SQL is to only ask for data that you actually need. Hibernate, as I have seen it used, defaults to fetching too many columns. I cut the SQL down, and come up with a performant statement. The developer has the challenge of translating the performant SQL back into Hibernate.
Hibernate makes easy things easier and harder things harder.
The trick is that while knowing what you are doing in regards of limitations and performance, you design the data model alongside cardinalities from user facing components. You'll end up with a highly normalized schema.
The nice thing is that you can create views later on and transform data into shapes that are more useful to others.
If you make the mistake to start with the data-model only without knowing how the data is being collected or used you will most likely spend lot's of time converting entity objects into other objects and the other way around. The worst thing I have seen in my career, was half of the business logic implemented in Java and the other half in PL-SQL.
JPA is great for large projects! I haven't had a single issue that we could not solve.
But we found even in simple applications with a dozen tables, the generated SQL was suboptimal. For example, to delete the children of a parent row resulted in a DELETE statement for each child row. I’m sure there are loads of good reasons why it did that, but it’a not something that you’d even consider in pure SQL.
The systems I build these days tend to put 100% of the database logic in the database using (you guessed it) plPGSQL, and leave Java (or actually Go these days) to do the non database transforms, networking etc. you could say that I replaced learning about JPA with learning more about the insane capabilities of my database.
I’m sure you (and half of HN) are gagging right now, but I know I’m not alone, and I’ll take 75% fewer LOC and 1-2 orders of magnitude performance improvement over JPA any day.
IIRC, it does that if you use Lists instead of Sets.
https://dzone.com/articles/best-performance-practices-for-hi...
All I have to do to create a new table is define a class with some attributes and the corresponding SQL migration, I don't even have to annotate anything. To create a new row I just do new Table(attr1: expression1, attr2: expression2).save() and I am done.
Compare that to the usual mess of writing down the same column name four times with raw SQL (1. to reference the column, 2. to set the column value with a named parameter, 3. to set the named parameter, 4. declare the variable you wanted to save in the first place).
Of course, I'm not using Hibernate directly, that would be foolish. Instead I am simply using Gorm to wrap the awful parts of Hibernate (the irony).
> You get to throw away all the semantics built into the database structure, including knowledge about indexes,
suggests you either don't know JPA very well or your writing is a bit sloppy.
Please avoid making sweeping generalisations about tools that save hundreds (or al lot more) of hours of programmer tools just because you didn't get it.
Too often I see people going with a lesser alternative because such comments are scaring them away.
Which bit they didn't get?
>> You get to throw away all the semantics built into the database structure, including knowledge about indexes,
I wrote:
> suggests you either don't know JPA very well or your writing is a bit sloppy.
To suggest that JPA means "throw[ing] away all the semantics built into the database structure, including knowledge about indexes" indicates either that the person doesn't know what JPA is about: indexes should be used with JPA for all but the most trivial setups. Same goes for other general database knowledge.
You wrote:
> They made some concrete criticism based on their experience (hard to maintain, complex annotations, etc),
I just pointed out that it was either a misunderstanding or so sloppily written as to create misunderstandings.
> but you in turn dismissed those with "you didn't get" and some borderline name-calling. Which bit they didn't get?
The bit about JPA not standing in the way of using good database practices.
It is not name-calling. I point to the exact words doctor_eval uses. To be polite and also be sure to make room for error on my side I also offer the option of sloppy writing. Sloppy writing happens to all of us and I'll be happy to know if doctor_eval didn't mean it or if I've misread it.
If not however it is not smart to use big words to try to trash a super useful tool that save many of us lots of time and often increase quality.
I recently found this obscure but quite stable library, kind of fell in love with it.
A User can be considered unique in one context by its email address, or by its social security number
Personally, I'm a fan of giving everything a random UUID, because it's more flexible. It's random and impossible to guess, it scales well because there's no central bottleneck like with an autoincrement, and it's future proof and flexible.What happens when the user changes the email address? What if the social security number changes, because it was wrong or because it actually changes? What if the original unique identifier wasn't a good choice? What if we decide that the user can have multiple email addresses? Then you may end up having to restructure the entire database, which will be a very annoying thing to do. What if you implement additional rules for what an email is allowed to look like and now the constraint fails for existing users, and this correction needs to be propagated to millions of already existing rows?
Real-life personal data is weird and fuzzy. They can violate seemingly sensible rules like being unique, unchanging, or conforming to any rule whatsoever. Best not to let them spread all over the DB and cause trouble later.
Instead, you could just have a random ID that doesn't mean anything and therefore can stay fixed forever, and any user-related metadata stays in the user table, where it can be modified as needed. Plus an UUID is a fixed 16 bytes, which is easy and efficient to deal with.
What if the user doesn't have an SSN? What happens if they have one but lawfully refuse to provide it? What happens when you ask for and SSN from a US citizen who is also a European citizen? What happens when your database leaks?
In general, relying only on natural keys is a nightmare. Double nightmare if it's PII. Natural keys only work if you are flawlessly omniscient about the domain. And you aren't.
Some cases I've seen in previous roles where some natural key is required include reconciling third party data sources, or processing events from a topic or stream and being able to replay the event log, etc knowing that a different ID may break other third parties you don't control since they've already imported the ID. Being able to replay your data sets from scratch and get exactly the same data can have some real advantages for some apps.
Of course you need to be aware of the domain and assume that the key can change over time and have strategies to deal with that (e.g. entity version tables bound by time, data migration to add key attributes, etc etc) and the data structures/processes needs to be designed for this. There's more work in it for sure to get right - it shouldn't be the default. But in some cases I've seen it work really well which frankly surprised me at the time.
Identity crisis: how Social Security numbers became our insecure national ID https://www.theverge.com/2012/9/26/3384416/social-security-n...
Back in the 1990s I was trying to convince my colleagues not to use SSNs as unique IDs. I've since noted that quite a few organizations that had gravitated to SSNs as IDs had to go through expensive and chaotic migrations to real unique IDs.
SSN alone is not sufficient, of course. But it _is_ definitely part of the natural key that you use _implicitly_ ANYWAY, whether recognizing it or not.
> Natural keys only work if you are flawlessly omniscient about the domain
I would call that BS. Nobody is "flawlessly omniscient" about anything, not even in mathematics, yet we design and build systems that work.
On the other hand, yes, it is a very good requirement to have someone on the team during database modeling who understands the domain model thoroughly. No UUID columns will save you from that.
These are different concepts. "Looking for a person" means search. You can look for people lots of ways. In medicine for example, they often look for first name + last name + birthday. Is that a unique ID? No, but it's close enough for search usually.
On the other hand, for any kind of indexing or foreign keys, you want an actually unique, immutable ID, which means you don't want a natural key, you want an artificial ID created just for your database.
And such systems typically use synthetic keys to completely dodge the kind of problems I outlined.
The problems with natural keys are that you, the programmer, don't know as much as you think you know. You muddle the problem domain with the solution domain and when something comes along in the problem domain you didn't think of, it's now much harder to fix.
> On the other hand, yes, it is a very good requirement to have someone on the team during database modeling who understands the domain model thoroughly. No UUID columns will save you from that.
They save you from having to work out how to store a record when you chose SSN as primary key and discover that, uh, no you can't do that. The same goes for purchase order numbers, waybill numbers, student IDs, payroll IDs, bank account numbers, license plates ... anything whatsoever that is visible in the problem domain will or will have exceptions you didn't know about, didn't foresee and for which legislation or policy allows no exception for not using a UUID column.
Having a notion of multiple verified ways to contact the user is one step up over this. Not lot of websites actually do this. Linkedin is one of them; because they recognized early that they needed to track their users as they changed their professional affiliation.
I tend to use list fields for things like phone numbers and email addresses. This makes it clear that I understand that users might legitimately have several of those and that they change over time. I always liked what Keybase did with encouraging its users to have multiple verified third party identities (the more the better).
Using a social security number is a mistake for a different reason: it's a sensitive bit of information that can be abused if it falls in the wrong hands. You should protect it like you would protect a credit card number and generally not store it unless you absolutely have a valid business reason to. Also, it's country specific which sort of makes it an obstacle if you need to serve an international market (or have the ambition to do so later).
I have three discord accounts and there is no way to avoid that.
Unless of course, you're using a relational database like OP and incur a performance hit from using a UUID as your primary key. Additionally, they're not sortable like autoinc id's.
I've always wanted to try out Twitter's Snowflake ID [1] algorithm to get around this, but it requires requires using something like Zookeeper. I've seen some people on the net talk about UUIDv6 being sortable by time, but there's still the potential performance hit of index size.
While I'm bringing this up I've never actually tested how slow PK UUIDv1's are and at what magnitude their performance hit becomes noticeable.
[1] https://blog.twitter.com/engineering/en_us/a/2010/announcing...
ksuid https://segment.com/blog/a-brief-history-of-the-uuid/
Using DB autogenerated IDs risks that nightmare situation I've seen in more than one organization I've worked with: the IDs "leak" and become actual identifiers, in perpetuity, for the related entity. Now you can no longer renumber your table, and if you dump and restore you get all new IDs.
The case you describe sounds like using Oracle ROWID as a key, which I suppose people do as a hack to get around schema problems instead of fixing the schema. [1] That's an exceptionally bad idea.
[1] https://docs.oracle.com/cd/B19306_01/server.102/b14200/pseud...
Why would you want to sort by ID? Sort by something sensible, like the signup date instead. An autoincrement may stop corresponding to time if for instance at some point a database has an external dataset imported into it.
IMO, using an ID for anything other than an opaque identifier is asking for trouble.
So yes, I agree with you, I always use a random UUID as ID.
> Then you may end up having to restructure the entire database, which will be a very annoying thing to do.
Well, you might call it annoying, I may call it a good upfront design requirement. Yes, you have sometimes spend time on stuff that doesn't immediately pay off, but it will pay in the longer run.
If you have a problem with your natural keys, this is mostly due to missing or misunderstanding your requirements, or an incomplete domain design. You can of course just sweep stuff under the rug, and pretend it's not there, but it's not a maintainable strategy.
(Unless you are a consultant of course, with a fixed term assignment on a project - in which case it is an excellent strategy for yourself...)
The author of TFA seems to be going through one of the stages described in "ORM is the Vietnam of Computer Science", an article that should be mandatory reading before one claims to know the solution to this decades old problem.
You can even fetch the results of arbitrary SQL expressions into a model class, which can handle partial population of columns. This allows combining ORM and SQL approaches with some code operating on models where that is natural, but this code can be applied to models which are fetched in alternative fashions when that is more preformat. E.g., fetching records using criteria that involves joins and only selecting relevant columns for the subsequent processing of fetched results.
The jOOQ "DSL" (i.e., Java interfaces and static methods) gives you essentially the full power of SQL without having to rely on external SQL files or stored procedures. (Or even worse strings.) You can even programmatically build these queries. E.g., optionally including different WHERE/HAVING criteria. The jOOQ "DSL" provides a fair amount of compile-time type safety, which isn't possible with external SQL.
* auto-complete in your IDE when writing queries in jOOQs Java DSL that maps quite naturally to SQL
* type safety. e.g.: migrate after a schema change, re-generate your jOOQ lib and see in your IDE (red underlines) all the place your queries would break using the new schema
* build queries from parts (e.g.: store/manipulate some where clauses in a local variable) w/o any string manipulation
But is has costs:
* generate the jOOQ library from your schema at build time (or everytime the schema changes): increase build time (a little) and complexity (a db needs to be around during builds)
* very small runtime overhead: queries are build at runtime
* one more thing to learn
To me the benefits outweigh the costs (unlike Hibernate, I much agree with the article) and I consider it similar to LINQ on C# while not being some language built in feature with it's own syntax.
http://blogs.tedneward.com/post/the-vietnam-of-computer-scie...
Edit: huh, seems to have got truncated over the years. Here's an archive link
https://web.archive.org/web/20160120004603/https://blogs.ted...
In other words it’s a complicated subject with a long and fascinating history, yet Americans will tend to only remember the short, disastrous bit they were directly involved in?
> "Although it may seem trite to say it, Object/Relational Mapping is the Vietnam of Computer Science. It represents a quagmire which starts well, gets more complicated as time passes, and before long entraps its users in a commitment that has no clear demarcation point, no clear win conditions, and no clear exit strategy."
Though I must admit your take is good, too!
Don't you mean the reverse? A relational database is never designed "for the ORM" -- ORMs are designed (sometimes poorly, sometimes better) for some databases. The object-relational impedance mismatch problem is well known in software engineering for a reason: OOP and relational databases weren't designed with each other in mind, and in fact, "fight against each other" in many ways. This is the starting point of the Vietnam article -- you can disagree with the analogy, but the impedance mismatch is very real.
If you’re living in the Java ecosystem, the biggest benefit is that you have a massive library ecosystem and developer base that understands it. If you’re going to throw all that out and require new people to learn your homegrown mess, why not pick a language that’s more interesting than Java? Then you’ll get new developers that are anxious about Go/Elixir/WhateverHotness.
Saying this as someone with 15 years in Java world.
For me, migration to Hibernate was improvement. There is a subculture of people who hate Hibernate, hate Java, hate frameworks for anything. And some of these people are very vocal and emotional about it. And then there is everybody else.
And a lot of it honestly sounds like projection. People who dont like to have to learn these things and quite clearly did not bothered to learn them. They assume Hibernate is used to avoid learning SQL, because that would make sense to them. But, back in real java world, developers are expected to know both.
I mean, there are definitely cases where JPA/Hibernate doesn't fit for all kinds of reasons, but don't avoid it where it does help (e.g. the 4 user CRUD app that needs to be "web scale").
My experience and methodology is as follow :
- Write test for your ORM layer. Possibly not in Java. Some high level integration type test. ( calling your web-layer or API and checking for what comes out )
- Burn your ORM layer down.
- Have someone who know the business logic sit with you. And re-write the ORM layer from mostly scratch.
- While doing the above, train that person on the very redondant gotcha ( Inverse n to n, accidental carthesian product, bad ID generation, compulsive flush, un-needed @lazy or @eager to deal with performance, @embedded abuse and fucked up SQL schema because of the previous)
- Train all dev on the persistence lifecycle of stuff in JPA. "No, most likely you won't have to call .persist or .merge yourself" being the bottomline
- Have a shiny documented exemple of 1 to 1, N to 1, N to N examples ( both with or without inverse link )
- If some report or API needs a fucked up SQL query with 18 join. Write that thing in native SQL and shove it in your DAO. You don't need to mess up you'r whole DAO layer for those 3 queries
- Pray
- Run the test from step 1.
--- TL;DR : if the ORM layer is somewhat clean. you can mostly forget about it. On the project I'm on now, I did not had to touch it more than once in 2 years. ( and that was terrible, granted, we touched a test and stuff that had nothing to do with it started to blow up. But still, once in 2 years is not a lot )
Could you please elaborate why will this end up happening?
I've been on projects that had ~50 active contributors. All of them used plain SQL queries and used a library (don't remember which) only to map columns to Java types. Everyone understood table structure they were working on and its relationship with other tables. If they introduced a new query they were expected to run 'explain plan' first to understand the consequences and change the query if needed. I won't deny that it all needed a bit of shepherding by the senior engineers but the overhead was negligible. As an upside every developer was always up to date with the schema and precisely knew the performance consequences.
The mess you state is perhaps a byproduct of "get-big-fast" code bases?
E.g. Query A retrieves an Author and a count of all the boks he has written. Query B retrieves an author and the title of the most recent book he has written. I see following options: - make two models, one for each query -> leads to a lot of similar models and code-bloat - make a base query and fetch additional data with an additional query -> leads to a lot of small queries that would sometimes be more performant as a single query
The logical objects are hierarchical and serialize easily to JSON and back, making it simple to write REST interfaces. There are a couple of production teams making good use of it.
Github repo is here; feel free to contact me about it: https://github.com/zeidon/zeidon-joe
Just get something like JDBI for the row set to POJO mappings.
For instance selecting just the fields you need is relatively simple with JPQL:
SELECT i.url FROM Image i WHERE i.id = ...Developers look like JSON looks like, what we send to browser, what formatting it has, validation and size of JSON data, as it's easy to monitor and trim.
Can't say the same about Hibernate. How the hell even hibernate caching works? Why even are there 2 levels of Hibernate cache? It's too easy to create and abuse transactions. Dirty-checking is JUST WAYYYY TOOO EAZY TO ABUSE. not calling, using setter of an instance shouldn't update in database by default omg, It shouldn't be possible for transactions to leak outside some easily specified scope - I've seen one project where transaction leaked to Jackson!! Jackson was calling getters on fields and executing DB queries. JSON ended up as 2.6Mb instead list of 10 fields.
Hibernate is popular because we don't need to learn SQL to get needed data, but it's also super hard to get it right and don't do something stupid by accident.
If in any doubt, refer to JOOQ - it's the SQL-oriented ORM for Java.
https://docs.jboss.org/hibernate/stable/orm/userguide/html_s...
> using setter of an instance shouldn't update in database by default omg
This doesn't happen.. the database won't update until you ask the entity manager to persist the entity.
> I've seen one project where transaction leaked to Jackson!! Jackson was calling getters on fields and executing DB queries. JSON ended up as 2.6Mb instead list of 10 fields.
I suspect you might not agree, but JPA lazy loading is one of the easiest concepts to understand. However, I'd argue that leaking your database models to the view is a mistake to begin with and said application is already incorrect.
> If in any doubt, refer to JOOQ - it's the SQL-oriented ORM for Java.
Both the author/maintainer of jOOq and Hibernate agree that each has their place.
I really am amazed at developers that don't take the time to learn about the tools they use.
Doesn't this happen through automatic dirty checking?
I think this is plain wrong, or I might have been very lucky with who I work with: if anything I think most people I work with learned JPA or other ORMs long after learning SQL.
Hibernate is how to get data into Java. And we still have database scripts, migrations to new versions and what not.
I saw a similar problem with some old codebase where I work. There is some Velocity templates that shows information stored on database entities (yeah... bad idea). And sometimes, we got some mysterious errors about transaction closed. Well... Results that Velocity calling the getters of these beans, can trigger a JPA/Hibernate query to get some additional data that has been loaded before. And this could happens after we close the database transaction.
There has to be ways around that though, perhaps using a duplicated domain of DTOs or coercing the ORM to use constructors or private setters to keep encapsulation and invariants.
Value classes like @Entity shouldn't have the responsibility to enforce those business rules.
We can disagree on which way is more object oriented though.
> I love open source, really, but big companies sponsoring open-source projects get most of their income from support or third party tools.
I work for VMware and consequently take some interest as to how my salary comes into being.
If you think VMware makes "most of its income" from supporting Spring, then I think I'd encourage you to spend some time at the investor relations site[0] reading any of the annual or quarterly reports. I'd advise the same for Oracle and Red Hat/IBM.
[0] The advice to use emails or SSNs as primary keys, though: yikes.
VMware is a huge company with its fingers in many pies, but I suspect if you rewrite the sentence as "most of their income attributable to that open-source project" then it would be true of such companies. Presumably VMware sees a return on investment for its sponsorship of Spring (otherwise why do it?); if that's not coming via support or non-free tools that build on Spring then where is it coming from?
Put another way: I don't think Spring makes money. It makes making money easier.
I use JPA/Hibernate for most writing and inserts. It helps a lot when you're dealing with aggregates with child and child entities. It would be a nightmare to track all changes myself and try do manually do what the ORM is doing for me. Deleted a child of a child of an aggregate? No problem, persist only that.
I've started to separate my JPA/Hibernate entities from my domain models as well, and it looks promising. There's some more mappins, but my domain won't be polluted with database concerns.
Then I use jOOQ for almost all reading of data, reading into custom read models that fit the view they are supposed to be shown in. No problem doing multiple joins or other stuff that would give you an immediate headache when trying to solve using JPA/Hibernate.
The beauty of dependency injection is it did more to make Java a functional language than Java8 with lambda notations. That pretty much eliminates the need for pure OOP, which JPA attempts to imitate. In reality JPA + JTA is a pretty awesome combination and avoids the stupid OOP paradigm.
Again. Argh. I would write a response blogpost, but argh, apathy for the orm pattern.
Mutable datastructures with default constructors and setters: yes, mutable entities suck. Unfortunately SQL is fundamentally built around mutable entities. Every field of your POJO is writable because every column of your database is writable. The impedance mismatch is big enough already without trying to make objects that behave differently from your database. Yes, an object shouldn't just be a datastructure with methods; unfortunately an SQL table row is just a datastructure, and classes are the only mechanism Java offers for representing such a thing. Same for mutable collections.
Reflection (which is the reason classes must be non-final): again, sucks, again, the only way to do something like this in Java.
Lazy loading is wonderful. Put your session in your view, write a normalised set of entities that actually model your domain, and get on with your life. Don't worry about the details of what loads when unless and until you have to.
Those who don't understand Hibernate caching are doomed to reinvent it poorly.
Don't use your database as an API. Yes, Hibernate/JPA needs to own your database. That's as it should be. SQL databases are way too complex to be shared between independent applications.
Do you really think people who can't be bothered to learn and understand Hibernate properly are somehow going to take the time to learn and understand "vanilla SQL"? Why?
None of the problems listed here are problems of JPA/Hibernate. They're problems of SQL databases which are surfaced through JPA/Hibernate, but if you skip out on JPA/Hibernate you still get exactly the same problems (maybe in a slightly less recognisable form). The real solution is to stop using these overrated datastores, but if you must use them then JPA/Hibernate is the least-bad way of doing so.
>>> JPA/Hibernate is still the best way to actually produce working applications if you have to use an SQL database for some reason...
This statement makes me think that you either do not prefer to use SQL RDBMS, don’t have to use them very often, believe they are some dusty piece of tech, or all of the above when my experience has me believing that RDBMS are absolutely the most common persistence layer I encounter in JVM, .NET, PHP, and Python codebases.
I don’t think I’ve ever heard a senior JVM based engineer proclaim that JPA/Hibernate are “the best way... to produce working applications”. It simply isn’t. For basic CRUD applications you will AT BEST barely write fewer lines of code with JPA than with native JDBC queries and ResultSet mapping and have all the lock-in and performance drawbacks of JPA.
Lazy loading will inevitably wind up with Session scope problems with any kind of concurrency, forcing nasty internal list enumeration to force a faux eager fetch to work around the problems.
Fetching just the columns you need for a particular projection will have you writing either SQL or Hibernate “SQL” in annotations.
If you have a mix of JDBC and JPA in a codebase you will inevitably wind up with enough consistency and visibility issues as to either ditch one of them or ditch the entire codebase.
Vanilla SQL is so pervasive and CRUD operations are so simple that I would have serious doubts about the credibility of a JPA proselytizer that didn’t know SQL.
I expect every single one of my backend engineers (on any tech stack) to understand the fundamentals of SQL INSERT, UPDATE, and DELETE statements.
Understanding INSERT, UPDATE, and DELETE doesn't help you very much when you have to persist changes to a single child entity of many in an aggregate (parent entity). How do you track which child has changed? Or if a new child is added? Or one is deleted? Or what if the relation is a child of a child of the aggregate, which might very well be the best way to model your domain.
In these situations, Hibernate/JPA will help you a lot! If you're doing it using plain SQL/JDBC, you'll probably end up writing your own mini ORM, and/or polluting your domain with database concerns. (I do keep my Hibernate entities separated from my domain.)
And everyone knows them. It is just absurd to talk about Hibernate as a way to avoid learning to write insert, update and delete. That is made up issue. That is like claiming that people who dont write getters and setters dislike them because they did not learned how to write them.
I dont know whether this claim is a manipulative attempt to try to insult people who like framework you dont or what. But it is ridiculous.
Popular doesn't mean good. I have to use SQL RDBMS a lot, and I respect the amount of low-level engineering work that has gone into them, but yeah I do hate using them.
> I don’t think I’ve ever heard a senior JVM based engineer proclaim that JPA/Hibernate are “the best way... to produce working applications”. It simply isn’t. For basic CRUD applications you will AT BEST barely write fewer lines of code with JPA than with native JDBC queries and ResultSet mapping and have all the lock-in and performance drawbacks of JPA.
I don't think seniority is a good metric, but I've got 10+ years of professional JVM experience for what that's worth. Using JPA means you'll write significantly less code, and the code you get to skip is the most tedious (and therefore rarely read or reviewed) part. Lockin is significantly lower: you can seamlessly migrate between databases in a way that you can't with handwritten SQL, and you can migrate between different JPA implementations with minimal work (not that I think there's actually much value in doing that, but the capability is there). Performance for equivalent effort will be significantly better because you've got a caching layer that actually works already in place (unless you turn it off, but, uh, don't do that).
Of course if your CRUD application is performance-critical enough to justify hand-tuning every query and implementing a correct caching layer by hand then you'll do better without the framework. But realistically that's a vanishingly rare case.
> Lazy loading will inevitably wind up with Session scope problems with any kind of concurrency, forcing nasty internal list enumeration to force a faux eager fetch to work around the problems.
Depends on your application - a lot (not all, but a lot) of systems decompose naturally into a sequence of isolated steps that provide a natural session boundary. E.g. for a REST API or MVC-style webapp just put the session in the view and get on with your life - people have some philosophical objection to this but it works really well. (I actually don't think MVC is a great way to structure a webapp, but that's a separate fight).
> Fetching just the columns you need for a particular projection will have you writing either SQL or Hibernate “SQL” in annotations.
True. But, on the assumption that you've actually structured your entities to follow your domain, how often is that something you actually gain a significant amount of performance (or anything) from?
> If you have a mix of JDBC and JPA in a codebase you will inevitably wind up with enough consistency and visibility issues as to either ditch one of them or ditch the entire codebase.
This I completely agree with (at least for people who don't make any actual effort to address the problem), and I think it's where articles like the OP come from. I see a lot of people follow a pattern something like: their application needs some vaguely tricky query, and rather than spending 5 minutes looking up how to do it in the Hibernate documentation they decide to handwrite the SQL for it instead. Then they realise that this makes the Hibernate cache for the affected entity invalid, and rather than look up how to selectively invalidate the cache for the entities affected by their query they disable the cache globally. Then they complain that Hibernate is slow and decide the solution is to handwrite the SQL for other queries instead. JPA works great, but only if you're willing to actually try to use it.
> I expect every single one of my backend engineers (on any tech stack) to understand the fundamentals of SQL INSERT, UPDATE, and DELETE statements.
Ah, but that isn't actually enough. The people talking about getting better performance from handwriting your SQL are people who understand different types of indices, different join strategies, how the query planner chooses which one to use. And if you put the same amount of time and effort into understanding Hibernate, you can get great things out of it.
I was careful to choose popular, and not project opinions about SQL/NoSQL/etc. In my field, most of our data is relational and we use NoSQL for caching, queues, shared work, ETL performance, dashboards, etc. but at the end of the day for persistence, the RDBMS is where the “gold copy” data ends up.
As you mentioned previously, knowing the tool set and the domain is critical to either approach. At a certain point with technology the benefits and costs are weighted by subjective preference and project specific needs. I have weighted SQL higher than JPA by many factors because I can take my SQL knowledge to any backend project, and I’ve been a part of a lot of different tech stacks in my career.
Maybe my travels have lead me to be surrounded by many more engineers that trust the database (and their knowledge of the database) to handle the persistence without a too many layers in between.
I, personally, have never seen a JPA based project that actually worked well with large-ish datasets, high concurrency, or when non-trivial ETL functions are part of the system- and this general domain has been the majority of my career, so I may have blinded myself to THE majority being confused for MY majority.
Thanks for the response and a good look at the topic from a different point of view.
I strongly disagree with this for a few reasons. I actually think the command-oriented way is makes the most sense. The problem with in place updates is that:
- Your queries aren't views. What you queried out of the DB is a snapshot of what is in there. It may already be different. - The way you interact with a DB is command based. If you want to update a row that is a command that may fail.
The only way I feel that using mutable data would make sense is if you had some sort of 2-way syncing. But those are notoriously difficult to get right even without network trips in the middle.
> Do you really think people who can't be bothered to learn and understand Hibernate properly are somehow going to take the time to learn and understand "vanilla SQL"? Why?
Yep, that is exactly what I think. People who know Hibernate know also SQL. People dont bother learn, dont know either. And then there are people who know only SQL, because they worked on projects without Hibernate. They typically learn Hibernate fast.
Because JPA is a magnitude larger space to learn than just SQL.
Or more precisely: using Hibernate in simple applications (CRUD) will cause you issues very soon (sessions missing), some magical saving of data when you a set, doing filtering in streams (and now you take too much fields).
Doing the same with SQL (using JDBC or something like JDBI) won't cause that for simple apps.
Every field is not writable in a database. There’s often constraints that restrict how fields can be updated. Requiring setters for all fields breaks that contract.
> Reflection (which is the reason classes must be non-final): again, sucks, again, the only way to do something like this in Java.
It’s the only way if you insist on having the entities track their own state changes via point in time snapshots. If they represent the changes themselves there’s no requirement for reflection.
> Lazy loading is wonderful. Put your session in your view, write a normalised set of entities that actually model your domain, and get on with your life. Don't worry about the details of what loads when unless and until you have to.
In the real world the lazy loaded view get tested with one widget loading five wozzles, then in production it’s one widget loading 5000 wozzles, each performing a separate query to hydrate its state.
> Those who don't understand Hibernate caching are doomed to reinvent it poorly.
Hibernate’s caching model manages to be both incredibly complex and incredibly limiting. Short of careful usage with an external store, it’s nearly impossible to scale across multiple JVMs. And even then it pushes the complexity to the cache.
> Don't use your database as an API. Yes, Hibernate/JPA needs to own your database. That's as it should be. SQL databases are way too complex to be shared between independent applications.
(Emphasis mine)
On the contrary, a well designed database can and will have many separate applications I retracting with it. All the more reason to have the database reflect the true constraints of the system.
> Do you really think people who can't be bothered to learn and understand Hibernate properly are somehow going to take the time to learn and understand "vanilla SQL"? Why?
The complexity of learning SQL is grossly overstated. Plus it translates as skill to all other languages and programming environments. On a purely economic basis it’s a better choice for an individual to learn SQL over Hiberate/JPA.
> None of the problems listed here are problems of JPA/Hibernate. They're problems of SQL databases which are surfaced through JPA/Hibernate, but if you skip out on JPA/Hibernate you still get exactly the same problems (maybe in a slightly less recognisable form). The real solution is to stop using these overrated datastores, but if you must use them then JPA/Hibernate is the least-bad way of doing so.
I think the ultimate example of how bad JPA can be is JPQL. They managed to take the worst aspects of everything, and then not just add them together, but multiply them!
There are, but there's no metamodel that exposes them. All you can do (in a generic/programmatic way) is attempt a write. A particular write may fail because of constraints, but this gives you no information (except in ad-hoc database-specific ways) about what kinds of writes might succeed.
> It’s the only way if you insist on having the entities track their own state changes via point in time snapshots. If they represent the changes themselves there’s no requirement for reflection.
Sure, but that creates a major impedance mismatch. In SQL databases the current state is first-class and changes are very much seccond-class.
> In the real world the lazy loaded view get tested with one widget loading five wozzles, then in production it’s one widget loading 5000 wozzles, each performing a separate query to hydrate its state.
Sure, and then you take 5 minutes and actually profile it, actually read a little bit of the hibernate documentation, and fix it. I find it strange how for most kinds of technology the accepted wisdom is that you should take a bit of time to understand its behaviour (indeed the article says as much regarding SQL), but for ORMs the conventional wisdom is that at the first sign of trouble you should throw the whole thing away.
> On the contrary, a well designed database can and will have many separate applications I retracting with it.
It shouldn't. You are virtually guaranteed to get deadlocks (even in a single application deadlocking is easy - you need to have clear rules about which things can be locked in which order and all queries need to abide by them), updating your schema becomes essentially impossible because you can never know what's using a given column or constraint, you can't make use of temporary tables because it won't be clear what owns or is responsible for them, validation has to be done in the database which makes it very difficult to unit test or deploy (and good luck getting your test environment to look like your prod environment if you have to co-ordinate between n different applications)...
> The complexity of learning SQL is grossly overstated.
The complexity of learning Hibernate/JPA is grossly overstated too. Seriously, it's not that hard if you actually try.
—Gavin King, creator of Hibernate
Source:-
https://twitter.com/markuswinand/status/456827165938434048?s...
I use jOOQ as well, but mostly only for the reading part. For the above case, I still use Hibernate, as I've yet to find an efficient way to do it in jOOQ.
> I WANT to solve business problems, I do not want to keep solving technical issues.
It is interesting how emotionally invested we become with our tools. Yet we don't have infinite time to become productive with all possible frameworks. So we have to specialize at least somewhat.
As to JPA itself, I agree that it's generally a bad fit for most uses. Circa 2010 I used it with Java Enterprise in the hope that an failed bean could be recovered by a parallel worker, but the technical costs were crazy high. And often I had to drop to raw SQL anyway. Less invasive ORMs can still be more generally useful, and remove some tedium.
We use Clojure and yesql (a library where you write sql queries directly in .sql files and the library generates functions for you). The devops noticed one of our queries was slow and taking too much DB resources. He sent us the query which we promptly found and then asked us if we could change it to a more performant version he just wrote.
We took his query, just replaced in our sql file and deployed. 10 minutes later he came back saying things look much better and the query update really helped.
I wonder how much time it would take if we were using JPA/Hibernate as we used to, many years ago.
"Frameworks do not keep retro-compatibility"
I would argue that is a good thing and in the case of Spring, doesn't feel true. In part, Spring is so hard to learn because it has too much support for legacy stuff (though this may have changed in the last few years).
The only issue with not supporting retro-compatibility is because the JVM doesn't support retro compatibility. I recently tried to upgrade an application to the latest version of Java (I think it was Java 12) and found that date formaters were completely changed to match an ISO standard which broke a lot of code. We also found a similar problem with the Java 8 transition as well forcing a huge upgrades to our libraries.
I am of the view that libraries and frameworks should support not support retro compatibility but the language should. This way, if you don't want to upgrade your library then you don't have to.
Using the web as an example, old Angular JS applications still work today as they did back when they were first written. I doubt applications written in the first version of Spring will work with the latest version of the JVM.
Often the fucked up native query end up in a different type of DAO for performance / concurency reasons anyway.
Don't get me wrong, I dislike JPA and Hibernate really much, but that particular aspect has often been one of the less painful to deal with.
Seems like a fair tradeoff.
Years of Django's ORMs has given our app over a hundred tables. Complex and /fast/ queries are next to impossible.
Django's ORM made app development lightening quick for the first developers. And impossible for the ones fives years later.
I can't find an explanation on the Wikipedia or GitHub pages, and whenever I see the name come up on HN my brain does a weird double-take as it goes "Is this an OS hibernation tool--No, it's the Java database thing... does it make objects go to sleep?"
The use case is "you have a collection of objects that reference each other in memory. You want to say: Bam, put that structure like it is into a database ("put it to sleep"), and retrieve it again for me if I need it ("wake it up after winter is gone")."
For this type of ORM Hibernate works fine. If you want to use a database as a database, it resists at every turn.
I feel like hiring process should filter these kind of developers out. At least most of them.
I also think that if they get in, internal processes should limit these developers impact, limit their ability to make decisions. As in their careers should be stagnant and they should not be gaining influence.
In large enterprise projects, I've always had to create custom SQL statements at some point, at which point I'd rather do everything in SQL. Otherwise, you have to know JPA/Hibernate and SQL, which (in my opinion) defeats the purpose.
Now, in Hibernate itself, the no-parameter constructor is not needed. Hibernate supports an "interception mechanism" which allows you to use whatever constructor you like. But that is not part of JPA standards and for most it is simpler to just go standard way.
I do wonder if I will fall into the same trap as complexity grows. But the migrations are just amazing so far. For them alone I want to stick with it.
- Hibernate is using blocking IO and threaded database pools. This makes it a problem if you want to use non blocking web frameworks. Like Spring's web flux. You should consider it a legacy technology for this reason alone. There's a good reason why there is no drop in reactive replacement: modern frameworks are trying to not repeat some of the design problems with hibernate (see the article for an overview of those).
- It comes with its own category of hard to diagnose and fix bugs. I've been on more than one project where I had to clean up other people's messy transactional logic. One symptom is people copy pasting @Transactional everywhere as if it was some kind of magical incantation that says "dear db gods please just make this work consistently". A second symbol is flaky tests where that clearly is not working as advertised. A lot of this relates to things like aspect oriented programming and reflection which are what hibernate uses to generate byte code at run time.
- For the same reason, hibernate is also a problem if you want to natively compile your code via e.g. Graal. Reflection and byte code generation are problematic for that. The less you have of that, the better.
- For the same reason, hibernate is also inappropriate if you need fast startup times (which would be why you'd consider native compilation). For example because you are doing server-less designs or edge computing. Having 10-15 seconds of startup overhead is not great. Warming strategies can mitigate this somewhat. But honestly, there's no good reason for Java servers to take much longer to start than it takes the JVM to start (which is still around a second or so). As soon as you get rid of hibernate, Spring Boot startup times become a lot more reasonable. If you then switch to using it's bean DSL (as opposed to scanning packages for annotations), it gets better still. Most of what Spring does at startup is millions (literally) of calls into various reflective methods. That's why it takes so long.
- Object impedance mismatch. Designs that need an ORM layer might not be that optimal. I've been on multiple teams where people got carried away a little too much with e.g. overusing inheritance and coming up with complex solutions to make the database mirror the class hierarchy. The result is dozens of tables and dozens of joins on read. I've seen GET operations that had 1500ms response times because of this. It's stupid. It's stupid even after you fix all the silly joins, missing database indices, etc. You can do good database design with hibernate of course. If you understand how to do that, hibernate is just another tool and not a particularly critical or important one. I've removed it on a few projects to simplify the design.
- These days it is valid to treat databases as document stores. Once you refactor a 15 table database to be the 3 tables that you really needed all along, most of Hibernate is just not needed. My golden rule is that if I don't query on it, I don't need (or want) separate tables or columns for it. Nothing wrong with storing some json blobs. I love using databases because they are fast, transactional, and come with some strong consistency guarantees. Hibernate is not a great fit for document databases. It assumes your domain consists of columns and tables and it wants to do clever things with joins to make that seem like an object tree. The best join is the one you don't need. That's why document stores can be so nice.
If I had to do a green field project, I'd probably go for R2DBC with Spring or maybe one of several other Kotlin reactive database frameworks in combination with ktor, http4k or one of the other emerging Kotlin server frameworks. All my recent projects are using spring web flux and Kotlin co-routines in any case. So, using something non blocking is a hard requirement for me.
But if I had to use hibernate, using Kotlin is the way to do it. It shovels most of the ugliness under the carpet via compiler plugins. So you can use nice immutable data classes and let the kotlin compiler worry about adding default constructors, opening the class and adding getter and setter cruft just so hibernate can do its runtime magic. Also it removes all of the need for hacky things like Lombok and its gazillions of additional annotations. Hibernate can be a lot less painful if you just do it properly. But not using it is better still.
JPA/Hibernate does not require getters and setters. Fields can be used directly for ages (more than 10 years).
The arguments against reflection are pseudo arguments, because the developer doesn't use reflection himself where usual programming language means would be better. Instead the framework uses reflection to free the developer from writing boilerplate code - completely different things!
The claim that it would be impossible to return unmodified collections because one would be forced to provider getters and setters is wrong. If Hibernate uses the fields directly, it is no problem to give only an unmodifiable view of a collection to the outside.
I don't see a general problem with lazy loading. You have to understand what you're doing, but that should be the case with every framework. Hibernate is quite flexible with eager and lazy loading and it is possible to specify an entity graph per use case to say Hibernate what to load eagerly and what not. Another possible is to use dedicated query objects (usual entity classes mapped to the same table, but designed for a certain use case).
The section about "Accessing a single table field" ignores the fact that the object mapped with Hibernate could also only use the needed fields. You could even select a single value with JPQL without any domain class involved. This argument is kind of dumb and wrong.
"Constraints" with Bean Validation are not a core part of Hibernate and shouldn't really be in this article. But, as they are already there, let me say that the criticized "too late" enforcement of the specified constraints is only the default behavior (because Hibernate can not know when to perform the check). Nothing prevents you from performing these checks explicitly with the means of the Bean Validation API. But apart from that, I'd prefer to write this kind of rules as usual code, too.
"Framework updates are horrible": I had never a severe problem switching to a new Hibernate version. Same is true for Spring (but wait, why does this article mention Spring at all?).
"Rename your JPA Repositories to JPA DAOs": The author doesn't understand the difference between a DAO and a Repository. A repository is at the same level as an entity or value object, it _is_ a domain concept. BUT the implementation of the repository interface is indeed part of the infrastructure, but this implementation would reside in another package. There is no need to name "repositories" always "repository" - if you want to name the class "BankAccounts" then do so! By the way: the class name "BankAccountsJPAImpl" is a crime!
The advice to generate IDs in your own implementation is kind of silly. "if an id is generated, it should be done knowingly" Why? Usually an ID is just a number with no special meaning other than being unique per entity type. Even if you'd decide to drop relational databases and use advanced CSV files instead the sequence number generation could easily be implemented then. And why on earth should one want to test the sequence number generation? I trust every solid database to be able to generate perfectly fine sequence numbers!
The section "Stop adding multi-directional association" has nothing to do with Hibernate specifically, because that is some kind of general design consideration.
One big question remains unanswered by this article: What is the alternative? The author implicitly suggests that it would be SQL. But things are not so simple. If you want to have a domain model (and not a mixture of domain logic and technical infrastructure), you not only have to load data from the database and create objects from it (the easy part), but you also need to find out what data needs to be written to the database after business operations were performed. I'm not aware of a simple solution here (but let me know ...). There are other things like optimistic locking where Hibernate simplifies things a lot.
All in all the article is not well balanced and flawed.
In my previous job we used Java and the benefits were a huge ecosystem of libs and tools, plenty of monitoring tools, a ton of expertise and people who understood its memory model and quirks and were able to troubleshoot production problems. The JVM is rock solid and has great performance for backend with lots of transactions.
I'm not experienced with Go, Python doesn't seem particularly suitable, and server-side javascript looks like a nightmare to me.
NodeJS seems crippled to me.
But I find that most people who say that it has "great performance" have not built a parallel implementation in JS, Go, Rust, or even .NET Core. I'm omitting memory unsafe languages by default and Python here, because I think that's the domain Java competes in, and Python lacks the investment these other languages have in performance.
The lack of value types and the amount of pointer chasing that JVM languages do as a result, the way generics are implemented via type erasure (which the JIT then has to re-optimize), and so on usually mean that CPU and memory usage for the same throughput is much higher than a competing implementation in a different language. And on older JVMs, tail latency will be orders - plural - of magnitude worse.
It is absolutely true though that for most workloads that efficiency isn't necessary and the ability to reuse that ecosystem reduces time and cost to develop. But it's just definitely not true that Java has "great performance" and I don't think that's ever really been true.
I haven't tried any of those, but saying the JVM can't run JS is not true.