I am having two tables in database USER_DETAILS and Address. The Entity classes for both the tables are below
@Entity
@Table(name="USER_DETAILS")
public class UserDetails {`
@Id @GeneratedValue(strategy=GenerationType.AUTO)
private int UserID;
private String UserName;
@OneToMany(cascade=CascadeType.ALL,fetch=FetchType.EAGER)
private List<Address> address=new ArrayList<>();
-------------------------------------------------------------
@Entity
public class Address {
@Id @Column(name="ADD_ID") @GeneratedValue(strategy=GenerationType.AUTO)
private int Id;
private String street;
private String city;
I want to execute a query such that it return me all the results where UserName="user1" and address.city='City1' When i execute the sql query as
SELECT u.UserName,a.street
from USER_DETAILS u, Address a
where u.UserName='user1'
and a.city='City1';
The result is
+----------+---------+
| UserName | street |
+----------+---------+
| user1 | street1 |
+----------+---------+
But when I run a criteria query for the above as
Criteria criteria=session.createCriteria(UserDetails.class,"user")
.createAlias("address", "ad")
.add(Restrictions.eq("user.UserName", "user1"))
.add(Restrictions.eq("ad.street", "street2"));
The result it shows is completely different than expected which is
user1
City2 :: street2
City6 :: street6
City4 :: street4
City8 :: street8
City0 :: street0
I tried other options like createQuery("Address")
instead of createAlias()
. but the results where same. Please give your suggestions.
Thank you
EDIT: I used HQl query similar to one i used as sql as
List<Object[]> list=session.createQuery("select u.UserName,a.street "
+" from UserDetails u,Address a"
+ " where u.UserName=:username and a.city=:cityname")
.setString("username", "user1")
.setString("cityname", "City1")
.list();
I got the same result as in sql which is the correct one. But criteria does not show the correct result.