0

给出来自Hibernate 文档的示例并对其进行修改,以便根级实体(客户)是只读的,而其集合(票证)之一是读写的:

@Entity
@Cache(usage = CacheConcurrencyStrategy.READ_ONLY)
public class Customer { 
    ... 
    @OneToMany(...)
    @Cache(usage = CacheConcurrencyStrategy.READ_WRITE)
    public SortedSet<Ticket> getTickets() {
        return tickets;
    }
    ...
}

从缓存访问客户时,票证集合会被刷新吗?

4

1 回答 1

1

如果您在其他地方修改tickets给定的其中一个,是的。Customer你为什么不测试这个?让我们假设Cutomer#1has Ticket#1andTicket#2在它的tickets集合中。我运行了这段代码:

// loading in first session
Session session1 = HibernateUtil.getSession();
Transaction tx1 = session1.beginTransaction();
Customer c1 = (Customer) session1.load(Customer.class, 1L); // loads from db and puts in cache
for (Ticket ticket : c1.getTickets()) { // caches q2742145.Customer.tickets#1
    System.out.println(ticket);
}
Ticket ticket = (Ticket) session1.load(Ticket.class, 1L); // doesn't hit the db
ticket.setName("foo"); // do some change on Ticket#1
session1.save(ticket);
tx1.commit(); // Ticket#1 gets updated in the db and the cached association invalidated

// loading in second session
Session session2 = HibernateUtil.getSession();
Transaction tx2 = session2.beginTransaction();
Customer c2 = (Customer) session2.load(Customer.class, 1L); // hits the cache
Set<Ticket> tickets = c2.getTickets();
for (Ticket ticket2 : tickets) { // reloads tickets from db
    System.out.println(ticket2); 
}
tx2.commit();

这表明票的集合得到“刷新”。

于 2010-04-30T07:29:25.763 回答