merveotesi
merveotesi

Reputation: 2193

Join in Hibernate Query

I have classes:

class User{
String id;
ArrayList<UserAttribute> attributeList=new ArrayList<UserAttribute>();
}

class UserAttribute{
User user;
String value;
String key;
}

I have tables associated to classes.

table user

column id

table user_attribute

column user_id
column key
column value

example user table content

user_id="123"

user_id="234"

example user_attribute table contents

user_id="123", key="address", value="green house street"

user_id=234, key="address", value="blue house street"

user_id="123", key="phone", value="234324"

user_id="234", key="phone", value="786988"

I want to get the user who has address "green house street" and(not or) has phone "234324"

I write sql(oracle) in sql editor:

 select u.* from user u left join user_attribute prop on u.id=prop.user_id inner join user_attribute prop2 on prop.user_id = prop2.user_id where prop.value = 'green house street' and prop.key = 'address' and prop2.key ='phone'  and prop2.value = '234324';

I tried many thing on hibernate side: but cannot use join because get

"unecpected token on"

error when using "on" clause.

in the end I wrote

entityManager.createQuery(
select u from User u, u.attributeList prop, u.attributeList prop2 where prop.value = :address and prop.key = :key and prop2.key =:key2  and prop2.value = :phone and prop.user.id=u.id and prop2.user.id=u.id and prop2.user.id=prop.user.id
)..setParameter("key", "address")
                .setParameter("phone", "234324")
                .setParameter("key2", "phone")
                .setParameter("address", "green house street").getSingleResult();

still no chance,

I try hard to find a single query solution but cannot achive so far. Thanks for any idea.

Upvotes: 1

Views: 10293

Answers (2)

swapy
swapy

Reputation: 1616

Hibernate is having problem with "on" clause .

Use native sql query..

plz refer HQL Problem

Upvotes: 1

JB Nizet
JB Nizet

Reputation: 692161

You need to make two joins, but don't need to specify any on clause, since Hibernate knows, thanks to the mapping of the association, how the tables are linked together. So the following query should work:

select u from User u
inner join u.attributeList a1
inner join u.attributeList a2
where a1.value = 'green house street' and a1.key = 'address' 
and a2.key ='phone' and a2.value = '234324'

Upvotes: 6

Related Questions