Answer the question
In order to leave comments, you need to log in
Is it possible to add a private method to an entity?
Is it possible to add a private method to the entity that calculates the value for the field? In this case, the calculateExpirationDate method, which is called from the constructor:
@Entity
@Table(name = "registration_tokens")
public class RegistrationToken {
private static final int TTL_MINUTES = 60 * 24; //24 часа
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private long id;
@Column(name = "token")
private String token;
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "user_id", nullable = false)
private User user;
@Column(name = "expiration_date")
private Date expirationDate;
public RegistrationToken() {
}
public RegistrationToken(User user) {
this.token = UUID.randomUUID().toString();
this.user = user;
this.expirationDate = calculateExpirationDate();
}
public RegistrationToken(String token) {
this.token = token;
}
public boolean isExpired() {
return this.expirationDate.before(new Date());
}
public boolean isNotExpired() {
return this.expirationDate.after(new Date());
}
private Date calculateExpirationDate() {
Calendar calendar = Calendar.getInstance();
calendar.setTime(new Date());
calendar.add(Calendar.MINUTE, TTL_MINUTES);
return new Date(calendar.getTime().getTime());
}
public void setToken(String token) {
this.token = token;
}
public String getToken() {
return token;
}
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getTokenString() {
return token.toString();
}
public User getUser() {
return user;
}
public void setUser(User user) {
this.user = user;
}
public Date getExpirationDate() {
return expirationDate;
}
public void setExpirationDate(Date expirationDate) {
this.expirationDate = expirationDate;
}
}
Answer the question
In order to leave comments, you need to log in
Or is it more correct to set expiretionDate through setExpirationDate
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question