1

I have two tables which have ManyToOne relationship. I need to shows specific rows of my ManyToOne relationship, but nothing will be shown in neither the page nor the console. (It does not even show the generated SQL although Hibernate shows the generated SQL of other parts of my code)

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();
4

1 回答 1

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=?
于 2013-06-26T07:41:15.530 回答