The best way to map a @OneToOne relationship with JPA and Hibernate

(Last Updated On: September 20, 2018)

Introduction

There are many ways you can map a one-to-one relationship with Hibernate. In this post, I’m going to demonstrate which mapping is the most efficient one from a database perspective.

Domain Model

For the following examples, I’m going to use the following Post and PostDetails classes:

OneToOne

The Post entity is the parent, while the PostDetails is the child association because the Foreign Key is located in the post_details database table.

Typical mapping

Most often, this relationship is mapped as follows:

@Entity(name = "PostDetails")
@Table(name = "post_details")
public class PostDetails {

    @Id
    @GeneratedValue
    private Long id;

    @Column(name = "created_on")
    private Date createdOn;

    @Column(name = "created_by")
    private String createdBy;

    @OneToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "post_id")
    private Post post;

    public PostDetails() {}

    public PostDetails(String createdBy) {
        createdOn = new Date();
        this.createdBy = createdBy;
    }

    //Getters and setters omitted for brevity
}

More, even the Post entity can have a PostDetails mapping as well:

@Entity(name = "Post")
@Table(name = "post")
public class Post {

    @Id
    @GeneratedValue
    private Long id;

    private String title;

    @OneToOne(mappedBy = "post", cascade = CascadeType.ALL, 
              fetch = FetchType.LAZY, optional = false)
    private PostDetails details;

    //Getters and setters omitted for brevity

    public void setDetails(PostDetails details) {
        if (details == null) {
            if (this.details != null) {
                this.details.setPost(null);
            }
        }
        else {
            details.setPost(this);
        }
        this.details = details;
    }
}

However, this mapping is not the most efficient, as further demonstrated.

The post_details table contains a Primary Key (PK) column (e.g. id) and a Foreign Key (FK) column (e.g. post_id).

one-to-one

However, there can be only one post_details row associated with a post, so it makes more sense to have the post_details PK mirroring the post PK.

one-to-one-shared-pk

This way, the post_details Primary Key is also a Foreign Key, and the two tables are sharing their PKs as well.

PK and FK columns are most often indexed, so sharing the PK can reduce the index footprint by half, which is desirable since you want to store all your indexes into memory to speed up index scanning.

While the unidirectional @OneToOne association can be fetched lazily, the parent-side of a bidirectional @OneToOne association is not. Even when specifying that the association is not optional and we have the FetchType.LAZY, the parent-side association behaves like a FetchType.EAGER relationship. And EAGER fetching is bad.

This can be easily demonstrated by simply fetching the Post entity:

Post post = entityManager.find(Post.class, 1L);

Hibernate fetches the child entity as well, so, instead of only one query, Hibernate requires two select statements:

SELECT p.id AS id1_0_0_, p.title AS title2_0_0_
FROM   post p
WHERE  p.id = 1

SELECT pd.post_id AS post_id3_1_0_, pd.created_by AS created_1_1_0_,
       pd.created_on AS created_2_1_0_
FROM   post_details pd
WHERE  pd.post_id = 1

Even if the FK is NOT NULL and the parent-side is aware about its non-nullability through the optional attribute (e.g. @OneToOne(mappedBy = "post", fetch = FetchType.LAZY, optional = false)), Hibernate still generates a secondary select statement.

For every managed entity, the Persistence Context requires both the entity type and the identifier,
so the child identifier must be known when loading the parent entity, and the only way to find the associated post_details primary key is to execute a secondary query.

Bytecode enhancement is the only viable workaround. However, it only works if the parent side is annotated with @LazyToOne(LazyToOneOption.NO_PROXY) and the child side is not using @MapsId.

The most efficient mapping

The best way to map a @OneToOne relationship is to use @MapsId. This way, you don’t even need a bidirectional association since you can always fetch the PostDetails entity by using the Post entity identifier.

The mapping looks like this:

@Entity(name = "PostDetails")
@Table(name = "post_details")
public class PostDetails {

    @Id
    private Long id;

    @Column(name = "created_on")
    private Date createdOn;

    @Column(name = "created_by")
    private String createdBy;

    @OneToOne(fetch = FetchType.LAZY)
    @MapsId
    private Post post;

    public PostDetails() {}

    public PostDetails(String createdBy) {
        createdOn = new Date();
        this.createdBy = createdBy;
    }

    //Getters and setters omitted for brevity
}

This way, the id column serves as both Primary Key and FK. You’ll notice that the @Id column no longer uses a @GeneratedValue annotation since the identifier is populated with the identifier of the post association.

The PostDetails entity can be persisted as follows:

doInJPA(entityManager -> {
    Post post = entityManager.find(Post.class, 1L);
    PostDetails details = new PostDetails("John Doe");
    details.setPost(post);
    entityManager.persist(details);
});

And we can even fetch the PostDetails using the Post entity identifier, so there is no need for a bidirectional association:

PostDetails details = entityManager.find(
    PostDetails.class, 
    post.getId()
);

If you enjoyed this article, I bet you are going to love my Book and Video Courses as well.

Conclusion

Knowing how to map entity relationships efficiently can make a lot of difference when it comes to application performance. For @OneToOne associations, you should always share the Primary Key with the parent table, and you should avoid the bidirectional association if you don’t plan to use bytecode enhancement.

Code available on GitHub.

Subscribe to our Newsletter

* indicates required
10 000 readers have found this blog worth following!

If you subscribe to my newsletter, you'll get:
  • A free sample of my Video Course about running Integration tests at warp-speed using Docker and tmpfs
  • 3 chapters from my book, High-Performance Java Persistence, 
  • a 10% discount coupon for my book. 
Get the most out of your persistence layer!

Advertisements

15 thoughts on “The best way to map a @OneToOne relationship with JPA and Hibernate

  1. Hi Vlad,

    when we tried to do this with a unidirectional relationship, we found that “entityManager.persist(details);” threw an exception because it tried to insert the Post entity into the database again, which created a primary key conflict.

    Probably this is because the Post entity was detached.

    Our workaround is to set the id field explicitly when setting the Post entity:
    setPost(Post post){
    this.post=post;
    this.id=post.getId();
    }
    This is somewhat weird.

    Is it possible to explicitly define the join column name of the post_id column in the details table via @JoinColumn? For us, Hibernate throws org.hibernate.id.IdentifierGenerationException: attempted to assign id from null one-to-one property

  2. Does it make any difference if you put @MapsId in PostDetails or in Post? Should I add @MapsId to both sides of a bidirectional association?

  3. Hi. Thank you very much for you post.
    I have a problem.
    How can I do a select query on Post without select on PostDetails?
    I am using spring jpa and in PostRepository I have :

    @Query(value = “select * from post p where p.title=:title”, nativeQuery = true)
    Post findPostByTitle(@Param(“title”) String title);

    this query result in two select query by hibernate :

    Hibernate: select * from post p where p.title=?
    Hibernate: select postdetails0 … where postdetails0_.post_id=?

    Is there any way to reduce to one query (on Post) while use @MapsId method?

  4. Hi Vlad,

    The lazy loading does work if we don’t have a join column as is explained in the article. But as we add a @JoinColumn as may be needed to use a different primary key column name(other than user_id format) the lazy loading doesn’t seem to work.

    We have 2 queries for each select. Is that expected behavior?

    Thanks,
    George

  5. Hey Vlad,

    I am struggling with a technical limitation and I can’t find the solution anywhere…
    Basically, taking your DB structure, I would like to:
    1. Insert Post_1 + PostDetails_1
    2. Insert Post_2 and make PostDetails_1 point to Post_2, unlinking it from Post_1.

    I want to do each step in it’s separate transaction (so 2 transactions in total).

    I tried:
    – Manually assigning the ID –> ofc it doesn’t work, can’t manually alter the ID
    – Cloning the PostDetails_1 and inserting the new clone while deleting the original object.

    Could you please help me?

    Thanks!
    Matt

    1. If the PK is shared, you can reassign a child entity to a new parent.

      If you don’t share the PK, meaning you have both an @Id and a @OneToOne association using a separate FK, then you can do it.

      1. The PK is the same as the FK.
        The @Id of the PostDetails is the PK and FK.

        Both of the things I’ve tried failed.
        – Manually reassigning fails
        – Deleting and inserting fails as well with attempted to assign id from null one to one.
        I have set the relationship before saving postdetails_1.setPost(post_2)

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.