How to convert nested SQL to HQL

前端 未结 4 1554
-上瘾入骨i
-上瘾入骨i 2021-01-02 01:52

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_         


        
相关标签:
4条回答
  • 2021-01-02 02:04
    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.

    0 讨论(0)
  • 2021-01-02 02:04

    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.

    0 讨论(0)
  • 2021-01-02 02:04

    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).

    0 讨论(0)
  • 2021-01-02 02:19
    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)  
    
    0 讨论(0)
提交回复
热议问题