RBP
RBP

Reputation: 485

creating hql query for one-to-many relationship

I have two class Domain and UserProfile . The relation between them is one to many. It is defined in UserProfile Class.I have firstName of user and domain object I have to write hql query to retrive the UserProfile object. I have created like this "from UserProfile as profile where profile.domain='"+domain+"' and profile.firstName ='"+firstName+"' ". But it is not working.

can anyone tell me how should be the query.

@Entity
@Table(name="TBL_STD_DOMAIN")
public class Domain implements Serializable {

  @Id
  @GeneratedValue
  @Column(name ="FLD_DOMAIN_ID")
  private Long domainId;

  @Column(name = "FLD_DOMAIN_NAME")
  private String domainName;
}


@Entity
@Table(name="TBL_STD_USERPROFILE")
public class UserProfile {

  @Id
  @GeneratedValue
  @Column(name = "FLD_USER_ID")
  private Long userId;

  @Column(name = "FLD_First_Name")
  private FirstName firstName;

  @ManyToOne
  private Domain domain;
}

Upvotes: 0

Views: 1432

Answers (1)

JB Nizet
JB Nizet

Reputation: 691635

You should never use String concatenation to pass parameters to queries. Use query parameters instead (named, preferrably):

String hql = 
    "select u from UserProfile u"
    + " where u.firstName = :theFirstName"
    + " and u.domain = :theDomain";

return session.createQuery(hql)
              .setParameter("theFirstName", firstName)
              .setParameter("theDomain", domain)
              .list();

Upvotes: 1

Related Questions