Một giải pháp là sử dụng các thuộc tính không phải cột và đóng gói chúng bằng getters/setters.
Để nói JPA sử dụng getters/setters thay vì trực tiếp accesing lĩnh vực tư nhân, bạn phải chú thích @ id trên công dài getId() thay vì tin dài id. Khi thực hiện điều này, chỉ cần nhớ sử dụng @Transient cho mỗi trình thu thập dữ liệu không tương ứng trực tiếp với một cột.
Ví dụ sau sẽ tạo cột ngày có tên myDate, trong khi ứng dụng sẽ có phương thức getTime() và setTs() DateTime có sẵn cho nó. (không chắc chắn về API DateTime, vì vậy vui lòng tha thứ cho các lỗi nhỏ :))
import org.joda.time.DateTime;
@Entity
public class Foo {
private Long id;
private DateTime ts;
@Id
public Long getId() { return id; }
public void setId(Long id) { this.id = id; }
// These should be accessed only by JPA, not by your application;
// hence they are marked as protected
protected Date getMyDate() { return ts == null ? null : ts.toDate(); }
protected void setMyDate(Date myDate) {
ts = myDate == null ? null : new DateTime(myDate);
}
// These are to be used by your application, but not by JPA;
// hence the getter is transient (if it's not, JPA will
// try to create a column for it)
@Transient
public DateTime getTs() { return ts; }
public void setTs(DateTime ts) { this.ts = ts; }
}
Nguồn
2012-12-10 11:33:06
Không thể tin rằng chúng không xây dựng trong bộ điều hợp giống như trong JAXB: public class DateAdapter mở rộng XmlAdapter {... –