views:

470

answers:

4

Suppose that I have the following HQL:

String hql = "select e.aField from MyEntity as e";

If I want to refactor and change the name of the MyEntity's member variable aField to something else, I also have to change all occurrences in the whole code in Strings. If I forget to change one hql string the code breaks.

How can I avoid this from happening?

A: 

you cannot since they are only strings (hard to refactoring by definition)

dfa
+2  A: 

Use an IDE that's smart enough to know how to do it for you, like IntelliJ. If I rename a class or variable, IntelliJ finds every use and manages the change for me.

duffymo
+3  A: 

You can used NamedQueries - you put your HQL as value of annotation on any entity and they are compiled to SQL at start-up time. if you have any errors in hql you wont be able to start your WebApp.

01
A: 

Options: 1. Use Criteria instead of HQL 2. Use NHibernateToLinq 3. create an enum of all of your attributes for each class and use that in you HQL (concatenation required)

epitka
With criteria you also need to have the field names as strings. Restrictions.eq("fieldname", foo) - this has the same problem with refactoring.
davidsheldon