How to convert nested SQL to HQL

2019-02-12 04:57发布

I am new to the Hibernate and HQL. I want to write an update query in HQL, whose SQL equivalent is as follows:

update patient set 
      `last_name` = "new_last", 
      `first_name` = "new_first" 
where id = (select doctor_id from doctor 
            where clinic_id = 22 and city = 'abc_city');

doctor_id is PK for doctor and is FK and PK in patient. There is one-to-one mapping.

The corresponding Java classes are Patient (with fields lastName, firstName, doctorId) and Doctor (with fields doctorId).

Can anyone please tell what will be the HQL equivalent of the above SQL query?

Thanks a lot.

4条回答
老娘就宠你
2楼-- · 2019-02-12 05:09

There is a significant difference between executing update with select and actually fetching the records to the client, updating them and posting them back:

UPDATE x SET a=:a WHERE b in (SELECT ...) 

works in the database, no data is transferred to the client.

list=CreateCriteria().add(Restriction).list();

brings all the records to be updated to the client, updates them, then posts them back to the database, probably with one UPDATE per record.

Using UPDATE is much, much faster than using criteria (think thousands of times).

查看更多
爷的心禁止访问
3楼-- · 2019-02-12 05:11
update Patient set last_name = :new_last , first_name = :new_first where patient.id = some(select doctor_id from Doctor as doctor where clinic_id = 22 and city = abc_city)  
查看更多
Ridiculous、
4楼-- · 2019-02-12 05:24
String update = "update Patient p set p.last_name = :new_last, p.first_name = :new_first where p.id = some (select doctor.id from Doctor doctor where doctor.clinic_id = 22 and city = 'abc_city')";

You can work out how to phrase hql queries if you check the specification. You can find a section about subqueries there.

查看更多
Melony?
5楼-- · 2019-02-12 05:26

I don't think you need HQL (I know, you ask that explicitly, but since you say you're new to Hibernate, let me offer a Hibernate-style alternative). I am not a favor of HQL, because you are still dealing with strings, which can become hard to maintain, just like SQL, and you loose type safety.

Instead, use Hibernate criteria queries and methods to query your data. Depending on your class mapping, you could do something like this:

List patients = session.CreateCriteria(typeof(Patient.class))         
    .createAlias("doctor", "dr")
          .add(Restrictions.Eq("dr.clinic_id", 22))
          .add(Restrictions.Eq("dr.city", "abc_city"))
    .list();

// go through the patients and set the properties something like this:
for(Patient p : patients)
{
     p.lastName = "new lastname";
     p.firstName = "new firstname";
}

Some people argue that using CreateCriteria is difficult. It takes a little getting used to, true, but it has the advantage of type safety and complexities can easily be hidden behind generic classes. Google for "Hibernate java GetByProperty" and you see what I mean.

查看更多
登录 后发表回答