load data from data base by ajax request by primefaces "selectOnemenu" component - spring

i use spring3 with hibernate3 and jsf2 with primefaces..
I have a problem when i try to load data from the db , i get null pointer Exception as the session factory is null !
I think the problem comes from :
when i made my managedBean in the viewscoped it gives me "Not serializable Exception" so i make all the class members implement serialaizable but it also gives me the not serializable Exception but for this class "org.springframework.orm.hibernate3.LocalSessionFactoryBean" , so i made the session factory transient .
after i made the session factory transient the application works fine but if i made ajax request the session factory is null so i have null pointer exception !!!
any help will be appreciated..
thanks inadvance

Not really create a new session factory
You are using spring so reference tree must be something
ManagedBean -> Spring Service -> Spring Repository
Your managed beans should have reference to a service layer(Singleton). This reference you should mark as transient and fetch from application context in method hooks.
The service bean will always be available from context and you dont have to recreate any instance, its just you pick it back from context.
As for hibernate, it should be in Repository layer and since you have protected your service layer from serialization Repository will not be serialized and hence no issue as above.
#ViewScoped
public class ManagedBean implements Serializable {
#Autowired private transient Service service;
}
#Service
public class ServiceImpl implements Service{
#Autowired private Repository repository;
}
#Repository
public class RepositoryImpl extends HibernateDaoSupport implements Repository {
//here you can have hibernate session factory injected for dao support
}
Hope this helps !!!!!

Related

#Transactional in a service class with no call to database

When a service class has no implementation of Jpa repository ,My understanding is that it is wrong to annotate it with Transactional, for example this service class with should not have #Transactional
#Service
public class BillingAddressServiceImpl implements BillingAddressService {
public BillingAddress setByUserBilling(UserBilling userBilling, BillingAddress billingAddress) throws DataAccessException
{
billingAddress.setBillingAddressName(userBilling.getUserBillingName());
billingAddress.setBillingAddressStreet1(userBilling.getUserBillingStreet1());
billingAddress.setBillingAddressStreet2(userBilling.getUserBillingStreet2());
billingAddress.setBillingAddressCity(userBilling.getUserBillingCity());
billingAddress.setBillingAddressState(userBilling.getUserBillingState());
billingAddress.setBillingAddressCountry(userBilling.getUserBillingCountry());
billingAddress.setBillingAddressZipCode(userBilling.getUserBillingZipCode());
return billingAddress;
}
}
The Transactional annotation stands for declaring the database transaction handling of Spring bean methods.
Since your service method is not working with the database it makes no sense to declare a transaction handling.
Transactional annotations are only used with method or classes that makes calls to database,one of the uses of transactional annotation is rollback - which means when we make call to a database there would be a recording of the intermidiate state between the successful call and its original state, this is so that in the case of a failed call the system does not crash but is able to return to its original state

Spring #Configurable with JavaConfig on GAE-Objectify classes

I have such an Objectify Entity class
#Entity
#Cache
#Index
public class DummyEntity {
#Id private Long id;
private ObjectifyStartup objectifyStartup;
private String someData;
//Getters and setters for all
}
This ObjectifyStartup is a bean initialized in Web MVC JavaConfig file which I need to be injected into any DummyEntity instance
#EnableWebMvc
#Configuration
public class SpringWebMvcConfig extends WebMvcConfigurerAdapter {
#Bean
public ObjectifyStartup objectifyStartup() { return new ObjectifyStartupImpl(); }
}
I want to do this somewhere in the code, basically in a controller
DummyEntity newDummy = new DummyEntity();
I know I need to use #Configurable annotation on the DummyEntity to make the Spring container inject the dependency, but what is the JavaConfig code I have to put into SpringWebMvcConfig class for this DI to work?
I cannot use Autowiring, Component Scans because of the performance hit in GAE due to Autowiring from best practices mentioned here Spring GAE Optimization . And all the solutions I have encountered uses #Autowired with #ComponentScan with <context:spring-configured/>. Kindly provide a solution that uses subjective declarations than autowiring.
After quite some time since I asked this question, I changed the strategy and I am now not initializing a ObjectifyStartup bean to provide me with ofy() service, as from Objectify Docs it is not advisable to create an instance of ofy() and using it pan-application. I was doing it so here because in the ObjectifyStartup bean I was registering all my Entities with the Objectify and then getting hold of its bean instantiation to do datastore operations. But now I have moved the Entities registration to a static block that executes with Spring bootstraps my application.

null pointer exception whilst using spring - although bean loaded correctly

i have a bean:
public class StatusPollingFilter extends AbstractDiscovery implements UserTester
defined as :
<bean
id="statusPollingFilter"
class="com.xxxxx.yyyyyyy.zzz.StatusPollingFilter">
<property
name="evoDao"
ref="evoDaoFacade">
</property>
it loads ok, as logs show:
2013-03-07 11:30:14,703 INFO DefaultListableBeanFactory [RunJSPModule] - Pre-instantiating singletons in org.springframework.beans.factory.support.DefaultListableBeanFactory#14966cc: defining beans [org.springframework.aop.config.internalAutoProxyCreator,org.springframework.transaction.config.internalTransactionAdvisor,tilesConfigurer,viewResolver,urlMapping,discovery,statu
sPollingFilter,
when i try to use it as:
TopoObject topoobj = evoDao.getTopoObjectDao().findById(topoId);
evoDao is the main guy doing the work this is defined in:
class AbstractDiscovery
as:
//Reference to the DAO facade, for accessing the database via hibernate.
protected EvoTAMDAOFacade evoDao;
The Question?
because i extend AbstractDiscovery i thought i would be able to access evoDao and use it as normal to get my Dao but it seems not - where am i going wrong?
why can it not find the Dao?
The EvoTAMDAOFacade is injected into AbstractDiscovery as:
/**
* DI method for accessing the DAO facade for accessing the
* database via hibernate.
* #param dao
*/
public void setEvoDao(EvoTAMDAOFacade dao)
{
this.evoDao = dao;
}
the getTopoObjectDao() is defined in the injected EvoTAMDAOFacade of as:
public TopoObjectDAO getTopoObjectDao()
{
return this.topoObjectDao;
}
AbstractDiscovery is defined as:
public abstract class AbstractDiscovery implements Discovery
The exception is :
[07 Mar 2013 11:42:24:353] POLL: Exception while getting obj during status update java.lang.NullPointerException 162.109.37.114 at:
java.lang.NullPointerException
Another Q? the statusPollFilter is running as thread in a scheduler for multiple objects - i'm not actually sure i should be defining it as a singleton bean but how do i access the Dao if i don't?
thanks in advance for your help.
having read more - i have come across the ans.
because the StatusPollingFilter object is under control of scheduler (i knew that scheduler had something to do with it) then it is unaware of the spring beans which is why i keep getting null when i try injecting the bean.
i created a class:
ApplicationContextProvider implements ApplicationContextAware
added static access
private static ApplicationContext appContext;
did a setter for it :
public void setApplicationContext(ApplicationContext context)
{
appContext = context;
}
and added
public static Object getBean(String beanName) throws BeansException
{
return appContext.getBean(beanName);
}
used in code as :
EvoTAMDAOFacade evoDao = (EvoTAMDAOFacade) ApplicationContextProvider.getBean("evoDaoFacade");
i now have access to the facade bean and all injected beans into facade.
i still have an issue with hibernate session but thats prob due to some other issue.
pt here is i don't have access to the bean as its not in control of the spring container so i needed to somehow get it , probably could have done it via the factory method but why mess around when there a simpler way.
thanks for help by anyone who may have posted or tried to understand my problem.

Spring autowiring with bean scope of prototype

I have a question in spring with autowire with a bean which is having a scope of prototype..
So basically i am writing a code which is spring with JPA.So i am autowiring my entity manager in my DAO layer .I am loading the entitymanager from a class by using the #configuraion Annotation .
#Configuration
public class DALConfigurationLoader {
#Bean
#Scope("prototype")
public EntityManager getEntityManager() {
}
When i do this i am expecting that for every request it should get a new bean .
#Component
public class OfferPriceDomainDAOImpl {
#Autowired
private EntityManager entityManager;
public OfferPrice getOfferPrice(String offer_Price_Id) throws DataAccessException{
//use entitymanager here
}
}
In this case it is a single entity manager for all the request which is wrong.i want each method should get a new entity manager .As based on the jpa specification every new request should process a new entity manager...How can i autowire a bean with a scope of prototype..
I would really appreciate if some one can answer my question..
Thank,
Swati
Use #PersistenceContext to inject an EntityManager, not #Autowired, as outlined in the JPA section of the Spring reference guide. It takes care of the lifecycle for you properly.
As to why it wasn't working the way you thought it might: whenever an instance of your DAO is created, it would be injected with an EntityManager. Since the EntityManager is scope=prototype, a new one will be created for each DAO that needs to be injected for one. However, since your DAO is a singleton, only one of them is created, so only one EntityManager is ever needed.
#Inject // or #Autowire
Provider<EntityManager> entityManagerProvider;
and then get EntityManager instance using entityManagerProvider.get().
I used javax.inject.Inject instead of Autowire because Provider is defined there too. Also that also would work in Guice.

Spring MVC + Hibernate DAOs : unable to wire beans

I'm currently working on a Spring MVC project in which I integrated Hibernate. The pure Spring MVC part (DispatcherServlet + request mapping) works fine. Now, the problem I have to cope with is quite strange : I've read "Java Persistence with Hibernate" and I am trying to design my persistence layer in a similar way than explained in the book. That is, I've designed it in two parallel hierarchies : one for implementation classes and a second for the interfaces.
So, I have an abstract class named GenericDaoImpl, that implements the GenericDao interface. Then I have a concrete class named AdvertisementDaoImpl, that extends GenericDaoImpl and that implements the AdvertisementDao interface (which extends GenericDao).
Then, in a service bean (class marked with #Service), I'll have my dao class autowired.
Here's my problem :
autowiring a DAO class that implements an interface but does not extends my abstract GenericDaoImpl class : OK
autowiring my AdvertisementDaoImpl that implements the AdvertisementDao interface and extends my abstract GenericDaoImpl class : leads to bean initialization exception.
The abstract class I have at the top of my DAO hierarchy handles all the boilerplate code for common CRUD methods. So, I definitely want to keep it.
Does anyone have an explanation about that?
Here's an excerpt of code :
public abstract class GenericDaoImpl <T, ID extends Serializable> implements BeanPostProcessor, GenericDao<T, ID>{
#Autowired(required=true)
private SessionFactory sessionFactory;
private Session currentSession;
private Class<T> persistentClass;
...
}
#Repository
public class AdvertisementDaoImpl extends GenericDaoImpl<Advertisement, Long> implements AdvertisementDao {
...
public List<Advertisement> listAdvertisementByType(AdvertisementType advertisementType, Class<? extends Good> type) {
return null;
}
}
#Service
public class AdvertisementServiceImpl implements AdvertisementService{
#Autowired(required=false)
private AdvertisementDao advertisementDao;
public List<Advertisement> listAllAdvertisements() {
return null;
}
}
Here's the most relevant part of the stacktrace (at least, I guess it is):
nested exception is
org.springframework.beans.factory.BeanCreationException: Could not
autowire field: be.glimmo.service.AdvertisementService
be.glimmo.controller.HomeController.advertisementService; nested
exception is java.lang.IllegalArgumentException: Can not set
be.glimmo.service.AdvertisementService field
be.glimmo.controller.HomeController.advertisementService to
be.glimmo.dao.AdvertisementDaoImpl
And here's my Spring configuration (link to pastebin.com) :
I believe you should use proxy-target-class in your transaction management configuration:
<tx:annotation-driven transaction-manager="transactionManagerForHibernate"
proxy-target-class="true" />
The symptoms of the problem you describe match the ones mentioned in Spring Transaction Management (look for Table 10.2) and AOP proxying with Spring:
If the target object to be proxied implements at least one interface
then a JDK dynamic proxy will be used. All of the interfaces
implemented by the target type will be proxied. If the target object
does not implement any interfaces then a CGLIB proxy will be created.
So, when CGLIB is not there by default, you have all the methods coming from implemented interfaces but you will miss proxying of the methods that come from super classes in the hierarchy and that's why you get an exception on this.
After a few more tests, it turns out that the problem was caused by my abstract GenericDaoImpl class implementing BeanPostProcessor interface : for some reason, the methods from this interface were executed not only at this bean instantiation but at every bean intantiation.
Given that, within my BeanPostProcessor hook methods, I was retrieving generics parameterized types, when these methods were executed against classes that are not in my DAO hierarchy, they would end up yielding runtime Exceptions (more specifically, ClassCastException).
So, to solve this issue, I had my GenericDaoImpl class not implement BeanPostProcessor interface anymore and I moved the body of the hook method in the empty contructor.

Resources