Lets say this is my class. And I want getters and setters for all fields except the Date. Is the a way to exclude?
@Data
public class User {
String first;
String last;
String email;
Date dob;
Boolean active;
}
I think this is the only way to hide:
@Getter(value=AccessLevel.PRIVATE)
@Setter(value=AccessLevel.PRIVATE)
private Date dob;
or maybe better with AccessLevel.NONE
like Ken Chan's answer suggests
so overriding the access level. However this does not hide it from constructors.
Also you can make tricks with inheritance. Define class like:
public class Base {
// @Getter if you want
private Date dob;
}
and let your User
to extend that:
@Data
public class User extends Base {
private String first;
private String last;
private String email;
private Boolean active;
}
Well , or better yet use AccessLevel.NONE
to completely make it does not generate getter or setter. No private getter or setter will be generated.
@Getter(value=AccessLevel.NONE)
@Setter(value=AccessLevel.NONE)
private Date dob;
You can do this by using the following annotations:
@Getter(value=AccessLevel.NONE)
@Setter(value=AccessLevel.NONE)
private LocalDate dob;
It is also better to use a LocalDate instead of Date. Date is a deprecated API.
@pirho, your example still creates the getter and setter but makes them private.
I'm not sure it's best practice, but what I did when I had to exclude @ManyToMany
fields from @EqualsAndHashCode
(to prevent stackoverflow) is this
@Entity
@Table(name = "users")
@Data
@EqualsAndHashCode
public class User implements UserDetails {
// ...
@ManyToMany
@JoinTable(name = "user_role",
joinColumns = {@JoinColumn(name = "user_id", referencedColumnName = "id"),
@JoinColumn(name = "username", referencedColumnName = "username")},
inverseJoinColumns = {@JoinColumn(name = "role_id", referencedColumnName = "id"),
@JoinColumn(name = "role", referencedColumnName = "role")})
@EqualsAndHashCode.Exclude
private Set<Role> authorities;
In other words, I explicitly added an @EqualsAndHashCode
so that I could put an @EqualsAndHashCode.Exclude
annotation at the @ManyToMany
field. You can do a similar thing with your getters ans setters. It works