Reputation: 1155
May I know what is the recommended way to retrieve a entity property name
for example to retrieve an object..
Product product = criteria.add(Restrictions.eq("productID",productId))
.uniqueResult();
List cats = sess.createCriteria(Cat.class)
.add( Restrictions.like("name", "Fritz%") )
.add( Restrictions.between("weight", minWeight, maxWeight) )
.list();
...
But I don't wish to to hard code the "productID" or "name" or "weight", what are the recommended solution to problem?
Upvotes: 0
Views: 564
Reputation: 692071
First solution: hard-code them in one place, using constants. This solution is awful though, because your code will become less readable, and you still have the risk of having incorrect column names in your constants.
Second solution: leave it as it is, and unit-test your queries. The code will stay readable, and your unit tests will make sure you don't have incorrect names.
Third solution: use the JPA API, and use the JPA2 criteria API, with the automatically generated metamodel. The queries will then look like this:
CriteriaBuilder cb = entityManager.getCriteriaBuilder();
CriteriaQuery<Order> cq = cb.createQuery(Order.class);
SetJoin<Order, Item> itemNode = cq.from(Order.class).join(Order_.items);
cq.where( cb.equal(itemNode.get(Item_.id), 5 ) ).distinct(true);
Where Order_
and Item_
are auto-generated metamodel classes holding attributes for every column and association of the Order
and Item
entities respectively. Beware that, IMHO, the JPA2 criteria API is a non-intuitive, hard to use API that doesn't make code very readable.
By all means, use HQL/JPQL every time you can instead of criteria queries: they are much more readable IMHO. Criteria queries are useful when a query must be dynamicall generated based on various optional criteria, or when you have a whole lot of complex, similar queries and you can reuse a common part. But for the majority of the cases, HQL is much more readable. You need to unit-test your queries anyway. So these tests will check that the properties names are correct.
Upvotes: 2