简体   繁体   中英

enum to string in JPQL select query

I am facing problem in converting java enum to string conversion. Please if you have any idea.

String mainQuerySt = "select o.ttType from Tt o";

Query mainQuery = em.createQuery(mainQuerySt);
List result = mainQuery.setFirstResult(offset).setMaxResults(numofRecords).getResultList();

I want the string representation of ttType enum . How to do it?

My Tt Definition:

@Enumerated(EnumType.ORDINAL)
@Column(name = "tt_type", nullable = false)
private TTType ttType;   

My enum TTType definition:

public enum TTType
{
    FC,
    PD
    ;

    @Override
    public String toString()
    {
        switch (this)
        {
            case FC:
                return "FC";
            case PD:
                return "PD";
            default:
                throw new AssertionError();
        }
    }
}

I can't use EnumType.STRING in @Enumerated now since the system is live.

Please reply.

One option may be to use enum constructor as bellow:

public enum TTType {
    FC("FC"),
    PD("PD");

    private String value; // the value

    // Constructor 
    TTType(String value) {
        this.value = value;
    }

    public String getValue() {
        return this.value;
    }

    public String toString() {
        return this.value;
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM