I have data model similar to this
class Office
{
#ManyToOne
#JoinColumn(name = "cafeteria_id")
Cafeteria cafeteria;
}
class Cafeteria
{
#OneToMany(mappedBy="cafeteria")
#LazyCollection(value=LazyCollectionOption.EXTRA)
List<Chair> chairs;
}
class Chair
{
#ManyToOne
#JoinColumn(name = "cafeteria_id")
Cafeteria cafeteria;
}
I have a JPQL query like this
select o from Office o where o.cafeteria.someThing = ?
Above query works fine but in one case I would like a query which could eagerly load all the chairs(o.cafeteria.chairs) as well. How should I modify query to eagerly fetch all chairs?
Use fetch attribute in OneToMany annotation. You can map the same relationship as many times as you want:
class Cafeteria {
#OneToMany(mappedBy="cafeteria")
#LazyCollection(value=LazyCollectionOption.EXTRA)
List<Chair> chairs;
#OneToMany(fetch = FetchType.EAGER, mappedBy="cafeteria")
List<Chair> eagerlyLoadedChairs;
}
And then you can use any of them:
// Lazy loading
select o from Office o inner join o.cafeteria c inner join c.chairs ch where c.someThing = ?
// Eager loading
select o from Office o inner join o.cafeteria c inner join c.eagerlyLoadedChairsch where c.someThing = ?
You have two options, either you change the fetch type from Lazy to Eager, but this will always load your List of Chair every time you load an object from Cafeteria.
like this:
#OneToMany(mappedBy="cafeteria", fetch=FetchType.EAGER)
#LazyCollection(value=LazyCollectionOption.FALSE)
List<Chair> chairs;
OR In your Service that call this query, after calling it, you simply load the Chair list in your specific use case, check more about Initializing Collections in Hibernate
Hibernate.initialize(cafeteria.getChairs());
Related
I have a situation where i get List of entity in hiberate, But inside the main entity i have another entity list. The entities that i use:
EmpListBean.java
#NamedNativeQueries({
#NamedNativeQuery(
name = "EmpList",
//Actual query involves lot of joins
query = " SELECT ID , NAME FROM EMPLOYEE WHERE EMP_ID=:EMPID"
,resultClass = EmpListBean.class
)
})
#Entity
public class EmpListBean {
#Column(name = "ID")
private int id;
#Column(name = "NAME")
private String empName;
// This is the list i need to retreive
#ManyToOne
#Column(name="workList")
private List<WorkListBean> workList;
//Getters & Setters
}
WorkListBean.java
#NamedNativeQueries({
#NamedNativeQuery(
name = "WorkListBeanList",
query = " SELECT ID , NAME FROM Work_List WHERE EMP_ID=:EMPID"
,resultClass = WorkListBean.class
)
})
#Entity
public class WorkListBean {
#Column(name = "ID")
private int id;
#Column(name = "NAME")
private String workName;
//Getters & Setters
}
The DAO Layer
Query query = session.getNamedQuery("EmpList");
query.setParameter("EMPID", myObj.getEmpId());
List<EmpListBean> oEmpListBean = query.list();
When executing below DAO layer code I get the "workList" Object as empty , I know this can be achieved by iterating the EmpListBean separately and calling named query for WorkListBean separately , but since the data is huge it takes too much time when doing that way, So wanted to know if there is any way that we could fetch WorkListBean inside EmpList Bean. The two entities used here are only for reference , the actual query i use is complex and could not reveal in this forum and it involves lot of table joins, So kindly let me know how this can be possible in hibernate.
I know this can be achieved by iterating the EmpListBean separately and calling named query for WorkListBean separately , but since the data is huge it takes too much time when doing that way
I understand you want to merge the two queries to include the data for both entities, then?
Once the association between EmpListBean and WorkListBean is properly defined, i.e. you have:
class EmpListBean {
...
#OneToMany
#JoinColumn(name = "EMP_ID")
private List<WorkListBean> workList;
}
you should be able to use the following approach:
session.createNativeQuery(
"SELECT employee.* FROM EMPLOYEE employee JOIN Work_List wl JOIN ... WHERE wl.EMP_ID=emp.id AND employee.EMP_ID=:EMPID AND ..." )
.addEntity("employee", EmpListBean.class )
.addJoin( "wl", "employee.workList")
.setResultTransformer( Criteria.ROOT_ENTITY )
.list();
Not sure if it works for named native queries, though, you'll need to check.
As commented by #Javalerner you should use #OneTomany and add Eager Loading with fetch="FetchType.EAGER"
and remove the Column annotation
#OneToMany(fetch = FetchType.EAGER)
private List<WorkListBean> workList;
I like Abd's response if you're looking for a simple #OneToMany.
Rather than forcing the bean to always eager load, you may want to just incorporate this concept into your NamedNative query using the FETCH JOIN style. Using this approach you can craft queries that are EAGER on an object whose association is otherwise Lazy. In that case, Hibernate will only eagerly fetch via your query and generally be lazy, which is I think what most people want.
Feel free to google around. Here is a well written article that may start you off.
http://www.basilv.com/psd/blog/2008/improving-performance-via-eager-fetching-in-hibernate
Best of luck!
to get whatever FetchType.LAZY is, you have to use JOIN FETCH in the sentence. When you use JOIN you get all whatever FetchType.EAGER is but not whatever FetchType.LAZY is
EmpListBean.java
#OneToMany(fetch = FetchType.LAZY, mappedBy="empListBean")
private List<WorkListBean> workList;
WorkListBean.java
#ManyToOne(fetch = FetchType.LAZY)
#JoinColumn(name="EMP_ID")
private EmpListBean empListBean;
DAO
String hql = "SELECT empListBean "
+ "FROM EmpListBean empListBean "
+ "JOIN FETCH empListBean.workList workList "
+ "WHERE empListBean.id = :EMPID";
Query q = sessionFactory.getCurrentSession().createQuery(hql);
q.setParameter("EMPID", myObj.getEmpId());
List<EmpListBean> empListBean = query.list();
I have the following problem (pseudo-java-code):
Let me a class A,B,C with the following relationships:
#Entity
#Table(name = "A")
public class A {
#OneToMany(mappedBy = "a")
private B b;
}
#Entity
#Table(name = "B")
public class B {
#ManyToOne(fetch = FetchType.LAZY)
#JoinColumn(name = "a_id")
private A a;
#OneToOne(mappedBy = "b", fetch = FetchType.LAZY)
private C c;
}
#Entity
#Table(name = "C")
public class C {
#OneToOne(fetch = FetchType.LAZY)
#JoinColumn(name = "b_id")
private B b;
}
I'm using JpaRepository with #Query annotation and I implemented the following query:
#Query("SELECT DISTINCT(a) FROM A a "
+ "LEFT JOIN FETCH a.b as b"
+ "WHERE a.id = :id ")
A findById(#Param("id") Integer id);
I want retrieve the informations about class A and B, but not C.
Somehow (I don't know why) the query try to retrive also the relation between B and C.
And then, with hibernate, start the lazy invocation for retrieving C.
Naturally, if I fetch also the relation between B and C (adding LEFT JOIN FETCH b.c as c) that's not happen.
My question is, why? Why I'm forced to fetch all nested relations and not only the ones which I need?
thank you.
Carmelo
Nullable #OneToOne relation are always eager fetched as explained in this post
Making a OneToOne-relation lazy
Unconstrained (nullable) one-to-one association is the only one that
can not be proxied without bytecode instrumentation. The reason for
this is that owner entity MUST know whether association property
should contain a proxy object or NULL and it can't determine that by
looking at its base table's columns due to one-to-one normally being
mapped via shared PK, so it has to be eagerly fetched anyway making
proxy pointless.
Shot in the dark, but there are some issues with lazy-loading #OneToOne-relationships. At least in older versions of Hibernate. I think (but can't seem to find any documentation) that this was fixed in one of the newer versions, so if you are not using a new version of Hibernate, try upgrading.
I have Item.java entity with below properties
#OneToMany(cascade=CascadeType.ALL, mappedBy="kitItem", fetch=FetchType.EAGER)
private Set<KitItemDetails> kitItemDetails = new HashSet<KitItemDetails>(0);
.... Other properties with getter and setter
I have KitItemDetails.java entity with below properties
#ManyToOne(cascade=CascadeType.ALL)
private Item kitItem;
In my DAO access class we are using below query to fetch all items with other related attributes as EAGER
List<Item> items = getCurrentSession().createCriteria(Item.class).addOrder(Order.asc("itemOrder"))
.list();
But for this its firing n select queries to fecth item details as below
select kititemdet0_.kitItem_id as kitItem_2_9_0_, kititemdet0_.id as id1_12_0_, kititemdet0_.id as id1_12_1_, kititemdet0_.kitItem_id as kitItem_2_12_1_, kititemdet0_.ITEM_ID as ITEM_ID3_12_1_, item1_.id as id1_9_2_, item1_.BAR_CODE as BAR_CODE2_9_2_, item1_.COLOR_CODE as COLOR_CO3_9_2_, item1_.IS_ACTIVE as IS_ACTIV4_9_2_, item1_.ITEM_CATEGORY_ID as ITEM_CA14_9_2_, item1_.ITEM_CODE as ITEM_COD5_9_2_, item1_.ITEM_DISP_NAME as ITEM_DIS6_9_2_, item1_.ITEM_IMAGE as ITEM_IMA7_9_2_, item1_.ITEM_NAME as ITEM_NAM8_9_2_, item1_.ITEM_ORDER as ITEM_ORD9_9_2_, item1_.ITEM_PRICE as ITEM_PR10_9_2_, item1_.ITEM_PRICE_WITH_TAX as ITEM_PR11_9_2_, item1_.ITEM_SUB_CATEGORY_ID as ITEM_SU15_9_2_, item1_.ITEM_TYPE as ITEM_TY12_9_2_, item1_.TAX_ID as TAX_ID16_9_2_, item1_.TAX_CODE as TAX_COD13_9_2_, itemcatego2_.id as id1_10_3_, itemcatego2_.COLOR_CODE as COLOR_CO2_10_3_, itemcatego2_.IS_ACTIVE as IS_ACTIV3_10_3_, itemcatego2_.ITEM_CATEGORY_NAME as ITEM_CAT4_10_3_, itemcatego2_.LOCATION_ID as LOCATION6_10_3_, itemcatego2_.PRINTER_NAME as PRINTER_5_10_3_, itemsubcat3_.id as id1_11_4_, itemsubcat3_.COLOR_CODE as COLOR_CO2_11_4_, itemsubcat3_.IS_ACTIVE as IS_ACTIV3_11_4_, itemsubcat3_.ITEM_CATEGORY_ID as ITEM_CAT5_11_4_, itemsubcat3_.ITEM_SUB_CATEGORY_NAME as ITEM_SUB4_11_4_, tax4_.id as id1_21_5_, tax4_.IS_ACTIVE as IS_ACTIV2_21_5_, tax4_.LOCATION_ID as LOCATION6_21_5_, tax4_.TAX_CODE as TAX_CODE3_21_5_, tax4_.TAX_NAME as TAX_NAME4_21_5_, tax4_.TAX_PER as TAX_PER5_21_5_ from KIT_ITEM_DETAILS kititemdet0_ inner join ITEM item1_ on kititemdet0_.ITEM_ID=item1_.id left outer join ITEM_CATEGORY itemcatego2_ on item1_.ITEM_CATEGORY_ID=itemcatego2_.id left outer join ITEM_SUB_CATEGORY itemsubcat3_ on item1_.ITEM_SUB_CATEGORY_ID=itemsubcat3_.id left outer join TAX tax4_ on item1_.TAX_ID=tax4_.id where kititemdet0_.kitItem_id=?
I tried with mappedBy, JoinColumn, JoinType, FetchMode, etc but did not worked out, what could be the issue ?
In general, having a relation set as EAGER does result in the "N select queries" problem when using criteria queries. You can overcome this by explicitly instructing Hibernate to do a fetch join. See the Hibernate documentation for more details.
The documentation contains an example very similar to your scenario (tweaked to use your class names):
CriteriaBuilder builder = entityManager.getCriteriaBuilder();
CriteriaQuery<Item> query = builder.createQuery( Item.class );
Root<Item> root = query.from( Item.class );
root.fetch( "kitItemDetails", JoinType.LEFT);
query.select(root).where(
builder.and(
builder.equal(root.get("foo"), foo),
builder.equal(root.get("bar"), bar)
)
);
Item item = entityManager.createQuery( query ).getSingleResult();
// Alternatively, .getResultList() to return List<Item>
#Fetch(FetchMode.JOIN) will not work in your case because, as the documentation goes on to state in its example for FetchMode.JOIN:
The reason why we are not using a JPQL query to fetch multiple Department entities is because the FetchMode.JOIN strategy would be overridden by the query fetching directive.
#Entity
class A{
#OneToOne(optional=true)
#JoinColumn(foreignKey = #ForeignKey(name = "FK_USER"), nullable = true)
B b;
..other fields...
}
#Entity
class B{
....
}
I want to fetch rows of table A.
I'm making jpql request
select new ADTO(b,..other fields(don't necessarily all)...) from A
(ADTO - data transfer object)
And it's works, but just when A::b not null.
If A::b is null this row doesn't selects.
And if i Have another request, it works good, even if rows content null A::b
select new ADTO(..filds without A::b...) from A
How can i select row with nullable A::b?
To not getting confused with aliases and entity names, I rename your Entities A and B to Parent and Child then it would be queried with an outer join like this:
select new ParentDTO(c, p.otherfield) from Parent p left join p.child c
Here is my problem:
I have this class it has few #oneToMany collections
public class ActivePropertyList implements Serializable
{
#OneToMany
#JoinTable(name = "PropertyAttributeLink",
joinColumns =
#JoinColumn(name = "EANHotelID"),
inverseJoinColumns =
#JoinColumn(name = "AttributeID", referencedColumnName="AttributeID"))
private Collection<AttributeList> attributeList;
#OneToMany(fetch= FetchType.LAZY)
#JoinColumn(name="EANHotelID")
private Collection<Hotelimageslist> hotelimageslist;
#OneToMany(fetch= FetchType.LAZY)
#JoinColumn(name="EANHotelID")
private Collection<Roomtypelist> roomtypelist;
//Getters & Setters ...
When I access this object from XHTML it takes too long to generate as I use <ui:repeat value=#{controller.ActivePropertyList.attributeList}> ...
PropertyAttributeLink has more than 5Mil rows and Images has more than 4Mil rows but when i use simple SQL query innerJoin i takes no more than few ms to generate Lists.
I've tried using namedQuery on AttributeList using HQL query but as AttributeList has no reference to ActivePropertyList as it is unidirectional #oneToMany it throws error on doing so.
Is there a way to create HQL NamedQuery to access each list just once and store it in controller?
something like
public List<AttributeList> getAttributeListByHotelID(int hotelID){
Query q = session().createQuery("from AttributeList AL inner join PropertyAttributeLink PA where PA.hotelID=:hotelID");
return q.list();
}
but this method doesn't work as hql needs AttributeList to know about PropertyAttributeLink
Pointing the joins just make the atributtes available for where conditions and other stuff, you should use FETCH to make the relations eager and have it inmediatly, avoiding the lazy iniciators, something like
from AttributeList AL inner join FETCH PropertyAttributeLink PA where PA.hotelID=:hotelID
As you see isn't so hard, i hope that helps you, you can get more information, as always, in the docs HQL - Associations and joins