简体   繁体   中英

JPA projection with custom resulting field names

I use interface-based projections using named-native-query. My UserDTO looks like this:

public interface UserDTO {

@Value("#{target.USER_ID}")
String getId();
@Value("#{target.USER_NAME}")
String getName();
@Value("#{target.REGISTRATION_REGION}")
String getRegistrationRegion();

}

After that I marshall the list of DTOs to Json, and field names which I see there are in camel-case:

    {"USERS": [
        {
            "id": "e00000099232200",
            "name": 1616674065,
            "registrationRegion": 1617344002
        }]}

But I need them in DB style - Upper-case and with underscores like:

{"USERS": [
        {
            "ID": "e00000099232200",
            "NAME": 1616674065,
            "REGISTRATION_REGION": 1617344002
        }]}

The straightforward way is naming my DTOs methods like getNAME or getREGISTRATION_REGION or iterating over Json fields and make them upper-case there. But is there a more elegant way to set the display name? Something like this:

@Display("REGISTRATION_REGION")
String getRegistrationRegion();

If you're using Jackson you can annotate your interface with:

@JsonNaming(PropertyNamingStrategy.UpperCamelCaseStrategy.class)

Or if you want this behaviour globally across all usages of your mapper, configure it as follows:

ObjectMapper mapper = new ObjectMapper();
mapper.setPropertyNamingStrategy(new PropertyNamingStrategy.UpperCamelCaseStrategy());

EDIT: You can implement your own CaseStrategy, for your case it will be:

    class UpperSnakeCase extends PropertyNamingStrategy.SnakeCaseStrategy{
        @Override
        public String translate(String input) {
            String snakeCased = super.translate(input);
            if (snakeCased == null) {
                return null;
            }
            return  snakeCased.toUpperCase();
        }
    }

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