I have a column in database with 5 possible values. I want to map this column as an enum field. The problem is some of these values contain a dash. I tried something like this:
public enum Status {
S1("S1"), S2("S2"), S3("S-3"), S4("S-4"), S5("S5");
private final String text;
Status(String text) {
this.text = text;
}
#Override
public String toString() {
return this.text;
}
But it doesn't work. If the row in database contains value with a dash, I get an error:
Unknown name value [S-3] for enum class [test.package.Status]
Is there any way to map values containing dash to an enum?
The toString() do not work as the evaluation of enum is based on public final String name(). And as this is final you can not override it.
You will have to use another type. In this answer you will get the required info.
have u tried this one in your model
#Enumerated(EnumType.STRING)
Status status
Related
I have a List of ProcessedClass (POJO I have created) that I would like to generate to a string of comma-delimited values. So all items in the list output to a single, comma-delimited list.
My plan is to: pass the list into a method, iterate through the list and append commas and finally remove the last comma and return the resulting string. The object being processed will have some nested POJO's with multiple different variable types (string, int, boolean, other POJO's, LocalDate etc..). I have added an example of the structure below.
My question is what is the best way to go about constructing this? Thank you in advance.
Example structure being processed:
//List<ProcessedClass> will be passed into the iternation method
public class ProcessedClass {
private Other other;
private Info info;
}
public class Other {
private String stringMessage;
private boolean booleanValue;
...
}
public class Info {
//Another defined POJO
private User user;
private LocalDate date;
private String name;
...
}
You can use StringJoiner with , delimiter.
StringJoiner stringJoiner = new StringJoiner(",");
processedClasses.forEach(a -> stringJoiner.add(a.toString()));
System.out.println(stringJoiner);
Of course, you have to implement the toString method in all defined classes.
I have an enum with enum values. I want to print the list of the enum values only.
Not just the enum. I have read about Value Of but see thats not the correct way to go at it.
This is what I want printed:
People Out
People In
Here is my enum with values in it. I added a constructor.
public enum People {
OUT("People out"),
IN("People in");
private final String name;
People(String name) {
this.name = name;
}
}
The method to retrieve the enums is:
public String retrieveEnumValues() {
return Stream.of(People.values()).
map(People::name).collect(Collectors.joining("\n"));
}
What am I doing wrong here?
People::name refers to standard enum's method name(), you should provide getter for your name field and using it People::getName.
I was looking arround for this, but I couldn´t find a right answer.
I´m trying to get any field from an entity based on it´s column name.
Like a generic get, in which it receives a String columnName and returns an Object field that represents the Class field which is mapped by that columnName by Hibernate.
For example
#Table(name="ENTITY_EXAMPLE")
public class EntityExample{
#Column(name="COL_NAME")
private String name;
#Column(name="COL_SURNAME")
private String surname;
public EntityExample(String name, String surname){
this.name=name;
this.surname=surname;
}
//getters and setters
public Object getField(String columnName){
Object field=//some way to map the columnName with the field;
return field;
}
}
public main(String[] args){
EntityExample example=new EntityExample("John", "Doe");
String exampleName=(String) example.getField("COL_NAME");
String exampleSurname=(String) example.getField("COL_SURNAME");
System.out.println("NAME: "+ exampleName+ ", SURNAME: "+exampleSurname);
}
and that main when runs should print:
NAME: John, SURNAME: Doe
The way I´m doing now is with ifs that checks if the parameter is equal to each annotated column and inside returns the field if equals, but it should be a propper way to do that.
way I'm doing now:
public Object getField(String columnName){
if(columnName.equals("COL_NAME")){
return name;
}
if(columnName.equals("COL_SURNAME")){
return surname;
}
}
Thanks in advance.
As far as I know, the way you're doing it, is the only way. With the exception being, to use a switch statement instead of multiple if statements:
switch (columnName) {
case 1: columnName = "COL_NAME";
return this.name;
break;
case 2: columnName= "COL_SURNAME";
return this.surname;
break;
default: columnName= "COL_BLAHBLAH";
return this.blahblhblah;
break;
}
The only possible way to what you want (and this is a big stretch), is if you did something along the lines of:
public Object getField(String columnName){
Object field= (Object)columnName;
return field;
}
Note: You would need to pass in the object name (aka: name,surname) and not the column name.
But I honestly don't think this is going to work. Regardless, you would need to cast a string as an object in such a way that the compiler would know how to handle the casting properly (don't think it's possible).
Good luck either way. Maybe someone else will have more ideas.
You can , of course, use reflection to go through the fields of your entity, looking for which one has the #Column annotation with the corresponding name. However, many people will tell you that Reflection is slow.
What we did to accomplish this was to create a set of public static integer constants for each of the columns. Thus in your entity you would have the following:
public static final int COL_NAME = 1;
public static final int COL_SURNAME = 2;
and in the Entity you also have a getFieldValue method as follows:
public Object getFieldValue(int fieldNo) {
switch (fieldNo) {
case COL_NAME:
return this.name;
case COL_SURNAME:
return this.surname;
default:
throw IllegalArgumentException("Invalid Field Number: " + fieldNo);
}
}
and you would use these to get fields values as follows:
String name = entityExample.getFieldValue(EntityExample.COL_NAME);
Of course, the problem you have now is maintaining both the list of constants and the switch cases when columns are added/removed/renamed. We get round this by using a script to generate both the constants and the method. You could also use Java's annotation processing to generate the same code.
I have an Enum
public enum status{
YES,
NO
}
the input from json string is "Yes" or "No", is there any method in ObjectMapper to match status.YES with "Yes", and status.NO with "No".
I don't want to change enum, because int my previous system, people use the enum all the time, I don't want cause problem for others
You can always redefine it like:
public enum Status {
YES("Yes"),
NO("No");
private final String status;
private Status(final String status) {
this.status = status;
}
public String value() {
return this.status;
}
}
And then use something like this: Status.YES.value();
You can use toString() method available in all Java enums:
http://docs.oracle.com/javase/7/docs/api/java/lang/Enum.html
and on returned String call compareToIgnoreCase method to compare it with input:
http://www.tutorialspoint.com/java/java_string_comparetoignorecase.htm
Or you can call toUpperCase on input String and then comapre them:
http://www.tutorialspoint.com/java/java_string_touppercase.htm
Finally, you can use toString mentioned earlier and put all letters except the first to lower case:
String YesString = enumWithYESValue.toString().substring(0, 1) + enumWithYESValue.toString().substring(1).toLowerCase();
Based on: How to capitalize the first letter of a String in Java?
I should take from a variable enum its value and transform it to string.how can i do?
here it is the type enum:
public enum State{
b,c,p;
};
now i have to insert into an object String one value.
You might use enum.name orenum.toString to get the name of the enum constant, or enum.ordinal to get the ordinal position.
you can use name() or toString(), so :
State aState = State.c;
String strState = aState.name();
See here the official java reference for more information...
State.b.toString() will return "b". The same goes for the other ones.
Usually,
State state = ...;
String string = state.toString();
should work, but it is not recommended since someone might override toString for some other purpose.
Instead the method you are looking for is
String string = state.name();
As an aside, your enumerated stated should always be all in capitals, and they should have descriptive names. It's not a language rule, but a convention. For example enum State { ON, OFF, PAUSED; }.
I tend to do something more complicated, but I find that it's more flexible:
public enum MyEnumeration {
SOME_NAME("Some Name"),
OTHER_THING("Other Thing"),
...
MORE_VALUES("More Values"),
private final String displayName;
private MyEnumeration(String displayName) {
this.displayName = displayName;
}
public String getDisplayName() {
return displayName;
}
}
This way, I use standard capitalization for my enums in code, but can have a more presentable name for them.
This trick can also be used to replace ordinal, by initializing a number, and then you don't need to worry about rearranging your enums.
Method #1: Using the built-in toString() and name() methods
If you want to print a String that is the same as the value of the State, then you can use the toString() method, or the name() method.
System.out.println(State.b); // Prints "b"
System.out.println(State.c); // Prints "c"
System.out.println(State.p); // Prints "p"
Method #2: Using a constructor to create a custom mapping
If you want to have a custom String associated with each of those states, you can use a constructor to associate a particular value with each enum value:
public enum State{
b("State B"), c("State C"), p("State P");
private String longName;
private State(String longName) {
this.longName = longName;
}
#Override
public String toString() {
return this.longName;
}
};
Of course, if you don't want to break the default toString() usage, you can create a different method called getFullName(), for example, to return the custom value.