jeudi 2 septembre 2021

Displaying entity fields by names

I have large entity with many fields in database. I would like to form an excel document containing only chosen fields - chosen by user, i mean.

@Data
@Entity
@Table(name = "ATTRIBUTE")
public class attribute {

    @Column(name = "INN")
    private String inn;
    
    @Column(name = "OWNERSHIP")
    private String ownership;
    
    @Column(name = "NAME")
    private String name;
    
    //...
}
    @PostMapping("/create")
    public ResponseEntity<StreamingResponseBody> createDocument(@RequestBody List<String> attributes) {
    //...
    }

So, in attributes list can be any combination of field names - "name", "ownership", etc, so, if user chose the fields "name" and "ownership", then in resulting document should be only two these fields. Obvious path is to use reflection api, it's rather easy way, but very ugly IMO.

    public byte[] formDocument(Attribute attribute, List<String> fields) {
        try (Workbook book = new XSSFWorkbook(); 
             ByteArrayOutputStream outputStream = new ByteArrayOutputStream()) {
            Sheet sheet = book.createSheet();
            Row row = createRow();
            
            for (String field : fields) {
                createCell(row, attribute, field);
            }

            book.write(outputStream);
            return outputStream.toByteArray();
        } catch (IOException e) {
            throw new ExcelException();
        }
    }

//....

    public Object getFieldValue(Attribute attribute, String fieldName) throws IllegalAccessException {
        Optional<Field> requiredField = Arrays.stream(Attribute.class.getDeclaredFields())
                .filter(field -> field.getName().equals(fieldName))
                .findFirst();
        if (requiredField.isPresent()) {
            return requiredField.get().get(attribute);
        } else {
            throw new FieldNotFoundException();
        }
    }

Something like this. So, I would like to ask - are there cleaner, more beautiful ways to do it? I thought about some json mapping, but it doesn't seem better. Thank you.





Aucun commentaire:

Enregistrer un commentaire