I'm trying to enforce a EXTRA lazy loading policy when fetching data navigating an object graph.
I have a OneToMany bidirectional relationship with 2 entities like:
many sideCode:
@Entity
public class Wine {
@Id
@GeneratedValue(strategy = GenerationType.SEQUENCE)
@Column(name = "ID")
private long id;
@ManyToOne(fetch=FetchType.LAZY)
@JoinColumn(name="WINE_ID",nullable=false,updatable=false)
private Winery winery = null;
private String name;
private int age;
// getters and setters....
}
and
one side Code:
@Entity
@Table(name = "winery")
public class Winery {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name = "id")
protected Long id;
@Basic
@Column(name = "name", nullable = false, length = 80)
private String name;
@OneToMany(fetch = FetchType.LAZY)
@IndexColumn(name = "INDEX", base = 0)
@Cascade(org.hibernate.annotations.CascadeType.ALL)
@LazyCollection(LazyCollectionOption.EXTRA)
@JoinColumn(name="WINERY_ID")
protected List<Wine> wines = new ArrayList<Wine>();
@Version
@Column(name = "version")
protected Long version;
// getters and setters....
}
I want to retrieve the
winery from the database, and then iterating through the
Wines, and make sure that not all the wines are retrieved from the db as long as I access the wine list:
Code:
String qs = "select w from Winery w";
EntityManager em = emf.createEntityManager();
EntityTransaction transaction = em.getTransaction();
transaction.begin();
Query query = em.createQuery(qs);
List<Object> oggList = query.getResultList();
Winery winery = (Winery)oggList.get(0);
ok I have the winery....
Code:
List<Wine> wineList = winery.getWines();
here I want nothing to happen
Code:
Wine myFirstWine = wineList.get(0);
here I want only one query to be executed... the query that retrieves exactly only the first one.
With this code I almost get what I want: actually I had to used an "Index" in order to force Hibernate to use a PersistenceList instead of a PersistentBag.
If I used a PersistentBag here
Code:
List<Wine> wineList = winery.getWines();
I would get the whole wine list from the DB.
My problem is that the
Code:
wineList.iterator()
triggers the fetching of the whole wine list. There is a way to avoid it?
thanks