How to convert nested SQL to HQL

前端 未结 4 1565
-上瘾入骨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

    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.

提交回复
热议问题