Java Hibernate OpenSession in View Avoid fetch on Controller - java

we have a APP in Hibernate lately we start using Open Session in View in our DAO we fetch the data we really need.. we dont close the session but later in our controller in any operation on the Entity Hibernate is fetching the Data from the DB i know this behavior is the main reason to use open session but i dont need the fetch is some cases.. i was wondering if i can tell hibernate not fetch the data in some cases....
student.getSchool().getTeachers()
in this case i have load all the data i need from this 3 entitys but hibernate starts to load the school and the teachers again..
thanks a lot

Three main options:
If you use EH-Cache, you won't have to wait while Hibernate queries the database for Student & School again.
Or you could keep the form & Hibernate Session in the HTTP Session, which also achieves caching.
For AJAX or similar requests fetching just the Teachers, you could change the Criteria to Projection or use a Hibernate Query, to "project" or retrieve just the target entity.. at the database level, doing a joined or sub-expression query. Student would be loaded but only as a proxy, in this case.

Related

Spring #Transaction (readonly=true) context commit data to DB in the middle of the process

I am working on an assignment to make the code transactional. I am having this problem about read-only transaction for while and none of a single suggestion I found on the internet didn't work. (Spring and hibernate integrated project)
This is my read-only transactional method
#Transactional(propagation=Propagation.REQUIRES_NEW, readOnly=true
,rollbackFor=Exception.class)
public void
editInternationalExportConsigment(InternationalExportConsignmentFormWrapper
exportConssi (){}
Inside this method, there is a translator process happening. Where the process fetch (select ) data from DB and set to an Object
Contact contact =inquiry.loadCustomerContactById(consignmentVO.getCustomerContactId().intValue());
if (contact != null && contact.getCity() != null) {
consignment.setOrgin(contact.getCity().getCountry());
consignment.setUniqueOriginCountry((contact.getCity().getCountry()!=null)?contact.getCity().getCountry().getId():null);
consignment.setOrginCity(contact.getCity());
}
There are no any update or insert query run in the middle, Only select. But end of the this code snippet execution it commit the data to DB (whatever the value set to setter method will persist into DB )
Can someone please tell me what wrong is happening here. your feedback will be much appricated.
After tedious research, I have found the answer. In our project there are two session factories are running. And also it uses spring OpenSessionInViewFilter to avoid 'lazy initializing' issue. OpenSessionInViewFilter has set flushMode to Auto. Since the OpenSessionInViewFilter keeping binding a hibernate session to the thread along in the entire process, it will override the transactional hibernate session object which gets creates once I start the new transaction.Therefore even if I kept the flushmode for transactional scope as 'COMMIT' it get override with the AUTO property by the properties declared OpenSessionInViewFilter.
When the flushMode is AUTO hibernate will flush dirty objects to DB.
Read this for understand hibernate data flushin
As a solution, I manually change the flush mode to 'COMMIT' inside my transactional method.
Thank you for everyone replied and commented. :)

Write to multiple DB in single transaction in hibernate

I have a requirement where i need to write to multiple DB. If any exception occurs while writing to anyone of the DBs, i want to rollback everything.
E.G.
Session userSession= a.getUserDBSession();
Session departmentSession= a.getDepartmentSession();
Session carSession= a.getCarSession();
//Do some work and write to User DB
// Do some work and write to Department DB
//Do some work and write to Car DB
// commit everything.
Note: Session is Hibernate Session
Any help would be highly appreciated
You can try using the Atomikos with hibernate.
Check the below link.
http://www.atomikos.com/Documentation/HibernateThreeStandalone

similar load and get hibernate method on spring data

I´m reading about Hibernate and using Spring data. In one chapter I´ve read about the different of use get() and load(), supposedly in Hibernate load return a proxy placeHolder and only access to database in case that you access to the entity attribute.
In my application many times I just need to return and entity to add as dependency to another entity and for that specific case add a proxy would be more than enough, but using Spring data repository I cannot find the get() or load() method, so I guess they dont implement the same feature as in Hibernate. Any idea if Spring data has that Hibernate´s features to have a proxy placeHolder?.
Regards.
JpaRepository interface has two methods: First is getOne(id) which is an alternative of hibernate load, second is findById(id) which is an aternative of hibernate get method.

Why did app engine perform writer operation when I "read" HttpSession Attribute

the write operation on the httpsession is consuming my resources
I have a on UserSession attribute in the session which only store a userID and hash
write operation should only perform while login
but each time I use UserSession in my controller datastore_v3.Put was performed
what is happening???
I am using spring mvc in my project
I suspect that the session state is being saved because Spring MVC has no way of knowing if the state of the session-scoped objects has been changed during the request.
It's probably updating the timestamp of your session to keep it fresh on every access.
If you're really curious, you can get to the low-level session data using (I believe) the _AH_SESSION table (do a query on table Query.KIND_METADATA_KIND in empty ns for the full list of tables, including "hidden" tables).

Hibernate Sessions between HTTP requests

I'm developing a web application in which the model consists a Group which contains a List of many Users. A HTTP request comes to show the Group. The Users are loaded with FetchType.LAZY because I don't want them all right away. The Group is saved into the HTTP session and the Hibernate Session is closed. The application then responds by showing the Group name and description. A new HTTP request might then come in to show some users from the group. The Group is pulled from the HTTP Session and the application tries to access the list. Won't Hibernate throw an Exception since the proxies for each User were tied to the Hibernate Session that was previously closed? How do I do lazy loading across HTTP requests within HTTP sessions?
You should not put users nor groups (as objects) in the session. The best scenario is to put group id in the session and load the group and users if/when necessary.
Worried about the performance? Let the Hibernate 2nd level cache solve this problem. The cache should even support retrieving all users by group if you configure object mappings correctly, something like:
<class name="Group" table="...">
<cache .../>
<bag name=users" ...>
<cache ....>
...
</bag>
</class>
I don't think you need to or should store it in session. When you need the association you query it.
Update
Refrain from Eager loading, unless the collection size is small or managable. For example you have a Groups with small number of users in each group.
If you have reverse mapping, you could use group id to query the user list in subsequent calls.
Have you considered Open Session In View?
Open Session In View

Categories

Resources