Miguel Ping
Miguel Ping

Reputation: 18347

OpenJPA 1.2.1: fine-grained fetch plan

Suppose I have the following:

@Entity
class Product {
  @OneToOne(Lazy)
  ProductType type;
}

@Entity
class ProductType {
  @ManyToOne(Lazy)
  ProductFamily pf;
}

@Entity
class ProductFamily {
  String name;
  // ...
}

By default, OpenJPA has a fetch depth of -1, and it seems that if I query Product:

select p from Product p

it will end up querying something like this:

select p from product p
left join product_type
left join product_family

I have read about fetch depth, and I can restrict the fetch depth to 1, meaning that the query will only fetch immediate relations:

select p from product p
left join product_type

but how can I customize the query in order to be able to specify a fetch join for nested relations? I have tried both left fetch join and adding fields to the fetch plan, but it doesn't work.


to make it clear: I want all *-to-One relations to be lazy by default, and then fine-tune the relations via fetch joins, but it seems that OpenJPA is ignoring the lazy configuration.

Upvotes: 0

Views: 522

Answers (2)

Miguel Ping
Miguel Ping

Reputation: 18347

My bad, I had to turn class transformation in order to enable Lazy Loading. Withouth bytecode enhancement, OpenJPA gives a warning saying just that.

Upvotes: 1

JB Nizet
JB Nizet

Reputation: 691973

Not sure I understand. If you want to be able to specify what must be fetched, you'll need to mark your associations as lazy, and load your objects using queries. By default *ToOne associations are eager, and *ToMany associations are lazy. Once marked as lazy, the following queries are possible:

select p from Product p // load only the products

select p from Product p 
left join fetch p.type // load products with their type

select p from Product p 
left join fetch p.type t 
left join fetch t.pf // load products with their type and the family of their type

If the association is eager, whatever to code used to load the entity, its association will be fetched.

Upvotes: 1

Related Questions