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

Imagine having a tool that can automatically detect if you are using JPA and Hibernate properly. Hypersistence Optimizer is that tool!


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:


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 {

    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 {

    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) {
        else {
        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).


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.


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 AS id1_0_0_, p.title AS title2_0_0_
FROM   post p

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 {

    private Long id;

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

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

    @OneToOne(fetch = FetchType.LAZY)
    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 property serves as both Primary Key and Foreign Key. 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.

If you want to customize the Primary Key column name when using @MapsId, you need to use the @JoinColumn annotation. For more details, check out this article.

The PostDetails entity can be persisted as follows:

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

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(

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


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.


47 Comments on “The best way to map a @OneToOne relationship with JPA and Hibernate

  1. Hi Vlad,
    Thank you for your article.
    For your article to be seen by more people,I’d like to translate your article and post it on my blog if you do not mind.
    Of course, I will indicate the author and the original link in a conspicuous position.

    • You need to retain all marketing info, like links to book and courses and Hypersistence Optimizer. After you translate it, I need to take a look at it and tell you whether it’s fine or you need to change it.

  2. With @MapsId, does it still possible to get associated Detail from Post through getPostDetail() method?

  3. It better really be ‘the best way’, cause I implemented it and my salary depends on the incoming code review. Will update you.

  4. Hi, Vlad.

    Thank you for the explanation. I work with spring-data repositories and have a doubt regarding how to implement the repositories for the referenced entities.

    Where do you suggest to be put jpql queries of PostDetails entity, in the Post repository or in a specific repository for PostDetails?

    • If the PostDetails is always managed by the Post, then in the PostRepository, otherwise, on its own.

      • Thanks, Vlad.

        I would like your suggestion in the following case.

        Given that PostDetails will always be managed by Post and that the association is like you advised , unidirectional, and that I use spring-data-rest, so what do you think it is the best way for accessing the PostDetails object from the rest browser?

      • You can still fetch the PostDetails directly and modify it. As long as it shares the entity identifer with Post, it’s not difficult to navigate from its parent entity.

  5. Hi, considering the efficient way of mapping the OneToOne relationship above using MapsId, how do you delete PostDetails and automatically delete the corresponding Post?

    • As I explained in my book, High-Performance Java Persistence, you have many options. You can use DDL-level ON DELETE cascade, you can use JPA or HIbernate event listerens that autoatically remove the child as well, or you can simply issue the 2 remove operations.

  6. Lets say I want to remove a Post row. This wont affect the PostDetail corresponding that removed Post. However, I want that PostDetail to be removed as well. How to do that?

    • Of course, it will affect the PostDetails as the child cannot exist without its parent since the FK constraint will be violated. If you don’t map the association on the parent side, you have two options. Either you remove the Post and the PostDetails using their shared identifier or you delete only the Post and rely on FK-level delete cascading. Check out my High-Performance Java Persistence book for more details.

  7. Hello Vlad, thx for your great post.

    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.

    and Anthony Patricio 2009-08-11

    So the resume: if your B->C mapping is mandatory (constrained=true), Hibernate will use proxy for C resulting in lazy initialization.

    Does this mean that above article is outdated and mistaken? Or I have misunderstood either you or Anthony?


    • Hibernate behavior keeps on changing, so it’s not unusual to get different results across versions. However, I doubt that the secondary statement will not be fired since there is no DB construct to ensure that a parent table row must always have an associated child row record. So, the best thing is to test it out. You can use my High-Performance Java Persistence GitHub repository for that. But, I’m 99.9% sure that it works as I said unless you enable bytecode enhancement which is a totally different story.

  8. Hi Vlad,

    Would it be possible to resolve the issue of lazy loading on the parent side of a one-to-one relationship through the use of a type similar to Optional?

    Obviously Optional itself could not be used because it is final and not serializable, but imagine a similar type MyOptional which did not have those problems.

    For example, if the field type in the parent entity were MyOptional, then with support from Hibernate, there’d be no need to check for the presence of the child entity — it could just return a “proxy” MyOptional which “lazy-checks” for the presence of the child entity.

      • Thanks for the quick reply & documentation.

        I know of the possibility of using bytecode enhancement, but of course that’s not a default configuration. I was mainly considering situations where it might not be possible or desirable to turn on bytecode enhancement. Do you think there is any value in such a feature in a future version of JPA/hibernate?

        Thanks, Shawn

      • I don’t think anyone will want to implement such a feature since bytecode enhancement already offers a solution for it. But since the JPA spec is open source, you should add an issue and see how it goes.

  9. [Solved] Hi Vlad, Thanks for the quick response. The High-Performance Java Persistence GitHub repository is truly an awesome & exhaustive collection of most possible JPA usecases. Very much helpful for budding JPA users like me, to be kept as reference. Thanks for creating it.

    For anyone having the same problem as me: Testcase ‘OneToOneMapsIdJoinColumnTest’ from above repository is closest to a Unidirectional-JoinColumn-MapsId-OnetoOne setup. And here lazy loading works!

    Comparing this to my environment, the repository test setup works on hibernate 5.4.2, while mine picked up a 5.3.9. Upgrading solved the problem with Lazy loading. Thanks !

  10. Hi Vlad, Great Article. Thanks for posting.
    I have come across the same problem as George. Hope you can help.

    Lazy loading at client side does stop working, when there is a @JoinColumn at client side.

    That is: If we query ‘PostDetails’, which has a @JoinColumn, mapping to any different column other than default, it eagerly fetches ‘Post’ also, with a second select query, regardless of the value of ‘fetch’ or ‘optional’ attribute.

    The ideal scenario of unidirectional one-to-one mapping using @JoinColumn & @MapsId at client side, and no mapping at Parent side, also has the same exact problem []

    Is there something missing here. Thanks in advance.

    • Send me A Pull Request with a replicating test case in my High-Performance Java Persistence GitHub repository so that I can see the problem.

  11. I’ve a different scenario:

    A user may be also worker. A worker may not have a user.

    So I can’t use “userId” as PK of Worker because there may no User for some workers.
    I can’t use workerId as PK for User too because there may no Worker for that User.

    So in my schema: Worker will have a PK workerId and FK userId which is nullable and unique.

    How should I hibernate?

    • Then use a join table with unique constraints on each FK.

  12. Hello Vlad
    I’m having a problem with the previous code, except I’m using JpaRepositories from spring-data-jpa rather than entitymanager itself.

    The code get the error:
    org.springframework.orm.jpa.JpaSystemException: null id generated for:class xxy.test.jpa.onetoonetest.TestEntityOneToOneExample$PostDetails; nested exception is null id generated for:class xxy.test.jpa.onetoonetest.TestEntityOneToOneExample$PostDetails

    And my solution to the previous error is to delete the “optional = false” in the OnetoOne annotation on Post.PostDetails. In this way the save method works but I don’t quite understand. Do you have any explanations for this?


    • Maybe it’s a Spring issue due to their save method hacks. Or, it could be a Hibernate issue. You need to investigate it and see what’s the real cause.

  13. Hi Vlad,

    In your last example with @MapsId, yes there is no cascading defined. Then when deleting the main Post entity will PostDetails be deleted automatically? If not, I see this as the only downside that often it is very convenient just to delete the main entity assuming that child entities will be deleted on cascade.

  14. Would a set up like this work with a database schema that is already set?
    For Ex: I have a db schema that contains the tables post and post_detail. post_detail has the fk constraint for post_id defined in the ddl. In PostDetail class the private Long id; is switched to the name postId and the @Column annotation like so, @Column(name=”post_id”) would the @MapsId annotation over the private Post post; map to the right id? Or does the @MapsId attempt to create another column? I am currently trying to implement this type of OneToOne relationship with a DB schema I have already implemented. I am getting an error during schema-validation that my child table is missing an id column to the parent table that I have not defined.

    • If you have a separate FK column, then you don’t have a test one-to-one table relationship. You have a one-to-many relationship with a unique constraint. Without changing the schema, you can’t use MapsId. You need to change The schema if you want to be more efficient.

      • I am a little confused. In the example provided @MapsId makes it so post_detail’s id is the same id as post (from my understanding). In my example, the database already exists. In this database, post_detail has a post_id column that is both the fk and primary key in post_detail which is the primary key from the post table (from my understanding this is what @MapsId does). Is that not the same?

        If that’s not the case, is that because post_detail has no actual id column in the db, and the @MapsId annotation links them together under the hood some how?

      • If you are sharing the PK bug want to customize the column name, you need to use the `@JoinColumn(name=”id”) next to MapsId.

  15. What if I wanted do persist Post with its PostDetails at the same time using cascade, when Post does not have its Id yet ? I keep getting error ;Caused by: attempted to assign id from null one-to-one property; which is quite logical for me – the question is is there any different way of persisting @OneToOne with @MapsId, since this example shows only the solution where Post is already persisted in the db ?

    • As long as you set both sides of the association, the cascading should work. If it does not work, you have to write a replicating test case and open a Jira issue for the Hibernate project.

  16. Hey Vlad, thought this was great article it really helped me understand whats happening under the hood in JPA.

    I was wondering on your final example what the Post class looks like.
    I think you mentioned it was undirectional so I assume it doesn’t hold a reference to its child(PostDetails) anymore like the previous examples. Is that correct?

    Also is it only possible to persist from the child in your final example since its the only one that has the logic to tell about the relationship? If that is true, is that bad practice to try to persist from the parent? I am asking because I am attempting to figure out a way to persist the parent and have it set up its relationship to its child.


    • In my last example, you don’t need to map the PostDetails in the Post entity. Also, you don’t need to cascade either. Just create the two entities and call persist for both. It’s just one extra line of code.

      • I see what you mean in for this example. What I am trying do is ingest a json file into the database, but it is nested pretty deep at certain points so it makes logic in the main a little more tedious calling persist on every nested child and its parent. Although I believe it probably is doable. Would calling persist on the root parent and have it recursively setup those relationships be extremely performant costly, is that why you prefer this method?

      • The problem comes when you need to fetch the entity. You can map two Post entities to the post table, one with the details for cascading while the other without the details. Check out this article for more details.

  17. Hi,

    I’m used to set a post_details_id in Post so I can put a not null constraint (each Post needs one PostDetails). How can I add the constraint with your example? Now I can add a Post without PostDetails in the database.

    • The Post is the parent, so it should not contain a FK. Also, a true one-to-one association shares the PK, so you don’t need a separate FK column. As for adding constraints, that should be done with FlywayDB, not Hibernate mappings.

      • Ok, but how to say “every Post needs to have one PostDetails”? Cause now you can have a Post without a PostDetails in the database. Seems like you can’t do this with this mapping…?

      • If every Post should have a PostDetails, then why use 2 tables? It looks like a single table us what you need.

  18. You wrote about GitHub, but when I went to your repo, Post and PostDetails were using annotations from the example you told that is not optimal. There was no MapsId.

    • If you check the test with the MapsId in its title, you’ll find it. There are more than 300 tests there.

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.