I have One to many relationship Owner->Dog.
I am to query the dog by ID as well bring the Owner in EAGER way I have set this code using Hibernate 4.1.6 not XML mapping is used. i only need some fields from DOG and OWNER using Projections the SQL being generated by Hibernate is perfect but my objects is not being populate because DOG is returning the fields populated but owner is returned DOG.OWNER==NULL here is the code i am using so far... My entities.other code is omit by brevity
Code:
@Entity
public class Owner implements Serializable
{
Set<Dog>dogs=new HashSet<Dogs>(0);
@OneToMany(fetch=FetchType.LAZY, mappedBy="owner")
public Set<Dogs> getDogs(){return this.dogs}
}
@Entity
public class Dog implements Serializable
{
private Owner owner;
@ManyToOne(fetch=FetchType.LAZY)
@JoinColumn(name="ownerid")
public Owner getOwner(){return this.owner;}
}
here is my method.
Code:
public Dog getDogAndOwnerById(Integer dogId)
{
Projection p=Projections.projectionList()
.add(Projections.property("d.id"),"id")
.add(Projections.property("o.id"),"id");//and others fields
Session session = getHibernateTemplate().getSessionFactory().openSession();
Criteria like = session.createCriteria(Dog.class,"d")
.add(Restrictions.idEq(dogId)).setProjection(p)
.setResultTransformer(Transformers.aliasToBean(Dog.class))
.setFetchMode("owner",FetchMode.JOIN).createAlias("owner","o");
Dog dog = (Dog)like.uniqueResult();
//Object[]obj=(Object[])like.uniqueResult(); for(Object id:obj)System.out.println(id);
//System.out.println(obj.length);
session.close();
return dog;
//dog is OK BUT dog.OWNER is null.
}
the query is perfect here is the HQL
Code:
select
this_.ID as y0_,
owner_.ID as y1_
from
dog this_
inner join
owner owner_
on this_.ownerid=owner_.ID
where
and this_.ID = ?
my problem is... Dog instance is NOT null and all the fields are O.K meanwhile Dog.Owner is returnig null I have try this not using any Transformers.
Code:
System.out.println(obj.length);
Object[]obj=(Object[])like.uniqueResult(); for(Object data:obj)System.out.println(data);
And I can see the data correct what Hibernate is not returning my objects right? What I am doing wrong.
any help is hugely appreciate.
if i use thisCode:
Projection p=Projections.projectionList()
.add(Projections.property("d.id"),"id")
.add(Projections.property("o.status"),"status");
and status belongs to both tables the DOG entity is populate the other is not.
if i useCode:
Projection p=Projections.projectionList()
.add(Projections.property("d.id"),"id")
.add(Projections.property("o.address"),"address");
and adress belong only to owner exception is thrown.
Code:
Exception in thread "main" org.hibernate.PropertyNotFoundException:
Could not find setter for address on class com.generic.model.Dog
Seems that Hibernate ALWAYS return at maximun 1 entity populate[the root entity] they can't populate both tables[selected columns] into objects[selected objects]?