chi*_*tiz 3 java hibernate projection resulttransformer hibernate-criteria
我有一对多关系所有者 - >狗.
我将通过ID查询狗以及以EAGER方式引入所有者我使用Hibernate 4.1.6设置此代码而不使用XML映射.我只需要来自DOG和OWNER的一些字段使用Projections Hibernate生成的SQL是完美的,但是我的对象没有填充,因为DOG返回填充的字段但是返回的所有者是 DOG.OWNER==NULL我到目前为止使用的代码...我的entities.other代码省略简洁
@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;}
}
Run Code Online (Sandbox Code Playgroud)
这是我的方法.
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.
}
Run Code Online (Sandbox Code Playgroud)
这里的查询很完美就是SQL
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 = ?
Run Code Online (Sandbox Code Playgroud)
我的问题是...狗实例不是空的,所有的字段都可以,同时Dog.Owner是returnig null我试过这个不使用任何变形金刚.
Object[]obj=(Object[])like.uniqueResult(); for(Object id:obj)System.out.println(id);
System.out.println(obj.length);
Run Code Online (Sandbox Code Playgroud)
我可以看到数据正确Hibernate没有返回我的对象的权利吗?我做错了什么.
任何帮助都非常感激.
[更新]如果我使用这个
Projection p=Projections.projectionList()
.add(Projections.property("d.id"),"id")
.add(Projections.property("o.status"),"status");
Run Code Online (Sandbox Code Playgroud)
和状态属于两个表,DOG实体填充另一个不是.
如果我使用
Projection p=Projections.projectionList()
.add(Projections.property("d.id"),"id")
.add(Projections.property("o.address"),"address");
Run Code Online (Sandbox Code Playgroud)
和地址只属于所有者异常被抛出.
Exception in thread "main" org.hibernate.PropertyNotFoundException:
Could not find setter for address on class com.generic.model.Dog
Run Code Online (Sandbox Code Playgroud)
似乎Hibernate总是返回最大1实体填充它们不能将两个表[selected columns]填充到对象[selected objects]中?
| 归档时间: |
|
| 查看次数: |
6126 次 |
| 最近记录: |