Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[FEATURE] Augment @FieldNameConstants with asArray property #3319

Open
ribomation opened this issue Dec 30, 2022 · 1 comment
Open

[FEATURE] Augment @FieldNameConstants with asArray property #3319

ribomation opened this issue Dec 30, 2022 · 1 comment

Comments

@ribomation
Copy link

Providing an array of the field names of a domain class is very common in Spring projects, such as Spring Batch when configuring reading or writing of flat-files (CSV, FWV). Using the Lombok @FieldNameConstants(asEnum=true) annotation makes it easier. However, the last step is still somewhat clumsy:
@FieldNameConstants(asEnum=true) class MyDomainClass {...}
var names = Stream.of(MyDomainClass.Fields.values()).map(Enum::name).toArray(String[]::new);

So, my suggestion is to add the annotation property asArray, which would generate a static final String[] with the names.

With Lombok

@FieldNameConstants(asArray=true)
@OtherLombokAnnotations
class Account {
    private String accno;
    private long balance;
}

With Java

class Account {
    private String accno;
    private long balance;
    public static final String[] Fields = {"accno", "balance"};
    //. . .
}

As an example, with the suggested property it would be a breeze to configure an CSV ItemWriter in Spring Batch:

@Bean
public FlatFileItemWriter<Account> itemWriter(Resource file) throws Exception {
	return new FlatFileItemWriterBuilder<Account>()
				.name("Account")
				.resource(file)
				.delimited()
				.names(Account.Fields)    // <----here
				.build();
}
@ribomation
Copy link
Author

Another example of usage from Spring, is generation of SQL for a NamedParameterJdbcTemplate object:

var sql = String.format("insert into %s (%s) values (%s)", 
    Account.class.getSimpleName() + "s",
    Stream.of(Account.Fields).collect(Collectors.joining(",")),
    Stream.of(Account.Fields).map(f -> ":"+f).collect(Collectors.joining(","))
)

Which would produce this SQL:

insert into accounts (accno,balance) values (:accno,:balance)

And could be used in the following snippet:

var jdbc = new NamedParameterJdbcTemplate(dataSource);
var data = new BeanPropertySqlParameterSource(anAccountObj);
jdbc.update(sql, data);

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant