Some lombok annotations like @EqualsAndHashCode
and @ToString
have Exclude
option. But neither @Data
nor @AllArgsConstructor
has a similar option.
But @Data
generates setters for all fields for which a setter is not already defined. So you would define a setter as below for the required fields, which does nothing.
private void setId(Long id) {
// Do nothing
}
Instead of the @AllArgsConstructor
, you could either use @RequiredArgsConstructor
, but annotate all the fields to be in the constructor with @NonNull
(or the field should be final).
Refer this answer for RequiredArgsConstructor.
My suggested approach : Another way would be to use @Builder
annotation along with @AllArgsConstructor(access = AccessLevel.PRIVATE)
. (NOTE : Builder by default adds a private all argument constructor, but this is done only if there are no other constructors. But in your case, a default constructor exists and you need to explicitly mention the all args annotation.)
This would prevent the use of the constructor from outside, but at the same time allow you to create objects using the builder. At this point, you could set the values to id
and updateTime
using the builder. To prevent this you need to add the below code as well.
public static class MyEntityBuilder {
// access is restricted using
// these private dummy methods.
private MyEntityBuilder id(Long id) {
return this;
}
private MyEntityBuilder updateTime(LocalDateTime time) {
return this;
}
}
So, even though it is not possible to achieve your requirement directly, you could do so by adding two dummy setter methods and another two dummy methods within the builder class.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…