0

I have been reading a lot about using enums as parameters in queries. I have some queries in my project that use the value from these enums as parameters.

For example:

public enum YesNo {
Y, N
}

Query:

select ent 
from 
       Entity ent 
where
       ent.id = :id
       and ent.deleted = project.path.example.YesNo.N

Entity:

@Entity
public class Entity{
Long id;
@Enumerated(EnumType.STRING)
YesNo deleted;
}

The above works correctly as expected.

However, when I have the following:

interface Commons{
    interface MostCommonTypesofAnimals {
        long DOG = 1L;
        long CAT = 2L;
    }
}

Query

select a 
from 
       Animal a 
where
       a.id = :id
       and a.type = project.path.example.Commons.MostCommonTypesofAnimals.DOG

Entity

@Entity
public class Animal{
Long id;
Type type;
}

@Entity
public class Type{
public Long id;
}

It does not work telling me that the path is incorrect even though it is actually correct.

Is there any work around? Or interface values cannot be mapped? Can anyone provide me an example that works? I could not find anything similar.

Please note that this is just an example to illustrate the situation., those are not the real names that I am using or anything.

1 Answer 1

1

For using enum while using hibernate / jpa (based on your tags), you should use annotation in your Pojo class.

@Enumerated(EnumType.ORDINAL)

In your example, something like:

@Entity
@Table(name = "tableName")
public class entityName {
    @Enumerated(EnumType.ORDINAL)
    private YesNo yesNoEnum;
}

The annotation can go here or in the getter, as you prefer.

You can find more info here

ps: for yes or no I suggest you using a boolean value, not an enum

Sign up to request clarification or add additional context in comments.

7 Comments

Hello, @Leviand! Actually, when I use Enums, it's working as expected. The problem is when I am using an interface which has some variables on it. Check the interface Commons.
there's a concept error then: if your table is "animal", that should be represented by a class, not an interface. Try to rework your code in that way. And also if you are using an interface into another one, use instead extends
My entity class is Animal. My interface class which is Commons, has another interface on it, named Animals.
Or: If you want to use the Animals as a value for queries, transform that into Enum, and set the enum to EnumType.ORDINAL
Can this helps you somehow ? -> stackoverflow.com/a/2301329/1984767
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.