简体   繁体   中英

Open Session in View with Pure JPA and Spring - not Hibernate Session

I'm creating a Java EE application that's using JPA for data access. Initially I used EclipseLink, but the bundled Geronimo Javamail implementation that it depends on via Moxy was giving me some odd issues and I couldn't force it to use Sun Javamail, so I've switched to Hiberate as the JPA provider.

EclipseLink was ignoring the lazy/eager annotations, it was eagerly loading everything. Hibernate pays attention to those annotations, and so dependant objects aren't loaded. That means if I load say a person, with a lazy loading of the persons parents, if I access the parents in the view it's not lazy loaded, I get an exception that says the database session's closed.

I understand there are two ways to get around this: - Open Session in View pattern/antipattern (which isn't great from a layered point of view, and can have the N+1 database calls problem, but is easy) - Have service methods that load all the data the view needs (which makes the service layer messy with lots of duplicate methods to get varying amounts of data)

For reference my layers are View -> Controller -> Service -> Entity Object -> JPA. I don't have a dto as it's a small app and I don't like the DTO anti-pattern.

Thinking about the Open Session in View pattern, the problem is the OpenSessionInViewInterceptor and OpenSessionInViewFilter are both Hibernate specific, and both require you to declare a hiberate session on your Spring configuration files. I prefer to stay with pure JPA, configured with a persistence.xml file.

What are my options here? Can I just change my Spring configuration to load Hibernate explicitly, but then use pure JPA inside my application? Is there a pure JPA way achieve the same result, lazy loading from the view?

  • it sounds odd the EclipseLink ignores standard JPA annotations.
  • the javamail implementation should not be in any way related to JPA
  • there is OpenEntityManagerInViewX (filter/interceptor) which handle the same scenario for JPA
  • you can easily go without this pattern if you declare and use your collections wisely.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM