Mã dưới đây là những gì Spring Roo tạo theo mặc định, EntityManager được đưa vào mô hình miền của bạn POJO với phần còn lại của các phương pháp để quản lý thực thể (lưu, cập nhật, xóa, tìmXXX, ...).Spring Roo: sử dụng thực thể JPA dưới dạng DAO
Có lẽ đó là một cách tiếp cận hướng đối tượng hơn (trái ngược với anemic domain model), nhưng những gì tôi không hiểu là:
Có hiệu suất vấn đề khi EntityManager được tiêm trong mỗi thực thể (hãy tưởng tượng bạn truy xuất 1000 thực thể từ cơ sở dữ liệu)
Không nên quản lý giao dịch (@Transactional annotations) đi vào một lớp dịch vụ? (hãy tưởng tượng bạn muốn hoạt động với hai thực thể khác nhau theo cách nguyên tử).
Bạn có thể nghĩ về các ưu điểm/khuyết điểm khác của mã này so với lớp DAO cổ điển không?
Mã này trông như thế này (một số phương pháp được loại bỏ cho rõ ràng):
@Configurable
@Entity
@RooJavaBean
@RooToString
@RooEntity
public class Answer {
@PersistenceContext
transient EntityManager entityManager;
@Transactional
public void persist() {
if (this.entityManager == null) this.entityManager = entityManager();
this.entityManager.persist(this);
}
@Transactional
public void remove() {
if (this.entityManager == null) this.entityManager = entityManager();
if (this.entityManager.contains(this)) {
this.entityManager.remove(this);
} else {
Answer attached = Answer.findAnswer(this.id);
this.entityManager.remove(attached);
}
}
@Transactional
public Answer merge() {
if (this.entityManager == null) this.entityManager = entityManager();
Answer merged = this.entityManager.merge(this);
this.entityManager.flush();
return merged;
}
public static final EntityManager entityManager() {
EntityManager em = new Answer().entityManager;
if (em == null) throw new IllegalStateException("Entity manager has not been injected (is the Spring Aspects JAR configured as an AJC/AJDT aspects library?)");
return em;
}
public static long countAnswers() {
return entityManager().createQuery("SELECT COUNT(o) FROM Answer o", Long.class).getSingleResult();
}
public static List<Answer> findAllAnswers() {
return entityManager().createQuery("SELECT o FROM Answer o", Answer.class).getResultList();
}
...
}
Cảm ơn bạn đã liên kết tuyệt vời. Câu hỏi duy nhất nó không thực sự trả lời là câu hỏi đầu tiên. Không rõ ràng khi nào và cách EntityManager được tiêm vào mỗi thực thể. –
@ GuidoGarcía, bạn có câu trả lời ngay bây giờ không? – eric2323223
@ eric2323223 chưa –