Issue
I want to check whether my entity contains a primary key or a composite key. If the entity contains a primary key then make isPrimaryKey
true and enter the value of the primary key in the key string else false and vice versa.
This is a sample JSON that I want to return:
{
"data": {
"identifier": {
"primaryKeys": {
"isPrimary": false,
"keys": ""
},
"compositeKeys": {
"isComposite": true,
"keys": "compositeKey"
}
},
"rows": [],
"columns": [
{
"createTimeStamp": "2020-09-30T19:00:00.000-05:00",
"createUserId": "SHOKUMA",
"lastUpdateTimeStamp": "2020-09-30T19:00:00.000-05:00",
"lastUpdateUserId": "SHOKUMA",
"key": {
"xyz": "DLRHOLD",
"abc": "010",
"cde": "LSE",
"date": "2020-01-01"
},
"dteExpn": "01/01/2025",
"indActive": "Y"
}
]
}
}
I have created some pojo for the same:
public class PrimaryKeys{
public boolean isPrimary;
public String keys;
}
public class CompositeKeys{
public boolean isComposite;
public String keys;
}
public class Identifier{
public PrimaryKeys primaryKeys;
public CompositeKeys compositeKeys;
}
public class Key{
public String xyz;
public String abc;
public String cde;
public String date;
}
public class Column{
public Date createTimeStamp;
public String createUserId;
public Date lastUpdateTimeStamp;
public String lastUpdateUserId;
public Key key;
public String dteExpn;
public String indActive;
}
public class Data{
public Identifier identifier;
public List<Object> rows;
public List<Column> columns;
}
public class Root{
public Data data;
}
Solution
public boolean hasPrimary() {
return Arrays.stream(this.getClass().getDeclaredFields())
.anyMatch(field -> field.isAnnotationPresent(Id.class));
}
public boolean hasComposite() {
return Arrays.stream(this.getClass().getDeclaredFields())
.anyMatch(field -> field.isAnnotationPresent(EmbeddedId.class));
}
@JsonIgnore
public String getKey() {
return hasPrimary()
? Arrays.stream(this.getClass().getDeclaredFields())
.filter(field -> field.isAnnotationPresent(Id.class)).findFirst().get().getName()
: Arrays.stream(this.getClass().getDeclaredFields())
.filter(field -> field.isAnnotationPresent(EmbeddedId.class)).findFirst().get().getName();
}
Answered By - Bhumika