tags:

views:

42

answers:

2

Given this Hibernate snippet

@org.hibernate.annotations.NamedQueries({
    @org.hibernate.annotations.NamedQuery(
        name = "ASSIGNED_CONTINGENCIES",
        query = "select ctg.id from Cont ctg join ctg.labels cl where cl.id = :label_id and ctg.datasetId = tscommon.rdsidtodsid(:datasetting_id)...."
    )
})

Does it mean that everytime I execute this, is the "query" string being created every time or is this a case of string internment? Would it be beneficial to have query in a final static String QUERY and then use it in the @NamedQuery? Would the same be also valid for "name" then?

+1  A: 

The String is a String literal, and so is always going to be interned when the class is loaded.

skaffman
+1. With emphasis on "class is loaded" rather than "query is executed" as OP mentioned.
ChssPly76
So guess I was right it's a case of internment and there is no reason to assign it to a static final, thanks.
non sequitor
+1  A: 

There is no performance or memory benefit, but it might be useful to use constants for the query names to avoid typographic errors, as in this example:

// Entity class
@NamedQueries({@NamedQuery(name=MyBean.FIND_BY_ID, query="select o from MyBean o where o.id = :id")})
public class MyBean {
    public static final String FIND_BY_ID = "MyBean.findById";
}

// Controller/Service/Factory/whatever
em.createNamedQuery(MyBean.FIND_BY_ID).setParameter("id", id).getSingleResult();
Jörn Horstmann
This seems rather overkill, to be honest. If you mistype a query name, you'll get an exception thrown when you try to load it.
ChssPly76
I prefer a compiler error to a RuntimeException any time. It also makes it easier to refactor query names and find usages / unused queries in a IDE.
Jörn Horstmann