1

I have two class such as:

@Entity
public class Customer{
    @Id
    private String id;
    private String name;
    @Column(nullable=false, unique=true)
    private String refId;
}


@Entity
public class Account{
    @Id
    private String id;
    @Column(nullable=false, unique=true)
    private String accountNr;
    @Column(nullable=false)
    private String accountType;
    @Column(nullable=false, unique=true)
    private String refId;
}

I want to join this two classes on refId for ordering on a field of Account such as:

select c.* from Customer as c inner join Account as a on a.refId=c.refId orderBy a.accountType

Is there any way to do such query in criteria

bdogru
  • 812
  • 1
  • 11
  • 19

2 Answers2

1

You should use relationships between tables e.g. @OneToOne, @ManyToOne.
After that it will be easy to write HQL.
You can read more about it here.

Alex
  • 11,451
  • 6
  • 37
  • 52
  • but in my case classes are not reffering to each other it is a oneToOne relation but not on primary keys – bdogru Jul 14 '14 at 14:28
1

Hibernate doesn't normally allow you to do an "at-demand" join via Criteria as in your SQL query. However, this appears to indeed be possible using a work-around of having multiple Criterias.

But if you follow Alex's suggestion to map an association in your Entity classes, you can create a much simpler Criteria like this, as Customer would have an account object already "mapped" to it:

Criteria criteria = session.createCriteria(Customer.class)
        .createCriteria("account")
        .addOrder(Order.asc("accountType"));

To do the associations, in your Entity classes you could replace the refId field with the relating object. So, in the Customer class, you could have an Account object association, like so (and vice versa):

@Entity
public class Customer {
    // Instead of "refId" field:
    @OneToOne(mappedBy = "customer")
    private Account account;
}

@Entity
public class Account {
    // Instead of "refId" field:
    @OneToOne
    @JoinColumn(name = "refIdColName")
    private Customer customer;
}

Assuming this was a one-to-one relationship. You don't need to reference the primary key in one-to-one mapping.

Community
  • 1
  • 1
Roy Six
  • 259
  • 3
  • 5
  • given link (DetachedCriteria) worked as expected, refId is what is desired, I have no option but proceed that way. thanks anyway. – bdogru Jul 15 '14 at 14:33