2015-03-23 8 views

Odpowiedz

2

To proste. Powiedzmy, że masz następujący model domeny:

@Entity(name = "Post") 
public class Post { 

    @Id 
    @GeneratedValue(strategy = GenerationType.AUTO) 
    private Long id; 

    private String name; 

    @OneToMany(cascade = CascadeType.ALL, mappedBy = "post") 
    private List<Comment> comments = new ArrayList<>(); 

    public String getName() { 
     return name; 
    } 

    public void setName(String name) { 
     this.name = name; 
    } 

    public List<Comment> getComments() { 
     return comments; 
    } 

    public void addComment(Comment comment) { 
     comments.add(comment); 
     comment.setPost(this); 
    } 
} 

@Entity(name = "Comment") 
public class Comment { 

    @Id 
    @GeneratedValue(strategy = GenerationType.AUTO) 
    private Long id; 

    @ManyToOne 
    private Post post; 

    public Comment() { 
    } 

    public Comment(String review) { 
     this.review = review; 
    } 

    private String review; 

    public Long getId() { 
     return id; 
    } 

    public Post getPost() { 
     return post; 
    } 

    public void setPost(Post post) { 
     this.post = post; 
    } 

    public void setReview(String review) { 
     this.review = review; 
    } 
} 

Jeżeli uruchomić następujące HQL zapytanie:

List<Comment> comments = session.createQuery(
    "select c from Comment c ").list(); 
for(Comment comment : comments) { 
    Post post = comment.getPost(); 
} 

Następnie dla każdego komentarza będziesz musiał uruchomić dodatkowy zapytanie do pobierania skojarzony komentarz .

Jeśli włączysz 2. poziom buforowanie:

@Entity(name = "Post") 
@Cacheable 
@org.hibernate.annotations.Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE) 
public class Post { 
    ... 
} 

Następnie hibernacji pierwszy idzie do poziomu Cache 2. załadować podmiot i dopiero trafia do bazy danych, jeśli nie ma wejścia cache znaleźć.

Prostszym rozwiązaniem jest po prostu fetch all required data at query-time:

List<Comment> comments = session.createQuery(
    "select c from Comment c fetch c.post ").list(); 

W ten sposób nie będzie działać w sprawach N + 1 zapytań, a nie trzeba będzie cache 2. poziom albo. Like any caching solution, pamięć podręczna drugiego poziomu jest podatna na niespójności, gdy baza danych jest aktualizowana poza interfejsem API Hibernate.

Powiązane problemy