我有两个表具有ManyToOne关系。我需要显示我的ManyToOne关系的特定行,但是在页面和控制台中都不会显示任何内容。 (它甚至没有显示生成的SQL,尽管Hibernate显示了生成的代码的其他部分的SQL)
Project.java
@Entity
@Table(name = "Project")
@DynamicUpdate
public class Project implements Serializable{
private int id;
private String Name;
private Developer developer;
@Id
@GeneratedValue
public int getID() {
return id;
}
@ManyToOne(cascade = CascadeType.ALL)
public Developer getDeveloper() {
return developer;
}
....
}
Developer.Java
@Entity()
@Table(name = "developer")
@DynamicUpdate
public class Developer implements Serializable {
private int id;
private String name;
@Id
@GeneratedValue
public int getID() {
return id;
}
.....
}
Model.Java
Criteria criteria = session.createCriteria(Project.class, "project")
.createAlias("project.developer", "developer");
try{
ProjectionList pl = Projections.projectionList();
pl.add(Projections.property("project.id").as("id"));
pl.add(Projections.property("project.name").as("name"));
criteria.setProjection(pl);
criteria.setResultTransformer(new
AliasToBeanResultTransformer(ListOfProjectsSearchResult.class));
criteria.add(Restrictions.eq("developer.id", 1));
}catch(Exception e){
e.printStackTrace();
}
return criteria.list();
答案 0 :(得分:0)
由于您未在投影列表中包含Developer
的任何字段,因此Hibernate不会返回该表的任何字段。但是由于WHERE
子句,它会使用Developer表创建内部联接,如此生成的SQL查询所示:
select
this_.id as y0_,
this_.name as y1_
from Project this_
inner join developer developer1_
on this_.developer_id=developer1_.id
where developer1_.id=?
如果您在投影列表中添加Developer
字段,Hibernate会将该字段添加到生成的查询的SELECT
子句中。
添加您的代码:
pl.add(Projections.property("developer.name").as("developerName"));
在developerName
课程中添加ListOfProjectsSearchResult
属性(如果该属性不存在)并再次执行您的代码。生成的SQL查询应该类似于:
select
this_.id as y0_,
this_.name as y1_,
developer1_.name as y2_
from Project this_
inner join developer developer1_
on this_.developer_id=developer1_.id
where developer1_.id=?