JPQL parameter on FROM clause

Hello… I don’t like this code… id like to send the entity name as a parameter instead of concatenating it.
Is there a way It can be done? Seems like parameters only work on the where clause?

public Integer generate(String entityName) {
entityName = “ambiente_” + entityName;
Integer codigo = dataManager.
loadValue(“SELECT MAX(s.codigo) FROM " + entityName + " s”, Integer.class)
//loadValue(“SELECT MAX(s.codigo) FROM :entityName s”, Integer.class)
//.parameter(“entityName”, entityName)
return codigo == null ? 1 : codigo + 1;

Thank you for the continued support

please use the backticks or the code construct when pasting code here and perhaps leave out irrelevant code. The code is pretty much unreadable without the auto formatting.

This is actually not really a Cuba thing, it is how jpa and jpql work.Adding the + is a bit weird to me since you are referring to the declared entity name as defined on the @Entity annotation.

If you want full compile time typed checking you can use the JPA criteria api. But this means you should switch from datamanager to entitymanager and use the underlying eclipselink criteria api Make sure to read EntityManager vs DataManager

    private Persistence persistence;

    public void query() {

1 Like

Man !! Thank you so much… I was trying to look for that criteriaBuilder. A search in the manual does not return any hits. I later tried to run the QueryDSL. Couldnt get it to run… This really helped me a lot !!! Thank you once again !!

public Integer generate(String columna, Class<?> clazz) {
    EntityManager em = persistence.getEntityManager().getDelegate();
    CriteriaBuilder cb = em.getCriteriaBuilder();
    CriteriaQuery<Integer> cq = cb.createQuery(Integer.class);
    Root<?> root = cq.from(clazz);;
    Integer codigo = em.createQuery(cq).getSingleResult();
    return codigo == null ? 1 : codigo + 1;
1 Like