As I explained in this article, JPA and Hibernate map each entity attribute to a database column. But you can use a small workaround to achieve the requested mapping.
You first need 2 entity attributes that map the 2 database columns. If you use field-based access (you annotate the attributes and not the setters), you can skip the getter and setter methods for these attributes. You can then add a 3rd attribute, which is the one you will use in your business code. You need to annotate it with @Transient
and calculate its value based on the other 2 attributes.
Here's a mapping that uses this approach to map a time (postedAtTime) and a date (postedAtDate) column to the LocalDateTime postedAt
attribute.
@Entity
public class Review {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
private String comment;
private LocalDate postedAtDate;
private LocalTime postedAtTime;
@Transient
private LocalDateTime postedAt;
public Long getId() {
return id;
}
public String getComment() {
return comment;
}
public void setComment(String comment) {
this.comment = comment;
}
public LocalDateTime getPostedAt() {
if (postedAt == null) {
this.postedAt = LocalDateTime.of(this.postedAtDate, this.postedAtTime);
}
return postedAt;
}
public void setPostedAt(LocalDateTime postedAt) {
this.postedAt = postedAt;
this.postedAtDate = postedAt.toLocalDate();
this.postedAtTime = postedAt.toLocalTime();
}
}
Please be aware, that you need to use the postedAtDate
and postedAtTime
attributes in your JPQL And Criteria queries. But as long as you work with the Review
entity object, you don't need to know about these 2 internal attributes.