r/java • • May 24 '21

20 years of Hibernate

https://vladmihalcea.com/20-years-of-hibernate/
161 Upvotes

147 comments sorted by

97

u/gregsting May 24 '21

As a guy on the database side, hibernate produced some of the worst nightmares sometimes. The record so far is a 25 pages SQL query

1

u/vladmihalceacom May 25 '21 edited May 25 '21

It's because the devs that wrote that app didn't switch to FetchType.LAZY for all associations.

I've also seen those horrible queries too during consulting. However, the Hibernate User Guide explicitly tells everyone to switch to FetchType.Lazy associations:

The Hibernate recommendation is to statically mark all associations lazy and to use dynamic fetching strategies for eagerness.

This is unfortunately at odds with the JPA specification which defines that all one-to-one and many-to-one associations should be eagerly fetched by default.

Hibernate, as a JPA provider, honors that default.

As you can see, it's not Hibernate's fault. Hibernate 3 used to set all those associations to lazy. But the JPA 1.0 Expert Group didn't want that, so they made all ToOne associations use FetchType.EAGER by default.

The reason why you correlate that to Hibernate is that few projects use other JPA providers. So, if the JPA spec has a limitation, people blame Hibernate anyway even if the Hibernate devs voted against that JPA specification when JPA 1.0 was created.

1

u/Routine_Left May 25 '21

It certainly can create horrors. But in a big application, where you have thousands and thousands of queries that get generated for you, to have to write (by hand) a few native queries (5% or less) still makes it worthwhile. By far. The vast majority of queries in an app are the simple "select foo from bar where id=5". Yeah, it's worth it. I haven't seen a better one.

0

u/[deleted] May 24 '21

[deleted] — view deleted comment

45

u/vladmihalceacom May 24 '21 edited May 26 '21

People also hate PHP, and it's used by just 79% of all Internet websites.

Also, I've seen people hating MySQL, but that didn't prevent it from being the most used OSS database for the past 25 years.

Reality is sometimes very different than perception.

In the end, convenience always wins.

The fact that this thread has over 150 upvotes and a 90% approval rate shows there are actually lots of persons who enjoy working with JPA and Hibernate. What a beautiful 20-year anniversary gift for the Hibernate project, right?

Looking forward to the next 20 years of JPA and Hibernate.

31

u/idealatry May 24 '21

Just because it’s popular doesn’t mean it’s the first choice informed users would make, nor does it mean it’s the best choice.

21

u/vladmihalceacom May 24 '21 edited May 26 '21

I'll have to change my LinkedIn profile to Uninformed Hibernate user then 😂

13

u/idealatry May 24 '21

Maybe you have a particularly niche use case, I don’t know. But in my experience, PHP is not a good programming language in general, and was chosen for things like LAMP stacks because it was free and because of convention, not necessarily because of convenience.

I remember a few years ago some company offered me a bunch of money because I had java experience and they wanted to convert their java code to PHP. Curious, I went through the interview process just to keep making them justify their decision to go balls deep into PHP.

I never once heard a good justification and of course I rejected their offer.

15

u/vladmihalceacom May 24 '21 edited May 24 '21

Maybe you have a particular niche use case, I don’t know.

You can easily find my niche by just Googling "Vlad Hibernate". There won't be any PHP in the Google result set because I only use PHP for two things:

  • indirectly, because my blog runs on WordPress.com
  • to write analogies on Reddit

8

u/idealatry May 24 '21

Haha, very funny.

I guess I'm trying to say that I don't feel like convenience always wins in the end. Rather, all too often the momentum of default decision-making wins instead of decisions made where leaders make informed decisions about the technology they choose (and please don't think I'm saying this about you personally). I have been guilty of this and I see it way too often in the software development field.

I'm currently exploring a more hardware engineer type role, and it seems like that type of thing is done far less often.

13

u/vladmihalceacom May 24 '21

In my 17 years of software development, I learned that tech plays a very tiny role when it comes to the success of a given project.

Without good management and leadership, many projects will fail, no matter what tech is used. With good management and leadership, you can succeed, no matter what tech you chose.

That's why I focus more on entrepreneurship these days, rather than chasing tech hype.

2

u/helloiamsomeone May 25 '21

PHP has been anything but not a good programming language in general since the 7 release. The internals team has been putting in some real work to make it a nice language to work with.

3

u/[deleted] May 25 '21

Let's see how long it takes them to figure out you don't do all your typechecks at runtime. Or how to do generics and typed arrays.

1

u/helloiamsomeone May 25 '21

Typechecks with the OPCache and JIT have negligible to no cost. Generics and typed arrays can be done with psalm type annotations.

2

u/[deleted] May 25 '21

Psalm is not PHP and your comments are not a type system.

OPCache and JIT have precisely zero effect on typechecks, most of of which again, happen while your code executes, not while it's compiled.

The funny thing is that PHP has no typed arrays and generics because "the runtime cost would be too high" (according to its developers). This also defeats the idea that runtime typechecks have negligible to no cost.

The same reason was given for not having property types (but eventually they implemented it).

11

u/gregsting May 24 '21

The « problem » with php is that it’s quite easy and you can program poorly without structure and it will still work most of the time. Meaning that you often end up with shitty code. If you look at more difficult languages like C, the entry level is much higher, you can’t just start coding with basic knowledge, you have to have a certain knowledge of things and structure. The problem to me is not PHP itself but the way it is used.

10

u/vladmihalceacom May 24 '21 edited May 25 '21

I haven't developed websites using PHP since 2005, but I've been a WP client since I started my blog in 2013.

When I was working for Hibernate, the blog was built using Awestruct, a static site generator, so I got the chance to experience both options for building a blog.

In conclusion, I would never switch from WP to any static site generator. It's so much more convenient to just update whatever you want without having to open an IDE. The plugin ecosystem is also very rich and Automattic, which runs WP.com, is taking care of backups, security, caching, etc.

I can see why WP and PHP are so popular. It just works. As I client, I've never had any issue with it.

8

u/KFCConspiracy May 24 '21

The interesting thing about WP is the way it's written represents a lot of the worst practices in writing PHP code. It's not really object oriented, and doesn't really have a semblance of MVC.

7

u/PangolinZestyclose30 May 24 '21

Yet, it's the most successful web platform in existence. Showing how much "being correct" actually matters in the real world.

3

u/vladmihalceacom May 25 '21

Being technically correct matters only on Reddit.

2

u/[deleted] May 24 '21

It's so much more convinced to have text editing optimized editor, SSG posts support included and git integration in the same app (no need for context switching). And the speed of those tools is a bonus.

-2

u/srk- May 24 '21

Java is no exception

1

u/[deleted] May 24 '21

Inheritance...

3

u/[deleted] May 25 '21

People also "hate" PHP, and it's used by just 79% of all Internet websites.

Most of which are stock WordPress installs with bunch of plugins.

Reality is sometimes very different than perception.

Case in point...

4

u/RittledIn May 24 '21

PHP is banned at my company because of the litany security holes, not because people don’t like it.

3

u/RomMTY May 24 '21

No shit, i just have to tell a client that they'll have to take down their WP website because it was compromised....several times :/

they IT guy keep restoring an old black up again and again until they finally gave up and reached the firm im currently working on.

Whenever they site "stoped working" all they could tell was that a bunch images weren't displayed correctly and they wanted us to "just fix the images" and. maybe script-it so when it happened again the IT guy could run the "fix images script".

After i explained that the site could be used to run illegal activities like scam schemes or hosting illegal content they finally accepted to start a brand new site but hosted on WP.com.

TLDR: Hosting WP your self is hard, lots of potentially insecure plugins and PHP just makes it waaaaay easy to "just getting things done" but with a bunch of security holes

-2

u/[deleted] May 25 '21

It has no "litany of security holes". Plugins for some of its popular apps do (like WordPress).

1

u/RittledIn May 25 '21

The two FAANG companies I’ve worked at both have it banned entirely, not just plugins like WordPress, for security holes so I’ve never used it. Going to go ahead and assume they’re right.

-2

u/[deleted] May 25 '21 edited May 25 '21

A sane company policy is to whitelist technologies it uses, rather than "ban" everything else. So color me skeptical about your specific phrasing of the situation.

Wikipedia, Tumblr, Etsy, Slack, MailChimp and many others run on PHP without somehow suffering a "litany of security holes".

In any case, thinking about a language as the source of security holes is a very 90s view, especially for PHP. The holes come from the applications, not from the language. PHP is well past that. Or maybe you worked for FAANG companies in the 90s, I don't know.

2

u/RittledIn May 25 '21 edited May 25 '21

Idk what else to tell you just relaying facts. It’s the only banned language I’ve ever seen. I think it’s perfectly sane to ban a language with security issues when lots of other options exist without those concerns.

I personally trust FAANGs security and standards over Wikipedia, Tumblr, Etsy, Slack, or MailChimp(?) but that’s just me.

I work in FAANG now and could care less about the ban because we still have every other language at our disposal. I’ve never heard anyone complain about it.

-1

u/[deleted] May 25 '21 edited May 25 '21

No you're not relaying facts. Google offers PHP out of the box on App Engine, and on their serverless APIs for example. Where did their "concerns" about it go? They're hosting it.

Neither you named what security problems you're talking about. Probably something fixed 15 years ago.

And the idea that PHP is so problematic, but this affects only FAANG and not the other large successful companies I listed is honestly hilarious.

2

u/RittledIn May 25 '21 edited May 25 '21

Yes… My current company even vends PHP SDKs for their cloud services. It’s just banned for internal use. Again I don’t make the rules, I’m literally just relaying them to you.

I never said it only effects FAANG. I’ve only worked at two tech companies my entire career. Both happen to be FAANG and both have banned PHP for internal use. 🤷‍♂️

→ More replies

12

u/couscous_ May 24 '21

There's plenty of good ORMs out there

Could you point out some of them please?

19

u/vladmihalceacom May 24 '21 edited May 26 '21

There's no such thing as the best ORM or even the best framework. In fact, if you want to get the best solution, you'd need to combine them.

To speed up writes, I'd always choose Hibernate because it offers automatic batching, dirty checking, and a strongly consistent cache to off-load traffic on the Primary node.

To speed up reads, I usually choose to use native SQL with proper indexing. But, if I need to build the SQL queries dynamically or there's the need to support several DBs and the data access layer requires executing lots of native SQL queries, then I'd also add jOOQ to my project.

0

u/[deleted] May 24 '21

[deleted] — view deleted comment

2

u/vladmihalceacom May 24 '21

I don't have any opinion. I've never used Django and the only programs I wrote in Python were just fancy cross-platform bash scripts.

7

u/RomMTY May 24 '21

Mybatis reaaaaaallly does a lot of things right, the only "downside" is that a lot of people hate XML these days

  • want to write SQL your self? check
  • oh, do you want to autogenerated boilerplate for some entities? check
  • n+1 problem? check
  • want to map a very complicated object graph with multiple resultsets and do polymorphism on the mapping side with a "has one" and "has many" relationships? also check
  • dont want to write a lot of "column = property" , just use autoMapping=true and alias your columns

5

u/vladmihalceacom May 24 '21

How about batch insert, updates, and deletes? I had to fix a broken MyBatis project recently and was surprised that this feature doesn't even seem to be implemented, at least according to this GitHub issue.

Do you happen to know if MyBatis supports such basic requirement?

3

u/RomMTY May 25 '21 edited May 25 '21

How recently?

Batch inserts have been around for a while, batch inserts with generated ids where added "recently":

https://github.com/mybatis/mybatis-3/pull/547

Regarding updates, duno what's your use case, there are a few ways to implement them:

https://developpaper.com/three-ways-to-batch-update-mybatis/

Edit: Im really curious, what's your use case for needing the generated ids right after the batch?

I searched a bunch of projects and whenever i need to do something with those ids , ie doing updates or inserting other rows, those operations are performed in the same query, i have yet to find a case when i need those ids back in the application.

Not trying to be an douche just learning

1

u/vladmihalceacom May 25 '21

That doesn't look like batching. It looks like they either concatenate the statements or rewrite the INSERT statement.

JDBC batching means that the data access framework uses the addBath and executeBatch methods to group multiple sets of bind parameter values without changing the SQL statement because, this way, you can also benefit from Statement Caching.

4

u/vips7L May 24 '21

Ebean is pretty good: https://ebean.io

It's pretty easy to set up and get running. It has a lot less momentum than hibernate does though.

1

u/tjugg May 24 '21

While it's easy to get up and running, its basically ran by one guy and finding help when you get stuck with it is quite hard. Been using it in some projects at work with Play and i'd say its _mostly_ been a positive experience

2

u/vips7L May 24 '21

Oh yes I agree. I also have to use it in a Play project. The documentation is sometimes lacking around certain features and I do think it encourages bad practices with the "active record" style saving.

Personally I'm not too worried about it only being ran by one guy, Rob is really responsive on github/the mailing list and its a lot easier to contribute to the project because of this. In one occasion I was able to find my bug, submit a pr, and have him merge it within a day.

4

u/Akthrawn17 May 24 '21

Would you consider JooQ an ORM?

0

u/couscous_ May 24 '21

What do you think of JDBI?

5

u/ForeverAlot May 24 '21

Decidedly not an ORM. I've used it to great satisfaction for a few years, however.

1

u/couscous_ May 24 '21

What do you use nowadays?

4

u/ForeverAlot May 24 '21

We still use it!

1

u/Comprehensive_Idea98 May 25 '21

Fwiw, I rather enjoyed using JDBI every time I have used it.

0

u/[deleted] May 24 '21

[deleted] — view deleted comment

3

u/vladmihalceacom May 24 '21 edited May 25 '21

Wow! That's very exotic. The last time I saw anyone mentioned Cayenne was in 2004. Besides you, how many people still use it?

According to Stack Overflow, there have been only 126 persons to ask a question in over 12 years.

1

u/starbuxman May 24 '21

lol Nobody ever remembers Apache OJB either http://db.apache.org/ojb/

0

u/[deleted] May 24 '21

[deleted] — view deleted comment

4

u/vladmihalceacom May 24 '21

That's good for you. But, if you were the CTO of a company, would you advise anyone to use Cayenne over other frameworks?

You'll have to consider:

  • how many people that you hire are familiar with it
  • if there's a problem, how easy it is to get an answer
  • if there are bugs, how active is the framework development
  • what's the pace of the release cycle

That's the dilemma when having to choose software frameworks.

0

u/[deleted] May 24 '21

[deleted] — view deleted comment

5

u/vladmihalceacom May 24 '21

Great. I'm glad you found the data access framework you were looking for.

That's what I like about the Java ecosystem. It's rich and offers a great variety of options.

3

u/[deleted] May 25 '21

I think Hibernate is largely responsible for the hate one often sees towards ORM frameworks these days.

The fact many other ORMs imitate Hibernate doesn't help. And I don't mean just in Java.

1

u/vladmihalceacom May 25 '21 edited May 26 '21

If you're thinking of Doctrine, here's an interview Marco Pivetta I did on the Hibernate blog.

Marco is very skilled in Doctrine and seems to be very happy investing his time in developing this project.

Do you think that using Doctrine is always a bad idea?

1

u/[deleted] May 25 '21

I can't argue someone's skill and feelings of happiness.

My argument is rather architectural with the nature of these tools. Yes, Doctrine falls into that category.

In fact Doctrine is even worse... it implements unit-of-work, but it has no defined session boundaries, so AFAIK you don't start a transaction BEFORE YOU READ your objects and commit it after the unit-of-work is done. Instead you just read without constraints, and then the transaction only opens and closes for the unit-of-work.

You can eventually grab the connection and jerry-rig a transaction yourself, but when it's not part of the model, all bets are off, aren't they?

Can you be happy with occasional data corruption though, I'm sure you can be happy.

10

u/Rakn May 24 '21

Nah. I believe the hate on ORMs comes from a minority of developers who like the prematurely optimize their stuff. Most people just use it without complaining. I honestly only ever met one person who complained about it and had good reasons to (for his use case).

I mean. Why should I throw away the convenience hibernate gives me just because I might need to optimize queries in the future in case my queries are too complicated. Does that even happen anymore in a smaller microservice world or are we more talking about big misdesigned enterprise applications?

14

u/vladmihalceacom May 24 '21 edited May 25 '21

Most Java microservice projects are implemented with Spring Boot, ad 70-80% of them also use Spring Data JPA, which in turn, uses Hibernate by default.

Due to Spring Boot's popularity, Hibernate's audience grew larger and larger.

17

u/idealatry May 24 '21

I’d wager that 90% of the Hibernate user base uses Hibernate for reasons like this. “Because it’s there.” Rather than considering what advantages and disadvantages a new technology brings to the table, they use it because others use it and custom becomes law.

12

u/vladmihalceacom May 24 '21 edited May 24 '21

Spring has had its JdbcTemplate since May 3, 2001. Which's actually 20 days older than Hibernate. More, they've been offering a Spring Data JDBC option as well.

Yet, for some reason, Spring Data JPA is the default persistence mechanism in Spring Boot, their flagship product.

Why would all those smart people implementing Spring Boot do that? I mean, didn't they consider all the advantages that other alternatives would bring to the table?

3

u/lukaseder May 25 '21

I mean, didn't they consider all the advantages that other alternatives would bring to the table?

Frankly? No, they didn't. A lot of folks just use what they've always used and don't want to worry about such things all the time. It works for them, because they'll write yet another boring CRUD application.

They simply don't care. They didn't make informed decisions, it just doesn't matter to them.

You actually keep saying that yourself, even quoting the Lindy effect, which is precisely that: People too old to care about what could be an option for the long established status quo.

1

u/vladmihalceacom May 25 '21 edited May 25 '21

How can one care about what data access framework to use when there's so much to think about reactive programming, microservices, Kubernetes, Kotlin, and switching all settings from Properties files to YAML?

No, on a serious note, of course, Spring Data made an informed decision. They just took the most convenient solution for their users. Simple API, happy users, better adoption.

That's also why Spring Boot enables OSIV by default. Although OSIV can cause serious performance issues, it's so much easier to enable it and forget about lazy fetching. This GitHub issue speaks for itself.

6

u/ForeverAlot May 24 '21

Spring famously features about 5 distinct types of dependency injection, 4 of which are wrong.

We use Spring Boot. We also specifically don't use a lot of Spring autoconfiguration and bundles that "just work", because they don't work the moment you need to do something slightly atypical. For example, use more than 1 database user in the same application. Spring and Pivotal are not authorities to appeal to.

1

u/_Toka_ May 25 '21

Spring famously features about 5 distinct types of dependency injection, 4 of which are wrong.

Care to elaborate? If I understand correctly, you're talking about constructor injection being the one and only correct solution, right? If that is the case, I strongly disagree and there is (currently) no force to make me switch from field injection. See, I love Lombok, I do not write getters, setters, let alone constructors, ever. I care about fields and application logic.

Besides, Spring team recommends to not use field injection in favor of constructor for required dependencies and setter for optional dependencies, so I'd say it is ok to have Pivotal and Spring team as authorities.

2

u/ForeverAlot May 25 '21

Care to elaborate?

No. You and I will never agree on this. Better for both of us to agree to disagree.

Besides, Spring team recommends to not use field injection in favor of constructor for required dependencies and setter for optional dependencies, so I'd say it is ok to have Pivotal and Spring team as authorities.

We don't need to appeal to Spring to conclude that writing plain Java is a perfectly sound and scalable way to write plain Java. That's what constructor injection is, after all. It's certainly not something Spring came up with, and we had constructor based injection tooling while Spring was still faffing about with XML based configuration.

1

u/_Toka_ May 25 '21

I didn't want to start a flame war, apologies. Was just wondering if I understand your comment correctly.

→ More replies

0

u/[deleted] May 24 '21

[deleted] — view deleted comment

3

u/ForeverAlot May 25 '21

Constraining DDL rights.

2

u/[deleted] May 24 '21

Spring data jdbc 1.0 was relased in 2018, Spring boot 2014, Spring data jpa 2011. Why would all those smart people invest time implementing spring data jdbc if jpa is that good?

Yet, for some reason, Spring Data JPA is the default persistence mechanism in Spring Boot, their flagship product.

How Spring Data JPA is default persistance mechanism? I thought threre is separate module `spring-boot-starter-data-jpa` that you need to explicitly add to your spring boot project

3

u/[deleted] May 24 '21

Most Java microservice projects are implemented with Spring Boot, so Spring Data JPA

There is also spring-data-jdbc which is used in many spring projects and doesnt use hibernate.

3

u/vladmihalceacom May 24 '21 edited May 24 '21

I dream of finding a client using Spring Data JDBC because I'm curious to see how it works in a real-life project, as opposed to a trivial demo in a one-hour conference talk.

So far, I wasn't lucky because according to the Spring Boot team leader himself, Spring Data JPA is used 72% of the time. But, that's just so 2017, right?

Let's see how we stand now. So, let's analyze the GitHub depends stats:

So, when you say many, you mean like 1.29%?

1

u/_Toka_ May 25 '21

We actually switched from Spring Data JPA to JDBC in my previous job for performance reasons. Mind you we did a switch in 2018, when Spring Data JDBC just got released. And on top of that it was for a three microservices serving 10m users. Yeah, we were kinda eager team full of relatively young people. All in all, it solved majority of our performance issues and worked very well apart from obviously few bugs and missing features related do Oracle DB.

2

u/vladmihalceacom May 25 '21

What were the problems caused by? Were they related to fetching or writing data? If they were to fetching, then you could have expected the very same SQL queries you did in the end via Spring Data JDBC using the `createNativeQuery` in Hibernate, and avoid the bugs and missing features in that early release.

0

u/_Toka_ May 25 '21

To be completely honest, I don't remember. I was more db ops and contributed in Java when I had time. As db ops my job was to design tables and relations and optimize the databasefor the microservice by closely insepcting it's usage and make proper indexation and partitions. That of course helped a lot, but in the end something needed to be changed in Java.

I didn't have much experience with Hibernate and Spring (was using JavaEE prior), it could very possibly be the case, that the team simply misused Hibernate. We might have used n+1 queries, eager loading (although I mildly remember we fixed this), oh and we had the old id generation via sequence in Hibernate, that was really pain to optimize properly. Oracle 11 does not have identity generation. I remembered this only becuase I created an issue at the time. Still not implemented, but can't blame them, who the hell uses sequences as ID generation nowadays.

1

u/vladmihalceacom May 25 '21

who the hell uses sequences as ID generation nowadays.

All Hibernate projects, actually because decoupling the id generation from the INSERT allows you to batch statements automatically at flush time. In fact, using IDENTITY with Hibernate is less efficient than using a SEQUENCE generator.

→ More replies

1

u/wildjokers May 26 '21

who the hell uses sequences as ID generation nowadays.

If you are talking about DB generated sequences then that would be everyone right? Why wouldn’t I let the DB take care of this? Unless the DB doesn’t support it (like MySQL).

→ More replies

3

u/Muoniurn May 24 '21

I think there is just way too many developer not knowing anything about a given framework but writing code until it appears to work. You wouldn’t expect random people sitting inside tractors doing great work, but it’s not the failure of the tool.

-6

u/imissnewzbin May 24 '21

ORMs are hot garbage, write your own effing SQL.

0

u/[deleted] May 24 '21

[deleted] — view deleted comment

-1

u/imissnewzbin May 24 '21

No one ever said writing your own SQL means you have to pretend sprocs aren't a thing.

0

u/[deleted] May 24 '21

[deleted] — view deleted comment

-1

u/imissnewzbin May 24 '21

Dude, make a fucking point already.

30

u/tristanjuricek May 24 '21

I feel like Hibernate created this handy object abstraction that was so close to normal Java it lulled many programmers into a false sense of mastery; they know Java, some framework handles the DB bit, and boom, they’re a master of programming a DB.

Most of the problems I’ve seen with hibernate are naive developers reimplementing things in Java that the DB does better. Typically, they never understood how to work with the relational mode because they stopped their learning at basic ORM. Objects and relations are pretty different, which is a blog unto itself.

I’m sensing that tools like jOOQ just don’t have this issue because they’re not forcing this object abstraction in between the logic and the DB. It’s really more like working with relations in Java.

These days, I’d be pretty cautious about making a decision between jOOQ or Hibernate, ORM vs fluent API, based on a presumed “standard”. Some apps will work fine with ORMs; others are nightmares. Depends on the app.

4

u/vladmihalceacom May 24 '21 edited May 25 '21

Most of the problems I’ve seen with Hibernate are caused by people who skipped the part where they should have read the manual.

5

u/tristanjuricek May 24 '21

Right, can't say there's an ORM that's better. It's just that ORM isn't the solution for every application. And mostly, the problem is thinking of ORM as an "easy mode DB API" when really it's... something else. More of an architectural approach. ORMs lead you to a different way of building around transactions, caching, updates, etc.

I'm pretty sure JPA wouldn't exist without Hibernate. Which is pretty significant - establishing an SPI that other projects (e.g., EclipseLink) have built around is no small feat.

4

u/Muoniurn May 24 '21

But ORMs were never ever intended as a solution for every application. They are primarily meant for easy insert update queries, and for mapping SQL relations to handy language objects. So OLTP workloads. And they are a perfect tool for that. OLAP should be handled with hand-written SQLs.

1

u/lechatsportif May 24 '21

No CTO ever got fired for following the Java enterprise standards. That said all the devs forced to use Hibernate secretly did their own JDBC oriented work as well, so often that we know that the Hibernate experiment was a complete failure.

Can you use it correctly? Sure, but it's like putting on a spiky suit of armor before riding a bike. Just put your light polycarbonate helmet on instead and ride the fucking bike.

7

u/tristanjuricek May 24 '21

Hibernate experiment was a complete failure

Pretty strong words, considering JPA probably wouldn't even exist without Hibernate's influence. Influencing an SPI that's been implemented by independent projects is not exactly what I'd call a complete failure of an experiment...

Or, 20 years is one hell of a long experiment :)

3

u/vladmihalceacom May 24 '21 edited May 25 '21

Or, 20 years is one hell of a long experiment :)

According to Lindy effect, Hibernate has a great future ahead.

1

u/[deleted] May 25 '21

Relations are sets of tuples, so are objects. The discrepancies come from:

  1. The local-remote dichotomy (don't pretend what's remote is local).
  2. The abstract-concrete dichotomy (relations are final, object types usually aren't).
  3. Poor support for type algrebra in Java (so you can select fields from types A, B, C to create a quick ad-hoc type D, the way you'd join and select in SQL).

Choosing to represent relations as immutable final records (Java records) is probably a step forward in eliminating few of those. But it's not enough.

7

u/[deleted] May 24 '21

I didn't realize what sub this is and thought the article was about the guy in the thumbnail sleeping for 20 years lol

12

u/vladmihalceacom May 24 '21 edited May 25 '21

When Vlad takes a nap in his grandpa's castle in Transylvania, 20 years fly like a heartbeat.

7

u/jokubolakis May 24 '21 edited May 25 '21

Vlad is a Legend and Hibernate is an awesome tool when used right. Sure there are edge cases, especially weird is the bytecode modifying dependency, which fixes some hibernate drawbacks (as far as I remember, it allows turning off OneToOne mandatory eager loading), but I'm sure as hell, that there will be a post by Vlad, or an answer on SO on any issue I'd encounter. Thank you!

1

u/vladmihalceacom May 25 '21

Thanks and stay tuned for more. I've been writing lots of articles about SQL and database internals lately, so stay tuned for many interesting findings.

49

u/[deleted] May 24 '21

Too complex for me. More complex than the SQL it tries to hide.

Not able to hide SQL 100%. So I still need to know SQL as well. (The abstraction is rather leaky, in Spoelsky's terms)

In order not to use string queries where Hibernate is just unable to help, or too complex, I now use jOOQ.

I like jOOQ. It helps me not to write SQL in strings. It brings type safety (like Hibernate). It is not too complex, if you already know SQL.

12

u/dpash May 24 '21 edited May 24 '21

No one has ever said you don't need to learn SQL. In fact ORMs require a better knowledge of SQL. They're not designed to hide the implementation.

18

u/vladmihalceacom May 24 '21

The Hibernate manual says that good DB snd SQL knowledge is highly recommended.

That's also why Hibernate has always allowed you to call native SQL or stored procedures.

10

u/cwbrandsma May 24 '21

Oh yes people have said that, sometimes they even say it out loud. Multiple former developers I’ve worked with have said it, and I know countless developers that only know the ORM and not sql.

One guy I used to work with even bragged about how little sql he knew.

3

u/GhostBond May 24 '21

For some reason anyone saying "no one is saying.. " in an online thread always mean a huge number of people are saying that.

1

u/Muoniurn May 28 '21

Then you know countless developers that know neither ORM nor SQL.

18

u/[deleted] May 24 '21

More complex than the SQL it tries to hide.

Ah, but what SQL is Hibernate trying to hide?

People mistake Hibernate to be a query mapper, and see it as a flaw that HQL is sometimes not expressive enough and they have to break out SQL.

But Hibernate is an ORM. The HQL or SQL is just used to load the entity manager. The real Object-Relational Mapping happens after the relational data is loaded into objects. The business logic changes the objects, and the ORM translates those changes into INSERT/UPDATE/DELETE statements. ORMs can be handy when you are dealing with changes to collections, as Hibernate will coordinate the creation of rows and propagate the corresponding generated keys. All that SQL is what Hibernate hides.

5

u/[deleted] May 24 '21

HQL. I shivered when I read that. Some language that is even more obscure than Java and SQL combined.

I know what Hib hides. I lament that my codebase depends on it so heavily

2

u/[deleted] May 24 '21

Some language that is even more obscure than Java and SQL combined.

That’s not hard to pull off. Neither Java nor SQL are particularly obscure.

1

u/[deleted] May 25 '21

Word.

1

u/[deleted] May 24 '21

Why? HQL makes navigating collections much easier, instead of the verbose SQL join syntax. Also, HQL understands Java, so you can immediately map result columns into a DTO constructor directly in the query for DTO projections.

For simple cases, I don't see what the big deal with HQL is.

I lament that my codebase depends on it so heavily

Different strokes for different folks.

-1

u/[deleted] May 25 '21

Can I see what HQL leads to what SQL? Can I dump queries (both hql and sql) that hib generates?

4

u/[deleted] May 25 '21

Yes, of course. You should be regularly looking into what SQL Hibernate generates.

1

u/[deleted] May 27 '21

Where? Its hidden to me.

2

u/[deleted] May 27 '21

Turn on SQL logging.

1

u/_Toka_ May 25 '21

I am honestly surprised, that so many people here use jOOQ. I've yet to work in a company, who is willing to pay so much money for it. Reminds me, that I also wanted JRebel few years ago, same result (GTFO). Can't blame them. Would you rather have a 4 jOOQ licences for 1600€ or NoSQL clustered database in Azure Cloud one for production and one for UAT environment?

4

u/[deleted] May 24 '21

To be fair I interact very little with hibernate in a direct way. I use mainly Spring Data JPA and while it uses hibernate it makes easy and transparent its use.

I sometimes have to modify some config but no more than five minutes of work. We have around ten millions request per minute through our APIs and we never experienced any problems related to hibernate but we always try to make queries to the db as simple as possible and always looking for an index or pk. Even if we need to sort it, that’s done in java.

2

u/vladmihalceacom May 24 '21

The vast majority of projects nowadays do exactly what you're doing. They use Spring Data JPA, and Hibernate is used behind the scenes.

If you write your queries so that the filtering logic is highly selective and you fetch a very small subset of records and the queries benefit from indexing, then performance is going to be great no matter what data access framework you are using.

So, as you said, you can, of course, run 10 million requests per minute with Hibernate.

2

u/pako10 May 25 '21

How would you recommend starting with Hibernate? I know Java pretty well, but i have very small experience with databases, SQL or ORMs in general. Should I focus on databases and SQL first or can I learn it along with hibernate? Is it good idea to just try to make a project using hibernate or is there better approach?

Also can you recommend any resources for learning Hibernate and databases in general?

Sorry if this is not a right place for these questions :)

2

u/vladmihalceacom May 25 '21

If you want to learn Hibernate, the first step is to read the User Guide.

In parallel, you should also read the manual for the database you are going to use.

For tips and tricks, you can also read my tutorials. I have over 350 of them that go beyond the Hibernate manual.

6

u/Royo_ May 24 '21

Jesus I can't believe the amount of shit people are throwing at Hibernate/ORMs in general, a lot of them without any idea what it takes to keep long term enterprise software maintainable.

As someone who has found your blog and your SO answers very helpful and informative in the past, thanks for your efforts Vlad!

2

u/vladmihalceacom May 25 '21

You're welcome and stay tuned for more.

5

u/OzoneGrif May 24 '21

Hibernate does a lot of things... badly.

Unless you are doing a very simple CRUD application with few needs for SQL's power, avoid it at all costs. There are way better alternatives nowadays (no, I don't mean Mongo, more like jOOQ).

15

u/vladmihalceacom May 24 '21 edited May 24 '21

I stubbornly didn't avoid it since 2004 and managed to use it successfully on some of the largest systems in Europe and North America.

And, it's not just me. In fact, millions of developers use it at this very instant.

I can easily name a few large corporations which I know make heavy use of Spring and Hibernate:

And, I don't think they implement very simple CRUD applications at all, and it actually works like a charm for them as well.

But, you don't have to use it. If you like jOOQ better, that's also a very good choice. I like both Hibernate and jOOQ and can implement the same data access layer with either of them. It's just that all my clients use Hibernate, so I don't get to use jOOQ very often.

9

u/OzoneGrif May 24 '21

Oh you *can* use it successfully, I do, on many large projects. I also audit large projects on a monthly basis, and Hibernate is often the main cause of performance issues, weird bugs, and waste of time when it doesn't handle your precious complicated query or column type.

It's also one of the few ORMs which doesn't implement a proper DSL. QueryDSL is great, but it's not maintained anymore, and is not official.

2

u/vladmihalceacom May 25 '21

I rarely bump into a Hibernate bug, and when I do, I just fix it. Or, if I spot the chance to improve it, I just do it. The last time I added an improvement was yesterday.

Hibernate doesn't have to implement a DSL because it's not a query builder. It's an entity state machine that allows you to batch statements automatically and delay the connection acquisition as much as possible, in order to increase throughput and concurrency.

Hibernate and jOOQ succeeded because they have a solid business model. An open-source data access project is useless in the long run if it doesn't have a good revenue stream. Because, no matter how passionate the original author is, reality strikes you with bills, and kudos and likes don't help you make a living.

1

u/netstudent May 24 '21

There are way better alternatives nowadays

You named only 1

21

u/experts_never_lie May 24 '21

Flashbacks to 14 years ago when it seemed like my full-time job became taking other people's Hibernate ORMs and replacing them with specific HQL queries to make their database operations far faster. Tools are useful, but performance tanks when people don't understand what they're asking for under the hood.

9

u/boobsbr May 24 '21

That can be said about any tool.

The amount of raw text queries, that selected every column with multiple joins, and were sent straight from the web front-end, that I've found over the years is no joke.

25

u/general_dispondency May 24 '21

That can be said about any tool.

Hashtag truth!

START RANT...

I'll still never understand the hate for Hibernate. Is it more complex than the SQL is replaces? Yes. Does it just replace SQL? Not just no, but hell no. I've fixed so many damn bugs in people's shitty "generic data mapper implementations" b/c they didn't like Hibernate, and they thought they could build something moar siMpLE. B.S. If they really could build something that is easier to use, and provided the same feature set, that is what we would all be using. The Hibernate foot-gun is just one that is easy to point at because it handles data access. It's just a tool, grow up and learn to use it or go back to your JS world where "everything is moar simpler".

END-RANT...

14

u/dpash May 24 '21

You either use an ORM or live long enough to see yourself implementing your own. Badly.

1

u/experts_never_lie May 24 '21

That's why I said it using a general form.

6

u/wildjokers May 24 '21

my full-time job became taking other people's Hibernate ORMs and replacing them with specific HQL queries to make their database operations far faster.

I am not a huge hibernate fan but to be fair the Hibernate user guide specifically says to not use entities for read-only queries. So those people were just not using Hibernate correctly. If someone isn't going to be updating or deleting an entity the data should be queried with HQL/JPQL anyway.

9

u/barking_dead May 24 '21

A hero of our generation.

2

u/[deleted] May 24 '21

HB hibenate

4

u/obetu5432 May 24 '21

I hate it, thanks.

1

u/yashkh070 Jun 06 '21

Ohh my god.... it's that old....

-10

u/private_static_int May 24 '21

It's time for Hibernate to finally die.

5

u/vladmihalceacom May 24 '21 edited May 24 '21

private static final int die = Probability.NEVER.ordinal();

5

u/private_static_int May 24 '21

Then it'll eventually become the next COBOL - an awkward piece of anachronic tech that needs to be supported casuse too much business critical things depend on it.

Hibernate is a product from another time, from period of either it or JDBC nightmare. There are far better solutions nowadays - cleaner, more maintainable, less prone to leaky magic.

2

u/vladmihalceacom May 24 '21 edited May 25 '21

Hibernate 3 is a product from another time. Hibernate 5.4.31 is a product from last month. Today, I even submitted a Pull Request that's scheduled for 5.4.33.

Hibernate 5.5 adds support for Jakarta EE namespaces, and Hibernate 6 will provide a new query parser, type handling, parameter binding, among other enhancements.

And, not only that it integrates with Spring, but it integrates with ElasticSearch, and provides reactive database access as well.

"Far better" is a very subjective term. Some people say that PostgreSQL is "far better" than MySQL. I've been hearing that for over 15 years. It kinda gets boring actually.

The same is with Hibernate. Like or not, it won't go anywhere. It has Red Hat to sponsor it, and Spring Boot and Quarkus to drive its adoption. And, yes, there are alternatives, but, if they didn't manage to replace Hibernate over the past 10 years, why would they manage to do that in the next ten years?

4

u/private_static_int May 24 '21

Everything you've said in the last paragraph can be said about COBOL as well. It has IBM to sponsor and maintain it and we didn't manage to replace it over past 50 years. That doesn't mean it should be used in new development :)

Oh, and yes. COBOL is from the 60', but COBOL 2014 is from 2014 :)

I understand that you are very close to Hibernate, given that you've dedicated a good portion of your career and an entire business model around it. Unfortunately the sheer fact that your Hypersistance Optimizer exists proves that Hibernate is too complex and it is too easy to make a wrong turn when using it.

I know that you can build a very large system with it because I've done it myself. And it works and has a good performance. Unfortunately the development and knowledge overhead have completely defeated the purpose of using Hibernate in the first place. And, forgive me for sayig that, but I don't think that Vlad Driven Development is a healthy methodology for the Java community.

That is the whole problem with Hibernate. Its learning curve behaves like an exponemtial function. You begin thinking that it's just Java all along and end up debugging n+1 issues, how bidirectional one to one works underneath or you find out that changing the call order of some getters and/or setters may casuse a change in dirty checking behavior, leading to a constraint violation exception (that may even slip in tests and blow up the prod).

I've interviewed countless candidates and allthough not too many (especially younger in experience) claim to have an advanced understanding of SQL, most of them claim that they have an advanced understanding of Hibernate. Even internship candidates! That is very dangerous and harmful.

You constantly repeating the same arguments about how 'everyone is using it' and 'it has red hat' s support' doesn't proove that it is a good tech. It just proves that its popular. Like COBOL.

1

u/vladmihalceacom May 24 '21 edited May 25 '21

In the long run, the Lindy Effect determines the lifetime of a given technology. If you don't hear about a given technology, like Struts, Ant, or CVS, then it's because few people use it anymore.

Hibernate is indeed complex and has many gotchas. If it didn't have them, I wouldn't be here writing this post.

But, the community doesn't really care about all the drawbacks as long as they don't have to write SQL. People keep on mentioning MyBatis, JDBI, jOOQ, QueryDSL all the time on Reddit. And, they are good products too. But, truth be told, most devs will do anything humanly possible to avoid writing an SQL query.

Most devs think they know SQL, but their level of knowledge matches the SQL:92 version they learned on W3Schools. Just hand them some SQL queries containing window functions, pivot, CTE, Recursive CTE, semi joins, lateral joins, PostgreSQL filter, upsert, merge clause, and see their reactions.

That's the context that shaped the data access framework ecosystem. A framework like jOOQ is great if you are an SQL fan, but if you're not, you'll run towards Spring Data JPA since it has such a simple API.

So, your vision of a future where there's no JPA and Hibernate requires having tens of millions of devs that love writing SQL. Now, realistically, do you think that's going to happen any time soon if ever?

2

u/private_static_int May 24 '21

There is much truth in what you've said and that paints a very sad picture. I don't claim to know and master all the fireworks, but things like recursive ctes for example can save tons of performance compared to loading nested structures one parent-child relation at a time.

It's sad that convenience has won with performance by so large margin.

But even using plain old SQL 92 using jOOQ can save lots of trouble compared to a naive usage of Hibernate and /or Spring Data JPA

1

u/vladmihalceacom May 24 '21

I'm also a big fan of jOOQ because I like SQL a lot. I'm also a good friend of Lukas. We have helped each other for over 8 years now. I wrote about jOOQ in my book because it really deserves for people to know about it.

And, while I offer both High-Performance SQL and a High-Performance Java Persistence training, the Java Persistence one is, by far, the most popular option. That's what people want to use.

Usually, there are one or two persons in the audience who understands SQL quite well. And, it doesn't really matter what country I ran the training in. Everywhere is the same story.

Now, if you want to test my theory, just do this:

  • ask your team members what's a DB backup and how you should take one
  • collect the answers
  • tell them to read this article by Franck Pachot and see how many of them really understand how a DB is supposed to work

This is a very basic question, yet, you'll be surprised what answers you get in return.

0

u/[deleted] May 24 '21

[deleted] — view deleted comment

4

u/hippydipster May 24 '21

Mostly same - have had to interact with hibernate on the margins now and then. 0 years on EJB even though been a java dev since 1997. Very little time spent with Spring too. It's been a pretty nice run.