简体   繁体   中英

find(Class,id) and JPQL get different object (JPA)

I am using Hibernate 4.1.10.Final as my JPA provider, Spring and Spring MVC. There are two entities:

@Entity
@Table(name = "a")
public class A {
    @Id
    private String id;

    @OneToMany(mappedBy = "a", cascade = CascadeType.ALL, fetch = FetchType.EAGER)
    private Set<B> bs;
}

@Entity
@Table(name = "b")
public class B {
    @Id
    private String id;

    @ManyToOne
    @JoinColumn(name = "fk_a_id")
    private A a;
}

I need to get an A and it's b s, so I use the find(A.class,id) of EntityManager.

A a1 = em.find(A.class, id);
a1.getBs().size();

For which the result is: the size of b s is zero (which means that there is no associated B). But I'm sure that there are many associated Bs in the database, and indeed the data can been loaded from database while checking via the console.

When I use Query:

Query query = em.createQuery("SELECT a FROM A AS a WHERE a.id = ?1",A.class);
query.setParameter(1, id);
A a= (A) query.getSingleResult();
a.getBs().size(); // = 22

I instead get a size = 22.

What's wrong?

Since you used the mappedBy property in your @OneToMany , the owner of the relation is B and not A. That's why when you load an instance of A, the corresponding Bs are not loaded. Try modifying your annotations with the following :

In class A :

@OneToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER)
@JoinColumn(name="fk_a_id")
private Set<B> bs;

In class B :

@ManyToOne
@JoinColumn(name = "fk_a_id", insertable=false, updatable=false)
private A a;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM