Skip to main content

Why should not use the AUTO JPA GenerationType with MySQL and Hibernate

Introduction

As I already mentioned, you should never use the TABLE identifier generator since it does not scale properly. In this post, I’ll show you why you should not rely on the AUTO GenerationType strategy if you’re Hibernate application uses MySQL.

Prior to Hibernate 5

On Hibernate 4, if you had the following entity mapping:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
@Entity(name = "Post")
@Table(name = "post")
public class Post {
 
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;
 
    private String title;
 
    public Post() {}
 
    public Post(String title) {
        this.title = title;
    }
}
When persisting 3 Post entities:
1
2
3
4
5
6
7
8
9
for int i = 1; i <= 3; i++ ) {
    entityManager.persist(
        new Post(
            String.format(
                "High-Performance Java Persistence, Part %d", i
            )
        )
    );
}
Hibernate would generate the following insert statements:
1
2
3
4
5
6
7
8
INSERT INTO post (title)
VALUES ('High-Performance Java Persistence, Part 1')
 
INSERT INTO post (title)
VALUES ('High-Performance Java Persistence, Part 2')
 
INSERT INTO post (title)
VALUES ('High-Performance Java Persistence, Part 3')
That’s great! Hibernate used the IDENTITY column to generate the entity identifier which is the only reasonable option for MySQL.

Hibernate 5

If you run the same unit test on Hibernate 5, you’ll get the following SQL statements:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
SELECT next_val as id_val
FROM hibernate_sequence FOR UPDATE
 
UPDATE hibernate_sequence
SET next_val= 2 where next_val=1
 
SELECT next_val as id_val
FROM hibernate_sequence FOR UPDATE
 
UPDATE hibernate_sequence
SET next_val= 3 where next_val=1
 
SELECT next_val as id_val
FROM hibernate_sequence FOR UPDATE
 
UPDATE hibernate_sequence
SET next_val= 4 where next_val=3
 
INSERT INTO post (title, id)
VALUES ('High-Performance Java Persistence, Part 1', 1)
 
INSERT INTO post (title, id)
VALUES ('High-Performance Java Persistence, Part 2', 2)
 
INSERT INTO post (title, id)
VALUES ('High-Performance Java Persistence, Part 3', 3)
What’s just happened? Well, Hibernate picks the TABLE generator instead of IDENTITY when the underlying database does not support sequences. However, TABLE generator is not a good choice. Check out the HHH-11014 Jira issue for more details related to this behavior change.

How to fix it?

The fix is extremely easy. You just need to use the native identifier instead:
1
2
3
4
5
6
7
8
9
10
@Id
@GeneratedValue(
    strategy= GenerationType.AUTO,
    generator="native"
)
@GenericGenerator(
    name = "native",
    strategy = "native"
)
private Long id;
Now, when running the previous test case, Hibernate uses the IDENTITY column instead:
1
2
3
4
5
6
7
8
INSERT INTO post (title)
VALUES ('High-Performance Java Persistence, Part 1')
 
INSERT INTO post (title)
VALUES ('High-Performance Java Persistence, Part 2')
 
INSERT INTO post (title)
VALUES ('High-Performance Java Persistence, Part 3')
If you want to use a portable solution that manages to customize the SEQUENCE generator while still allowing you to pick the IDENTITY generator for MySQL, then check out this article.

Source Link (Copied) https://vladmihalcea.com/why-should-not-use-the-auto-jpa-generationtype-with-mysql-and-hibernate/

Comments

Popular posts from this blog

Search Engine Optimization (SEO) Tricks

6 Key Search Engine Optimization (SEO) tricksStressed and frustrated with your Website's lower rankings on the Search Engines?The tricks and tactics listed below can tremendously change the entire scenario of your website's ranking and rating on Search Engine Results Pages (SERPs) and can take your website to a whole new level, with which increase in relevant traffic on the website is easily observable.http://www.boolment.com The tricks discussed here needs to be implemented in the most desirable way possible. Paginate Your Content: The content on your website is the main facial asset with which you can either impress your audience if the content is paginated well, or you can confuse the hell out of them if the content is unpaginated. So, make sure to arrange everything in a well-ordered manner. Organize CSS For Spiders: Organizing CSS for spiders is a crucial factor that must be considered in order to let the Search Engines know what you are up to and what exactly are you trying…

Android & iOS Application Development For Dummies

App Development ProcessApp Development Process explained in the most simplified way This tutorial will guide all the beginners how an app is developed from scratch and will help in letting the beginners know how the process works.Phase-1 (Conceptualization): Even a concept or an idea starts with an approach to introduce something after acknowledging the inkling of amiss or what's missing in the existing market. Developing the aftermath ideas involves critical questioning and rational thinking towards the wire-framing stage. Phase-2 (Design): After analyzing the idea thoroughly and looking through all possible dimensions, comes the design part, where a feasible layout of the model is planned to move ahead for the further development processes. Phase-3 (Coding): Development process begins with designing a user-friendly UI. Prototypes of the model are prepared with the combined agreement of developers and designers to increase the efficiency and capitalization. The expedience checking r…

Digitization of Restaurant Chains

How Restaurant Businesses Are Transforming With Mobile Apps The Interaction Between Apps and Customers: Customers interact with mobile phones more often than we can imagine and this interaction can be efficiently utilized when it comes to ordering food, which in turn makes it hassle-free for the customers to order food. Just by looking at the online menu on their mobile phones, customers can effortlessly feed themselves with your service and at the same time, your sales graph can jump vertically upwards. While a customer easily gets all information regarding your restaurant, your restaurant gets famous at the same time. In that sense, mobile apps have restructured the way customers and restaurants interact with each other. Business Profits With Mobile Apps:Mobile apps for restaurants benefits them through multiple dimensions. From push notifications to personalized offers, the customer engagement becomes more thrifty with your catering. To explain it with an example, consider the restau…