Take the 2-minute tour ×

I have the following entities:

public class Foo {
    @ManyToOne(optional = false) // I've tried @OneToOne also, same result
    @JoinColumn(name = "bar_id")
    private Bar bar;

    // this is a business key, though not mapped as unique for legacy reasons
    @Column(nullable = false)
    private long fooNo; 

    // getters/setters + other properties

public class Bar {
    @OneToOne(optional = true, mappedBy = "bar", cascade = CascadeType.ALL)
    private Foo foo;

    // getters/setters + other properties

NOTE: This is the correct mapping: @ManyToOne and @OneToOne (it wasn't designed by me). I have tried @OneToOne on both sides also, with the same result.

Basically, I can have a Bar without a Foo object, but everytime I have a Foo, there has to be a Bar associated with it. Foo is considered the parent object (which is why its the owner of the association), but Bar can stand alone in certain cases.

I then load a Foo object like this:

SELECT f FROM Foo f WHERE f.fooNo = :fooNo

foo.getBar() correctly fetches the appropriate Bar, as expected. However, foo.getBar().getFoo() is null. It seems the other side of this relationship is not correctly initialized by JPA/hibernate. Any ideas why this is happening and how I can fix it?

I use Hibernate 3.2.1 as my JPA implementation, which we are using through EJB3 beans (though that is probably irrelevant).

share|improve this question
Did you try fetch = FetchType.LAZY? –  durron597 Nov 30 '12 at 13:24
You mean to put that on the Foo reference? I thought that was the default, when not specified? –  Morten Jacobsen Nov 30 '12 at 13:28
Could you explain how this objects must be related, because current mapping is confusing. –  Aleksandr M Nov 30 '12 at 13:38
Another idea: have you tried putting the annotation on the getter/setters, not on the field? –  durron597 Nov 30 '12 at 13:40
@AleksandrM I added a brief comment on the idea behind the mapping. @durron597 I have not, but I can see internally that the field has the value null when I inspect the object in debug mode. I don't think putting mappings on getter/setters will change this? Bar.fooshouldn't be lazy loaded (as bar was lazy loaded through Foo. –  Morten Jacobsen Nov 30 '12 at 13:44
show 4 more comments

1 Answer

Are you sure about your assotiation? ManyToOne usually implies oneToMany on other.

share|improve this answer
This should probably have been a comment instead of an answer. Yes, this is the current mapping (its not designed by me). I have tried @OneToOne on both sides (because that is logically what it is), but it does not change anything. –  Morten Jacobsen Nov 30 '12 at 13:32
You may also try manyToOne on both sides –  Konstantin Pribluda Nov 30 '12 at 13:50
add comment

Your Answer


