我想避免在代码中将列名作为字符串。有没有其他方法可以实现这一目标?:
String query = "SELECT c.foo1.columnA, c.foo1.foo2.columnB FROM Table c";
session.createQuery(query).list();
我可以通过拆分并获取c.foo1.foo2.columnB
,属性ClassMetadata
和其他Hibernate函数来遍历列作为Type
之类的字符串,直到我到达最后一个元素。但是,我无法想到从Java bean获取列字符串的方法,也可以迭代属性。
答案 0 :(得分:1)
不确定是什么意思。几个想法
如果您担心属性名称错误的可能性,那么当前的IDE通过验证JPA查询中的属性名称可以做得很好
对象反射可以为您提供属性名称。但不一定所有属性都映射到列。您可以查看this并通过反射将其与bean属性名一起使用。
希望有所帮助。
答案 1 :(得分:0)
There is no way to achieve what you are looking for. But, if your concern is correctness of these queries and worry that the problem will not be known until the execution hits this, you could use NamedQuery
@Entity
@NamedQuery(
name="findAllEmployeesByFirstName",
queryString="SELECT OBJECT(emp) FROM Employee emp WHERE emp.firstName = 'John'"
)
public class Employee implements Serializable {
...
}
Usage
List employees = em.createNamedQuery("findAllEmployeesByFirstName").getResultList();
The benefit is that queries defined in NamedQuery
annotations are compiled to actual SQL at start up time. So incorrect field references(typo etc) will cause a start up error and the application will not start.
Another option will be as mentioned in the other answer to trust in a good IDE to refactor all occurrences properly when you rename fields (Idea does a great job at this, so would any other IDE)
EDIT: I do not think there is any performance degradation with named queries. Rather it may appear to be faster as compiled queries are cached(very subjective)
Finally, its better to use the actual query as-is as mentioned in comments. It is far more readable and debug in its context. If you are concerned about correctness, unit-test the heck out of it and be confident.