Which Spring Entity Manager Factory should I use? - spring

There are two entity manager factory beans in Spring that would work for my application. The org.springframework.orm.jpa.LocalEntityManagerFactoryBean and org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean. I am using Spring 3.0 with EclipseLink JPA 2.2.
What I've read about these two are that they are the same. Except that LocalContainerEntityManagerFactoryBean uses weaving. What is it? And, why would I want to use it?

"Weaving" is a term for program transformation, usually heard around "aspect oriented programming" area. The transformation is usually not done to the source but the .class (the bytecode) and a techy term for changing bytecode is "bytecode instrumentation".
why would I want to use it?
The JPA implementation you use may rely on such bytecode instrumentation for some features it provides and hence you might be forced into using it.
And for weaving to work correctly, you might need to specify a -javaagent: For eg,see section 'Eclipse Junit' here.
It looks like LocalContainerEntityManagerFactoryBean allows you to configure a weaver implementation ( one of DefaultContextLoadTimeWeaver, GlassFishLoadTimeWeaver, InstrumentationLoadTimeWeaver, OC4JLoadTimeWeaver, ReflectiveLoadTimeWeaver, SimpleLoadTimeWeaver, WebLogicLoadTimeWeaver
at an XML file, instead of relying on a -javaagent runtime argument.
This configuration isn't such a big factor, I'd guess.
Other features which the docs explain, sound like deciding factors.
LocalEntityManagerFactoryBean bootstrap is appropriate for standalone applications which solely use JPA for data access. If you want to set up your persistence provider for an external DataSource and/or for global transactions which span multiple resources, you will need to either deploy it into a full Java EE 5 application server and access the deployed EntityManagerFactory via JNDI, or use Spring's LocalContainerEntityManagerFactoryBean with appropriate configuration for local setup according to JPA's container contract.

If you plan on deploying your application to an Application Server and letting the Application Server manage the Entity Manager Factory and Transactions than the LocalContainerEntityManagerFactoryBean might be a better option. If you rather have the Application be more isolated, than the LocalEntityManagerFactoryBean would be more appropriate.
This blog can help provide more insight: http://second-kind-demon.blogspot.com/2011/06/spring-jpa-java-ee-jboss-deployment.html

Related

Transitioning to Spring Data

We are currently using Spring 3.2.3 + JPA (Hibernate). We use aspects for transaction support as opposed to annotations. We write out own entity services (read: repositories) to abstract the persistence away from our application.
I've read a lot about Spring Data and feel it would make our code considerably cleaner and more robust. I wonder though, are there any gotchas that I should consider before transitioning?
Thanks
If you're already on JPA the transition should be as easy as it can be: activate the repositories, point the infrastructure to your EntityManagerFactoryBean and off you go.
Transactions should just work fine as well. The annotation based usage within Spring Data is selectively activated for the repository beans only. They are configured to take part in existing transactions by default, so any custom larger scoped transaction setting should be in effect already.

Benefits to using Spring templates

What are the enumerated benefits to using the Spring template classes such as RestTemplate, JdbcTemplate, JpaTemplate, JdoTemplate, JndiTemplate JdoTemplate etc?
I'm looking for the general benefits of using these classes as best practice design, for example the thread safeness of these classes. Or if someone could point me to the section of the Spring documentation that discusses the same I would accept that as well.
Less boilerplate code
More cohesive exceptions handling (e.g. JDBC drivers checked exceptions are translated to meaningful runtime exceptions)
Easier and uniform configuration (almost everything can be configured in Spring context files)
Automatized resource management (like, for instance, closing DB connections)
Note, that not all templates are equally useful. For instance jdbcTemplate is a pure gem, I can't live without that (mostly because JDBC is not the best interface one can imagine), on the other hand jpaTemplate does not bring so many advantages.
Note, that if you use given template, your code becomes dependent on Spring interfaces, so Spring is not only dependency mechanism for your application, but becomes also part of it - Spring is no longer easily replacable with something else (Google Guice, CDI). However, given the fact Spring is a pretty good peace of code, I would not be worried about that aspect.

Is it possible to integrate OSGi with Spring Data?

I'm currently working on an OSGi application running under apache Karaf that uses JPA and QueryDSL.
I was wondering if I could use Spring Data with QueryDSL instead of the current approach.
The reason for this is that I find Spring repositories to be quite useful and having a template for NoSQL database accesses might be useful in the future.
I have tried to start a normal spring application without a web context with OSGi but I get a ClassNoutFoundException when it tries to load the applicationContext.xml or the ApplicationContext.class.
I don't want to use Spring DM since it is discontinued.
Basically the sole reason for wanting to try this integration is for the Spring Repositories, but if you think this is not necessary please tell me. Any information regarding how to achive this or if it's ok to persue this would be more than welcome.
Thank you
Update
I've managed to make spring work by starting the application context with org.eclipse.gemini.blueprint.context.support.OsgiBundleXmlApplicationContext. The applicationContext is exported in OSGi as a service and I can get all the beans that I need by calling it.
The problem I'm having right now is that when I declare <jpa:repositories base-package="x.y.z" /> I get the following exception:
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor#0' defined in URL [bundle://251.13:0/META-INF/spring/applicationContext.xml]: Initialization of bean failed; nested exception is java.lang.IllegalStateException: No persistence exception translators found in bean factory. Cannot perform exception translation.
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:527)[185:org.springframework.beans:3.1.4.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:456)[185:org.springframework.beans:3.1.4.RELEASE]
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:294)[185:org.springframework.beans:3.1.4.RELEASE]
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:225)[185:org.springframework.beans:3.1.4.RELEASE]
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:291)[185:org.springframework.beans:3.1.4.RELEASE]
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:197)[185:org.springframework.beans:3.1.4.RELEASE]
at org.springframework.context.support.AbstractApplicationContext.getBean(AbstractApplicationContext.java:1109)[187:org.springframework.context:3.1.4.RELEASE]
at org.eclipse.gemini.blueprint.context.support.AbstractDelegatedExecutionApplicationContext.registerBeanPostProcessors(AbstractDelegatedExecutionApplicationContext.java:502)[193:org.eclipse.gemini.blueprint.core:1.0.0.RELEASE]
at org.eclipse.gemini.blueprint.context.support.AbstractDelegatedExecutionApplicationContext.registerBeanPostProcessors(AbstractDelegatedExecutionApplicationContext.java:451)[193:org.eclipse.gemini.blueprint.core:1.0.0.RELEASE]
at org.eclipse.gemini.blueprint.context.support.AbstractDelegatedExecutionApplicationContext$4.run(AbstractDelegatedExecutionApplicationContext.java:306)[193:org.eclipse.gemini.blueprint.core:1.0.0.RELEASE]
at org.eclipse.gemini.blueprint.util.internal.PrivilegedUtils.executeWithCustomTCCL(PrivilegedUtils.java:85)[193:org.eclipse.gemini.blueprint.core:1.0.0.RELEASE]
at org.eclipse.gemini.blueprint.context.support.AbstractDelegatedExecutionApplicationContext.completeRefresh(AbstractDelegatedExecutionApplicationContext.java:290)[193:org.eclipse.gemini.blueprint.core:1.0.0.RELEASE]
at org.eclipse.gemini.blueprint.extender.internal.dependencies.startup.DependencyWaiterApplicationContextExecutor$CompleteRefreshTask.run(DependencyWaiterApplicationContextExecutor.java:137)[194:org.eclipse.gemini.blueprint.extender:1.0.0.RELEASE]
at java.lang.Thread.run(Thread.java:662)[:1.6.0_37]
Caused by: java.lang.IllegalStateException: No persistence exception translators found in bean factory. Cannot perform exception translation.
at org.springframework.dao.support.PersistenceExceptionTranslationInterceptor.detectPersistenceExceptionTranslators(PersistenceExceptionTranslationInterceptor.java:142)[195:org.springframework.transaction:3.1.4.RELEASE]
at org.springframework.dao.support.PersistenceExceptionTranslationInterceptor.<init>(PersistenceExceptionTranslationInterceptor.java:79)[195:org.springframework.transaction:3.1.4.RELEASE]
at org.springframework.dao.annotation.PersistenceExceptionTranslationAdvisor.<init>(PersistenceExceptionTranslationAdvisor.java:70)[195:org.springframework.transaction:3.1.4.RELEASE]
at org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor.setBeanFactory(PersistenceExceptionTranslationPostProcessor.java:103)[195:org.springframework.transaction:3.1.4.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeAwareMethods(AbstractAutowireCapableBeanFactory.java:1475)[185:org.springframework.beans:3.1.4.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1443)[185:org.springframework.beans:3.1.4.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:519)[185:org.springframework.beans:3.1.4.RELEASE]
As a JPA provider I'm using OpenJPA. The entityManagerFactory is a service which I can get by using the blueprint. I think I need to reference it in <jpa:repositories base-package="x.y.z" />, but how do I do that since the applicationContext.xml is read by spring and not the blueprint?
I would really appreciate any hint in the right direction.
Thank you
Use Querydsl-SQL directly in your code and
it will work well within OSGi as it does not use class loading, weaving, enhancing, caching and other tricks that sound really good but causes chaos
your code will run much faster than with any of the "cache-enhanced" JPA engines
others will be able to understand your code (not like JPA Criteria API queries)
you will know exactly what SQL commands run on the Database Server that minimizes problem-solving time
your code will be as database independent as with any ORM tool
Do not use Spring, spring-data, JPA and other monoholitic technologies together with OSGi as
they were designed to work within monoholitic systems where everything is in one application context, not in separate bundles
by using these technologies together with OSGi you will spend most of your time to fix bugs like this and looking for workarounds
People who argue with this, already spent lots of time on finding such workarounds. They managed to implement some business logic. They hope that they now truly found workarounds for every conceptual issue and they do not have to spend the same amount of work next time. They are in a bidding fee auction. Be honest guys! Somewhere deep you know I am right ;-).
I am saying this with the experience that I
tried the perfect stack based on Hibernate and Don't repeat the DAO article of IBM (much before Spring-Data hype began). Twice
wrote hibernate-osgi-adapter for Hibernate 4.1.x
Re-implemented the complete JPA chapter of OSGi Enterprise specification
Well you have a couple of choices here, try to get it to run with blueprint (probably the hardest - since you need to call spring beans, but I think could still be done), use Karaf 3.0.0.RC1 it also supports Blueprint Geminin which does have a tighter support for Spring and last but not least use Spring-DM, even if it is discontinued you are able to use and probable the best approach is to use spring-dm for certain Spring specific parts and std. Blueprint for the rest. Because you just use services through both frameworks everything will work, just don't mix the spring and blueprint descriptors in one bundle.

Spring Data JPA like project not dependent on Spring

Does anyone know any Java frameworks that follows the repository approach with automatic implementation of query methods (e.g. findByNameAndLastName(…)) but not tied to Spring, only pure JPA. Such feature also exists in GORM. I would like to see if there is any project that can be used in Guice or pure JavaEE environment without bringing Spring as a dependency.
(Disclaimer: I am the author of Spring Data JPA)
There is the CDI Query Module which is very similar to what Spring Data JPA. There's also a DeltaSpike module.
Note that Spring Data JPA ships with a CDI extension that creates repository proxies as plain CDI beans and does not bootstrap a Spring container. There are APIs that allow the creationg of repository proxies programmatically such as:
EntityManager em = // … obtain EntityManager
JpaRepositoryFactory factory = new JpaRepositoryFactory(em);
UserRepository repository = factory.getRepository(UserRepository.class);
Yes, it still requires Spring libraries to be present on the classpath but it is then using them similar to how you would use Commons Collection or the like. We try not to reinvent the wheel and the Spring libraries we depend on provide a lot of useful code that we do not have to re-code.
So if it's Spring as DI container you're worrying about, feel free to give the CDI extension of Spring Data JPA a choice. If you don't want to use any Spring whatsoever (for whatever reason), have a look at the alternatives.
Based on Oliver's information, followed up as also interested in this topic --
CDI Query joining Deltaspike mail thread: http://apache-deltaspike-incubator-discussions.2316169.n4.nabble.com/Porting-the-CDI-Query-extension-project-to-DeltaSpike-td4329922.html
Deltaspike base link: http://deltaspike.apache.org/index.html
Getting started: http://deltaspike.apache.org/documentation.html
Just did their 0.4th release as of 5/31/2013.
However, have not done enough of a review to contrast/compare Deltaspike versus Spring-Data w/ CDI extensions (spring-data being very mature).
Take a look at Tomato on github!
It is a functional replacement for Spring JPA, has zero dependencies, performs better and is far easier to use. It will reduce your data access code by 98% and deliver the results you want right out of the box.
https://rpbarbati.github.io/Tomato.
If you want free, fully functional dynamic forms and/or tables for any Tomato entity or hierarchy, that can also be customized easily, try the angular based companion project...
https://rpbarbati.github.io/Basil
Both are current, maintained projects.
Try it yourself, or contact the author at rodney.barbati#gmail.com with questions.

Is it bad practice for a spring-based jar project to provide a bean configuration file?

If you have a library containing Spring beans that need to be wired together before an application can use them, does it make sense to include any sort of bean configuration file in the JAR (such as the /META-INF directory)? The idea is to give the application the option of importing this into its master Spring context configuration.
There may be more than one way to wire these beans, so I could provide a bean configuration file for each of the standard ways in which you'd typically wire them together.
Or, do I force the application to wire these up explicitly?
If it helps, the specifics of my problem involve a library I created to encapsulate our product's persistence layer. It contains Service, DAO and model beans. The DAO implementations currently use Hibernate (this probably won't change). Some of the DAO implementations need different kinds of Strategy beans injected into them (database encryption logic), depending on the type of database we are deploying on (MySQL vs SQL Server, etc). So we have potentially a few different configuration scenarios. I could also provide datasource bean configurations, relying on property substitution at the app level to inject all the particulars needed by the datasource.
Thanks for your input!
In this case, it's a good idea to provide some beans files, either as examples for documentation purposes, or as fully-fledged files ready for including into a wider context.
If your beans' wiring can get complex, then you shouldn't really leave it entirely up to the library client to figure it out.
This is more of a documentation and education task, really.

Resources