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

1 Answers1

0

As you are not including any field of Developer in the projection list, Hibernate won't return any field of that table. But it creates an inner join with the Developer table because of the WHERE clause, as shown with this generated SQL query:

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=?

If you add in your projection list a field of Developer, Hibernate will add the field to the SELECT clause of the generated query.

Add in your code:

pl.add(Projections.property("developer.name").as("developerName"));

Add a developerName attribute in your ListOfProjectsSearchResult class if it is not present and execute again your code. The generated SQL query should be something like:

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=?
eternay
  • 3,754
  • 2
  • 29
  • 27
  • still the same, It also does not show the generated SQL query at all to compare –  Jun 26 '13 at 23:51
  • Are you sure you are executing this code? Put traces in your code to be sure you are executing it. – eternay Jun 27 '13 at 10:17