简体   繁体   中英

OneToOne Lazy always fetch child

I have the following @OneToOne relation:

@Entity
@Table(name="USER")
public class User implements Serializable{

private Basket basket;

    @OneToOne(cascade = CascadeType.ALL,orphanRemoval=true,mappedBy="user", fetch=FetchType.LAZY )
    public Basket getBasket() {
        return basket;
    }

    public void setBasket(Basket basket) {
        this.basket = basket;
    }

//all other proerties are ommited and none relevant. 
}

Now the basket class:

@Entity
@Table(name="BASKET")
public class Basket implements Serializable {

private User user;

@OneToOne(fetch=FetchType.LAZY)
    public User getUser() {
        return user;
    }
//all other proerties are ommited and none relevant. 
}

Now I'm trying to fetch User object using HQL in object which has Spring Transaction manager using AOP:

public User getUser(String param1,String param2) {
    Session session = this.sessionfactory.getCurrentSession();
    String queryString = "from objects.User user where user.param1=:param1 and user.param2=:param2";
    Query query = session.createQuery(queryString); 
    query.setString("param1", param1);
    query.setString("param2", param2);
    User user = (User) query.uniqueResult();
    return user;
}

but I see that Basket is also fetched although it's Lazy:

Hibernate: select user0......
Hibernate: select basket0.....

Why?

Because a one-to-one normally represents highly cohesive objects and is fetched using a join by default, so there's little reason not to fetch both user and basket. I'm not sure why you're seeing two separate selects. I believe that should only happen if you tell it specifically to fetch using a select instead of a join. This article does a good job of analyzing a one-to-one relationship. It might help you out.

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