tailieunhanh - Java Persistence with Hibernate phần 6
Trong một ứng dụng Hibernate, bạn lưu trữ và tải các đối tượng bằng cách thay đổi bản chất nhà nước của mình. Bạn làm điều này trong đơn vị của công việc. Một đơn vị duy nhất của công việc là một tập hợp các hoạt động được coi là một nhóm nguyên tử. Nếu bạn đang đoán rằng đây là liên quan chặt chẽ đến các giao dịch, | 402 CHAPTER 9 Working with objects Storing and loading objects In a Hibernate application you store and load objects by essentially changing their state. You do this in units of work. A single unit of work is a set of operations considered an atomic group. If you re guessing now that this is closely related to transactions you re right. But it isn t necessarily the same thing. We have to approach this step by step for now consider a unit of work a particular sequence of state changes to your objects that you d group together. First you have to begin a unit of work. Beginning a unit of work At the beginning of a unit of work an application obtains an instance of Session from the application s SessionFactory Session session Transaction tx At this point a new persistence context is also initialized for you and it will manage all the objects you work with in that Session. The application may have multiple SessionFactorys if it accesses several databases. How the SessionFactory is created and how you get access to it in your application code depends on your deployment environment and configuration you should have the simple Hiber-nateUtil startup helper class ready if you followed the setup in Handling the SessionFactory in chapter 2 section . You should never create a new SessionFactory just to service a particular request. Creation of a SessionFactory is extremely expensive. On the other hand Session creation is extremely inexpensive. The Session doesn t even obtain a JDBC Connection until a connection is required. The second line in the previous code begins a Transaction on another Hibernate interface. All operations you execute inside a unit of work occur inside a transaction no matter if you read or write data. However the Hibernate API is optional and you may begin a transaction in any way you like we ll explore these options in the next chapter. If you use the Hibernate Transaction API your code works
đang nạp các trang xem trước