Hibernate에서 load () 대 get ()의 장점은 무엇입니까?
누구든지 Hibernate에서 load()
vs 의 장점이 무엇인지 말해 줄 수 있습니까 get()
?
Hibernate에서 load () 대 get ()의 장점은 무엇입니까?
프록시 는 최대 절전 모드가 데이터베이스에 도달하지 않고 메모리에 주어진 식별자 값으로 가짜 객체를 준비한다는 것을 의미합니다.
예 :
전화하면session.load(Student.class,new Integer(107));
hibernate는 ID가 107 인 메모리에 가짜 Student 객체 [row]를 생성하지만 Student 클래스의 나머지 속성은 초기화되지도 않습니다.
이 방법들의 의미론에 대한 설명은 그들 사이의 실질적인 차이점을 설명하지 않습니다. 실용적인 규칙은 다음과 같습니다.
get()
개체를로드하려는 경우 사용load()
예를 들어 다른 개체와의 관계를 생성하기 위해 추가 SQL 쿼리를 실행하지 않고 개체에 대한 참조를 가져와야 할 때 사용 합니다.public void savePost(long authorId, String text) { Post p = new Post(); p.setText(text); // No SELECT query here. // Existence of Author is ensured by foreign key constraint on Post. p.setAuthor(s.load(Author.class, authorId)); s.save(p); }
"Java Persistence with Hibernate"책, 페이지 405에서 :
get ()과 load ()의 한 가지 차이점은 인스턴스를 찾을 수 없음을 나타내는 방법입니다. 주어진 식별자 값을 가진 행 이 데이터베이스에 없으면 get ()은 null을 반환합니다 . 부하 () 메소드는 ObjectNotFoundException을 던진다 . 선호하는 오류 처리 방법은 사용자의 선택입니다.
More important, the load() method may return a proxy, a placeholder, without hitting the database. A consequence of this is that you may get an ObjectNotFoundException later, as soon as you try to access the returned placeholder and force its initialization (this is also called lazy loading; we discuss load optimization in later chapters.) The load() method always tries to return a proxy, and only returns an initialized object instance if it’s already managed by the current persistence context. In the example shown earlier, no database hit occurs at all! The get() method on the other hand never returns a proxy, it always hits the database.
You may ask why this option is useful—after all, you retrieve an object to access it. It’s common to obtain a persistent instance to assign it as a reference to another instance. For example, imagine that you need the item only for a single purpose: to set an association with a Comment: aComment.setForAuction(item). If this is all you plan to do with the item, a proxy will do fine; there is no need to hit the database. In other words, when the Comment is saved, you need the foreign key value of an item inserted into the COMMENT table. The proxy of an Item provides just that: an identifier value wrapped in a placeholder that looks like the real thing.
load will return a proxy object.
get will return a actual object, and returns null if it wont find any object.
A: This is explained in the hibernate reference. One difference was performance and the other one is that load throws an unrecoverable Exception when no Object is found for the ID.
More details here
- Use get() when you want to load an object
- Use load() when you need to obtain a reference to the object without issuing extra SQL queries, for example, to create a relationship with another object:
Ex: if you are trying to load /get Empoyee object where empid=20. But assume record is not available in DB.
Employee employee1 = session.load(Employee.class,20); //Step-1
system.out.println(employee1.getEmployeeId(); //Step-2 --o/p=20
system.out.println(employee1.getEmployeeName(); //Step-3 -->O/P:ObjectNotFoundException
If you use load in step-1 hibernate wont fire any select query to fetch employee record from DB at this moment.At this pint hibernate gives a dummy object ( Proxy ). This dummy object doesnt contain anything. it is new Employee(20). you can verify this in step-2 it will print 20. but in step-3 we are trying to find employee information. so at this time hibernate fires a sql query to fetch Empoyee objct. If it is not found in DB.throws ObjectNotFoundException.
Employee employee2 = session.get(Employee.class,20); //Step-4
for session.get() hibernate fires a sql query to fetch the data from db. so in our case id=20 not exists in DB. so it will return null.
The performance issues is also major difference between get and load method.
The get() method fetches data as soon as it’s executed while the load() method returns a proxy object and fetches only data when object properties is required. So that the load() method gets better performance because it support lazy loading. Whe should use the load() method only when we know data exists because it throws exception when data is not found. In case we want to make sure data exists we should use the get() method.
In short, you should understand the differential in between, and decide which method is best fix in your application.
I found this differences on the tutorial Difference between get and load method in Hibernate
When Load is called it returns a Proxy object. Actual select query is still not fired. When we use any of the mapped property for the first time the actual query is fired. If row does not exist in DB it will throw exception. e.g.
Software sw = ( Software )session.load(Software.class, 12);
Here sw is of proxy type. And select query is not yet called. in Eclipse debugger you may see it like
sw Software$$EnhancerByCGLIB$$baf24ae0 (id=17)
CGLIB$BOUND true
CGLIB$CALLBACK_0 CGLIBLazyInitializer (id=23)
CGLIB$CALLBACK_1 null
CGLIB$CONSTRUCTED true
id null
prop1 null
softwareprop null
when I use
sw.getProp1()
the select query is fired. And now proxy now knows values for all the mapped properties.
Where as when get is called, select query is fired immediately. The returned object is not proxy but of actual class. e.g.
Software sw = ( Software )session.get(Software.class, 12);
Here sw is of type Software itself. If row exists then all mapped properties are populated with the values in DB. If row does not exist then sw will be null.
sw Software (id=17)
id Integer (id=20)
prop1 "prodjlt1" (id=23)
softwareprop "softwrjlt1" (id=27)
So as always said, use load only if you are sure that record does exist in DB. In that case it is harmless to work with the proxy and will be helpful delaying DB query till the mapped property is actually needed.
session.load(): It will always return a proxy object with the given identity value, even the identity value is not exists in database. However, when you try to initialize a proxy by retrieve it’s properties from database, it will hit the database with select statement. If no row is found, a ObjectNotFoundException will throw.
session.get(): It will always return null , if the identity value is not found in database.
Get ()은 데이터베이스 또는 최대 절전 모드 캐시에서 객체를 가져 와서 반환하는 반면, load ()는 실제로 존재하지 않을 수있는 객체의 참조 만 반환하고, 객체의 다른 속성에 액세스 할 때만 데이터베이스 또는 캐시에서 데이터를로드합니다.
load ()를 사용하면 id를 인쇄 할 수 있지만 다른 필드에 액세스하려고하면 데이터베이스 쿼리를 실행하고 주어진 식별자를 가진 레코드가 없으면 org.hibernate.ObjectNotFoundException이 발생합니다. 최대 절전 모드 특정 런타임 예외이므로 명시 적으로 잡을 필요가 없습니다.
참조 URL : https://stackoverflow.com/questions/5370482/whats-the-advantage-of-load-vs-get-in-hibernate
'Development Tip' 카테고리의 다른 글
Google Geocoding API-REQUEST_DENIED (0) | 2021.01.09 |
---|---|
MySQL : 10 분 이상 지난 모든 행 삭제 (0) | 2021.01.09 |
Ruby에서 표준 편차를 어떻게 할 수 있습니까? (0) | 2021.01.09 |
jQuery를 사용하여 프로그래밍 방식으로 (0) | 2021.01.09 |
VIM에 대한 GoLang 구문 강조 표시 추가 (0) | 2021.01.09 |