Đang chuẩn bị nút TẢI XUỐNG, xin hãy chờ
Tải xuống
Đầu tiên, bạn lấy các đối tượng từ cơ sở dữ liệu với các định danh được. Bạn chỉnh sửa các đối tượng, và những thay đổi này là tuyên truyền cơ sở dữ liệu trong tuôn ra khi tx.commit () được gọi là. Cơ chế này được gọi là tự động bẩn kiểm tra điều đó có nghĩa là Hibernate Tất cả các chiến lược lấy trước đó là hữu ích nếu bạn cố gắng | 406 CHAPTER 9 Working with objects Session Persistence Context 1 2. 1 1 A get id 1 K Y 1 1. 3. f 4. 1 5. 1 openSessionQ setValue v flush close Figure 9.6 Modifying a persistent instance First you retrieve the object from the database with the given identifier. You modify the object and these modifications are propagated to the database during flush when tx.commit is called. This mechanism is called automatic dirty checking that means Hibernate tracks and saves the changes you make to an object in persistent state. As soon as you close the Session the instance is considered detached. Making a persistent object transient You can easily make a persistent object transient removing its persistent state from the database with the delete method see listing 9.5 . Listing 9.5 Making a persistent object transient using delete Session session sessionFactory.openSession Transaction tx session.beginTransaction Item item Item session.load Item.class new Long 1234 session.delete item tx.commit session.close Look at figure 9.7. The item object is in removed state after you call delete you shouldn t continue working with it and in most cases you should make sure any reference to it Session Persistence Context 1 2. f- -4- load id - p 1 K 3. Y delete o - I J R -I L I . - T I 1 1. I 4. I 5. openSessionO flushO close Figure 9.7 Making a persistent object transient The Hibernate interfaces 407 in your application is removed. The SQL DELETE is executed only when the Session s persistence context is synchronized with the database at the end of the unit of work. After the Session is closed the item object is considered an ordinary transient instance. The transient instance is destroyed by the garbage collector if it s no longer referenced by any other object. Both the in-memory object instance and the persistent database row will have been removed. FAQ Do I have to load an object to delete it Yes an object has to be loaded into the persistence context an instance has to be in persistent .