Sleeping request by type enum

I need to get data from a database by enum type. I have the following enum:

public enum ShopType {
    VANS("VANS"), ATTICUS("ATTICUS"), FAMOUS("FAMOUS")

    ShopType(String label) {
        this.label = label;
    }

    private String label;

    public String getLabel() {
        return label;
    }

    public void setLabel(String label) {
        this.label = label;
    }
}

      

In my DAO class, I have a method that returns a list of objects by the selected type on the page jsp

. On the page, jsp

I am sending the selected value, for example String

, is it correct?

This is what my method looks like

@Transactional
public List<Shop> findByType(String type) {
    return sessionFactory.getCurrentSession().createQuery("from Shop where type=" + .....  .list();
}

      

I don't know how to create a correct query. I store the Enum in my database as tinyint.

Here's the model.

@Column(name = "type")
@Enumerated(EnumType.ORDINAL)
private ShopType type;

      

+3


source to share


2 answers


As you are specifying your enum as an ordinal then you must use an ordinal in your query. Example

@Transactional
public List<Shop> findByType(String type) {
    return sessionFactory.getCurrentSession().createQuery("from Shop where type=" + ShopType.valueOf(type).ordinal()).list();
}

      

If you change @Enumerated(EnumType.STRING)

then your request will look like this:



@Transactional
public List<Shop> findByType(String type) {
    return sessionFactory.getCurrentSession().createQuery("from Shop where type=" + ShopType.valueOf(type).name()).list();
}

      

ShopType.valueOf(type)

... This will only work if the string type is the same as the enum name. Also, if your label is the same as the enum name, you don't need the label. ShopType.VANS.name()

is equal "VANS"

and the name()

method is final, you can be sure that it cannot be overridden.

+5


source


Just convert String to Enum and use the request name parameter



@Transactional
public List<Shop> findByType(String type) {
    ShopType enumType = shopTypeFromString(type);
    return sessionFactory.getCurrentSession().createQuery("from Shop where type=:p_type")
        .setParameter("p_type", enumType).list();
}

private ShopType shopTypeFromString(String type) {
    // You can implement this convertion in your own way
    return ShopType.valueOf(type);
}

      

+4


source







All Articles