best approach for setting hibernate/spring project - spring

I have a project with spring and hibernate in GWT,
I am using below applicationcontext.xml,
I was just looking for some best approach of making this file
like all the annotated classes below i.e entity.user, entity.secretQuestion and many more , they all get called when my application runs even if i don't need them , which i guess makes my application quite slow,
so is it possible that only the class which i am calling is getting load in applicationcontext.xml and if yes then would it be a better approach as well ?
<bean id="sessionFactory"
class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="annotatedClasses">
<list>
<value>com.cricsite.persistence.entity.User</value>
<value>com.cricsite.persistence.entity.SecretQuestion</value>
</list>
</property>
</bean>
<bean id ="ManagerAdmin" class= "com.persistence.MySQLRdbHelper">
<property name="sessionFactory" ref="sessionFactory" />
</bean>

You might be looking for something called "lazy loading"
Please take a look at these threads;
Help needed with Spring/Hibernate Lazy-loading
What is lazy loading in Hibernate?
how does spring allow for lazy-loading?

Related

hibernate annotatedClasses in external file

I'm using spring + hibernate in my application.
I need to map the entities that are annoted by hibernate annotations.
I have this configuartion.
<bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="annotatedClasses">
<list>
<value>com.example.repositoryComment.Model1</value>
<value>com.example.repositoryControlUpload.Model2</value>
<value>com.example.repositoryCycleTicketSummary.Model3</value>
</list>
</property>
I'd like that the entities configuration stay in another file.
Exemplo:
<bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="annotatedClasses">
<list>
filesThatContainsModels
</list>
</property>
This classes (Model1, Model2, Model3) are annoted by hibernate.
I don't use packagesToScan, because my warmup need to be fast.
There is way for configuration only the class that annoted, but not using packagesToScan?
Thanks
One option at build-time would be to take advantage of annotation processing.
Basically a custom annotation processor will scan your source files at build time and generate a list of all files found to be annotated with #Entity. It takes this list of classes along with an external property file that describes your static SessionFactory configuration and it generates your spring XML file as applicationContext-persistence.xml.
You then just make sure your main applicationContext.xml imports that file for runtime.
Another alternative would actually to use the packagesToScan property. But rather than do what a lot of developers do and point it to the root package of your application, provide the property with a more restrictive list of packages that represent exactly where it should look, helping it avoid inspecting unnecessary classes. For example:
<property name="packagesToScan">
<array>
<value>com.company.application.feature1.persistence</value>
<value>com.company.application.feature2.persistence</value>
...
</array>
</property>
But I honestly think you're over optimizing. If you have this type of bootstrap performance issues, there has to be something else going wrong here to give you cause for concern.
I have worked on a monolithic application with tens of thousands of class files where the scan pointed to the package root of the application and it didn't take any more than a few seconds to bootstrap the Hibernate persistence classes.

spring-batch : load and use a property file

I am new on Spring batch so am here to ask some basic advice.
What is the best approach to load a config file in memory (or bean) and use its content while the spring Job/step are running ?
I am not sure but based on some google search I found the below scenario even if I dont quite understand why I should define a writer even if i dont need it :
step1 : load config file (the content is two field delimited by =)
step2 : perform some java code and use the previous config file
so for the step 1 :
<bean id="inputFile" class="org.springframework.core.io.FileSystemResource" scope="step">
<constructor-arg value="path_config_file"/>
</bean>
<bean id="readerConfigFile" class="org.springframework.batch.item.file.FlatFileItemReader" scope="step">
<property name="resource" ref="inputFile"/>
<property name="lineMapper">
<bean class="org.springframework.batch.item.file.mapping.DefaultLineMapper">
<property name="lineTokenizer">
<bean class="org.springframework.batch.item.file.transform.DelimitedLineTokenizer">
<property name="names" value="field,value"/>
<property name="delimiter" value="="/>
</bean>
</property>
<property name="fieldSetMapper">
<bean class="org.springframework.batch.item.file.mapping.BeanWrapperFieldSetMapper">
<property name="prototypeBeanName" value="configProperties"/>
</bean>
</property>
</bean>
</property>
</bean>
<bean id="outputConfig" class="outputConfig"></bean>
<bean id="configProperties" class="configProperties" scope="prototype"/>
so my question are :
How can I use the information gathered in the file ? Should I put them in the Java bean ?
How can I pas this info between different step or make them persistent in the whole application life-cycle ?
Would you recommend to use a itemProcessor to achieve the above ?
Any advice are most than welcome
I'm a bit confused about your questions because I think you only need to load a properties file in spring context using a PropertiesFactoryBean:
<bean id="config" class="org.springframework.beans.factory.config.PropertiesFactoryBean">
<property name="location">
<value>file:path_config_file</value>
</property>
</bean>
<bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="propertiesArray">
<list>
<ref bean="config"/>
</list>
</property>
</bean>
and you can refer to property values using ${} placeholder; but this solution is unrelated to spring-batch; I don't need it!
About your questions:
Using a POJO is a good way because spring-batch offers in-box mapping strategies (BeanWrapperFieldSetMapper in your case)
Objects used in a job are accessible only in job context, not in application context (this is why I think you need a PropertiesFactoryBean).To pass object between steps read How can we share data between the different steps of a Job in Spring Batch?
ItemProcessor is requested if you need to convert an object T read from a ItemReader<T> to an object of type S written by an ItemWriter<S>. So no, you don't need an ItemProcessor.
I hope I was clear, English is not my native language

How to apply transactions best practice for read operations in Spring MVC using Hibernate?

As it is mentioned in blogs/books (e.g. Java Transactions Design Strategies by Mark Richards), read operations must have the Propagation.SUPPORTS attribute.
In a simple Spring 3.1 MVC project with Hibernate 4.1 the scenario is:
Declarative transaction management using #Transactional
sessionFactory of org.springframework.orm.hibernate4.LocalSessionFactoryBean
Transaction manager of org.springframework.orm.hibernate4.HibernateTransactionManager
Service class with #Transactional(propagation=Propagation.REQUIRED)
Function of that Service class that only retrieves a resultset (performs read operation) with #Transactional(propagation=Propagation.SUPPORTS)
Function of read operation retieves the resultset using sessionFactory.getCurrentSession().get()
Of course, when a Controller executes the function of read operation, the exception "No Session found for current thread" is raised because a transaction is not started and a session is not obtained.
Based on the above configuration (while it is best e.g. non-invasive, less code etc) the Propagation.SUPPORTS attribute cannot be used unless a transaction is started before with Propagation.REQUIRED or Propagation.REQUIRES_NEW.
How do we use use Propagation.SUPPORTS for read operations without having to start a transaction e.g. with Propagation.REQUIRED before but still taking advantage the benefits of declarative transaction management?
Thank you in advance.
Coder, here is the configuration:
<tx:annotation-driven transaction-manager="txManager"/>
<context:component-scan base-package="com.myapps.service.impl" />
<bean id="txManager"
class="org.springframework.orm.hibernate4.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
<property name="driverClassName" value="${db.driverClassName}" />
<property name="url" value="${db.url}" />
<property name="username" value="${db.username}" />
<property name="password" value="${db.password}" />
</bean>
<bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="mappingResources">
<list>
<value>.....</value>
</list>
</property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">${db.dialect}</prop>
<prop key="hibernate.format_sql">true</prop>
</props>
</property>
</bean>
I disagree with using SUPPORTS for read operations. Use REQUIRED.
A transaction is needed anyway to perform every database operation
Doing several small transactions to read several things at once won't benefit from the first-level cache
There won't be any isolation between all the subsequent reads, meaning that something not visible to the first read might become visible for the second one
you'll get lazy loading exceptions when traversing associations
Transaction is not always required for Propagation.SUPPORTS.
Propagation.SUPPORTS: Support a current transaction, execute non-transactionally if none exists.

Nested Spring TxProxyTemplate issue

I have the following config.
<bean id="abcManager" parent="TxProxyTemplate">
<property name="target">
<bean class="com.x.y.AbcManagerImpl">
<property name="abcDAO" ref="abcDAO"/>
<property name="xyzManager" ref="xyzManager"/>
</bean>
</property>
</bean>
<bean id="xyzManager" parent="TxProxyTemplate">
<property name="target">
<bean class="com.x.y.XyzManagerImpl">
<property name="abcDAO" ref="abcDAO"/>
<property name="anotherManager" ref="anotherManager"/>
</bean>
</property>
</bean>
<bean id="anotherManager" parent="TxProxyTemplate">
<property name="target">
<bean class="com.x.y.AnotherManagerImpl">
<property name="abcDAO" ref="abcDAO"/>
<property name="oneMoreManager" ref="oneMoreManager"/>
</bean>
</property>
</bean>
What is the issue with the following configuration? will having the same DAO at the different levels cause concurency issues?
We found that we get lots of weblogic connection releases when we have high load.
How is this related to the connection release issue?
We use Hibernate for DAO operations.
First, analyse the logs to see when spring creates and closes transactions.
Set the logger for org.springframework.transaction to DEBUG for this.
Next my guess is you need to examine your #Transactional annotations (which I assume you use on your managers (=services?). Make sure the propagation is set correctly because this might be related to your issue (hard to say without seeing your manager's code of course).
To answer your question directly:
What is the issue with the following configuration? will having the same DAO at the different levels cause concurency issues?
Nothing, and no. I don't see anything wrong with this. Not sure what you mean about 'same DAO' - you don't have the same DAO. You have the same parent, but 3 distinct DAOs.
If you're asking, then, why is weblogic closing your DB connections before your transaction completes, we wouldn't be able to answer that with the information above.

Spring MVC from 2.5 to 3.0

We are migrating our web application from Spring 2.5 to Spring 3.0.5. Looks like all the Controller classes (the classes in org.springframework.web.servlet.mvc package: BaseCommandController, AbstractCommandController, SimpleFormController, etc) have been deprecated. We used those classes heavily in our application. These classes have been replaced by #Controller annotation instead.
I have a few questions regarding Spring 3.0.x Controller configuration...
We used the following XML to create a Controller bean in Spring 2.5. If <context:component-scan> is used instead to create the Controller beans, then how do I wire-in the dependencies? If possible I would like to avoid Auto-Wiring.
<bean id="photosetViewController" class="com.xyz.web.PhotosetViewController"
p:photosetManager-ref="photosetManager"
p:photoManager-ref="photoManager" />
We have created 3 Interceptors. We use SimpleUrlHandlerMapping to map these Interceptors to different request URLs and also to map URLs to Controllers. How do we achieve the same in Spring 3.0.x?
<bean class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping">
<property name="alwaysUseFullPath" value="true" />
<property name="interceptors">
<list>
<ref bean="httpRedirectInterceptor"/>
<ref bean="loginInterceptor"/>
</list>
</property>
<property name="mappings">
<value>
/abc.html=abcLookupController
/photoupload.html=photoUploadController
</value>
</property>
</bean>
<bean class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping">
<property name="alwaysUseFullPath" value="true" />
<property name="interceptors">
<list>
<ref bean="httpRedirectInterceptor"/>
<ref bean="loginInterceptor"/>
<ref bean="userMenuInterceptor" />
</list>
</property>
<property name="mappings">
<value>
/index.html=homepageController
/success.html=simpleController
</value>
</property>
</bean>
In case of SimpleFormControllers we used different methods like initBinder, referenceData, formBackingObject. We also used command objects and validation classes. How do we achieve the same in Spring 3.0.x?
<bean id="photosetAddController" class="com.xyz.web.PhotosetAddController"
p:photosetManager-ref="photosetManager"
p:photosetTypeManager-ref="photosetTypeManager"
p:stateManager-ref="stateManager" >
<property name="validator">
<bean class="com.xyz.form.PhotosetAddValidator" />
</property>
<property name="formView" value="photosetadd" />
<property name="successView" value="redirect:/photoset" />
</bean>
Any pointers are greatly appreciated.
As skaffman noted - your code will work fine without any modifications. I'll answer your questions in short:
You can use #Resource(name="beanName") for name-based injection. But autowiring is also a good option. Either #Autowired, or #javax.inject.Inject. Note that you can use #Qualifier("name") to differentiate between beans with the same interface/base class. You can even use the javax.inject qualifiers (read about all these in the docs)
interceptor mappings can stay the same
There is #InitBinder, which denotes the initBinder method. I can't tell about the other.

Resources