Serialization exception using spring-sessions - spring-boot

Primefaces/Joinfaces JSF app in Spring-Boot.
App is working fine running stand-alone, but I have recently started implementing session replication via Spring-Session. When the session is persisted to the session store, I get a not serializable exception.
Caused by: java.io.NotSerializableException:
com.company.application.service.dao.security.RoleBasedSecurityDao$$EnhancerBySpringCGLIB$$9de506c
Looking at that error message, it looks like the serialization exception is not for the class itself, but for something owned by the class. The only thing it has on it is the JDBCTemplate.
#Repository
public class RoleBasedSecurityDao {
private final static Logger log = LoggerFactory.getLogger(RoleBasedSecurityDao.class);
private NamedParameterJdbcTemplate jdbcTemplate;
#Autowired
#Qualifier("dataSource")
public void setDataSource(DataSource dataSource) {
jdbcTemplate = new NamedParameterJdbcTemplate(dataSource);
}
[...]
}
If I add "implements Serializable" to the class definition, the error changes:
Caused by: java.io.NotSerializableException:
org.springframework.dao.support.PersistenceExceptionTranslationInterceptor
I am not familiar with JSF, but from what I have read, the expectation is that all of your JSF classes are serializable. How can I make my DAO serializable, when it needs an instance of JdbcTemplate?

As #Selaron pointed out, the issue was non-transient spring beans on JSF controllers. Don't do that.

Related

#Transactional not starting transactions with Spring Boot 3 / Hibernate 6

I am currently migrating to Spring Boot 3 / Hibernate 6.
Hibernate is correctly parsing all the entities and repos, connecting to the database, etc...
However, it seems #Transactional is not starting transactions correctly.
Small example:
#Component
public class Test {
#Autowired
private EntityManagerFactory entityManager;
#Transactional
public void test() {
Session s = entityManager.unwrap(SessionFactory.class).getCurrentSession();
s.createQuery("FROM sometable").list();
}
}
Error:
Caused by: org.hibernate.HibernateException: Calling method 'createQuery' is not valid without an active transaction (Current status: NOT_ACTIVE)
at org.hibernate.context.internal.ThreadLocalSessionContext$TransactionProtectionWrapper.invoke(ThreadLocalSessionContext.java:341)
Relevant Config:
#Configuration
#EnableTransactionManagement
#EnableJpaRepositories(basePackages="com.somepackage")
#EntityScan(basePackages="com.somepackage")
public class TransactionConfig {
...
}
session context class in application.properties
...
spring.jpa.properties.hibernate.current_session_context_class=thread
...
If I remove the above setting of session_content_class=thread,
I get this error:
Caused by: org.hibernate.HibernateException: No CurrentSessionContext configured
Edit 1:
The below still results in the same error "is not valid without an active transaction"
#PersistenceUnit
private EntityManagerFactory entityManager;
Edit 2:
If I do not unwrap a session and just call a class with extends extends JpaRepository, it works... but it creates a new transaction and ignores the parent #Transaction
Fix was the following:
#PersistenceContext
private EntityManager entityManager;
and to unwrap:
Session s = entityManager.unwrap(Session.class);

Delaying Dependency Injection in Spring

I'm writing an app that talks to one database, obtains credentials for other databases, and connects to the others. It does this using a DataSource and EntityManagerFactory constructed at runtime.
If I want to use Spring Data Repositories, I think I'd need to Autowire them, and therefore they must be Spring Beans.
How can I use Spring Data if I don't have a constructed DataSource until after I run a query against the first database?
I believe that conditional bean creation is your answer. check here.
Also, you have to get the bean after you make sure the conditions are met. check here.
#Component
public class RuntimeBeanBuilder {
#Autowired
private ApplicationContext applicationContext;
public MyObject load(String beanName, MyObject myObject) {
ConfigurableApplicationContext configContext = (ConfigurableApplicationContext) applicationContext;
SingletonBeanRegistry beanRegistry = configContext.getBeanFactory();
if (beanRegistry.containsSingleton(beanName)) {
return beanRegistry.getSingleton(beanName);
} else {
beanRegistry.registerSingleton(beanName, myObject);
return beanRegistry.getSingleton(beanName);
}
}
}
#Service
public MyService{
//inject your builder and create or load beans
#Autowired
private RuntimeBeanBuilder builder;
//do something
}
So, define a bean for your Spring Data Repository and set its condition to be met when the other database credentials are fetched.
And then, reloading the bean using the RuntimeBeanBuilder in your service will get you the bean because now its condition is met.

ClassBridge with DAO class injected

I have a Hibernate Search ClassBridge where I want to use #Inject to inject a Spring 4.1 managed DAO/Service class. I have annotated the ClassBridge with #Configurable. I noticed that Spring 4.2 adds some additional lifecycle methods that might do the trick, but I'm on Spring 4.1
The goal of this is to store a custom field into the index document based on a query result.
However, since the DAO, depends on the SessionFactory getting initialized, it doesn't get injected because it doesn't exist yet when the #Configurable bean gets processed.
Any suggestions on how to achieve this?
You might try to create a custom field bridge provider, which could get hold of the Spring application context through some static method. When provideFieldBridge() is called you may return a Spring-ified instance of that from the application context, assuming the timing is better and the DAO bean is available by then.
Not sure whether it'd fly, but it may be worth trying.
Hibernate Search 5.8.0 includes support for bean injection. You can see the issue https://hibernate.atlassian.net/browse/HSEARCH-1316.
However I couldn't make it work in my application and I had implemented a workaround.
I have created an application context provider to obtain the Spring application context.
public class ApplicationContextProvider implements ApplicationContextAware {
private static ApplicationContext context;
public static ApplicationContext getApplicationContext() {
return context;
}
#Override
public void setApplicationContext(ApplicationContext context) throws BeansException {
ApplicationContextProvider.context = context;
}
}
I have added it to the configuration class.
#Configuration
public class RootConfig {
#Bean
public ApplicationContextProvider applicationContextProvider() {
return new ApplicationContextProvider();
}
}
Finally I have used it in a bridge to retrieve the spring beans.
public class AttachmentTikaBridge extends TikaBridge {
#Override
public void set(String name, Object value, Document document, LuceneOptions luceneOptions) {
// get service bean from the application context provider (to be replaced when HS bridges support beans injection)
ApplicationContext applicationContext = ApplicationContextProvider.getApplicationContext();
ExampleService exampleService = applicationContext.getBean(ExampleService .class);
// use exampleService ...
super.set(name, content, document, luceneOptions);
}
}
I think this workaround it's quite simple in comparision with other solutions and it doesn't have any big side effect except the bean injection happens in runtime.

Spring Data JPA Transaction - No Transaction in progress - Spring Data Neo4j

I think i'm missing something obvious. Iam trying to make a entity persist into a database via a JUnit Test case, however it doesnt seem to be persisting due to no active transaction.
Configuration:
#Configuration
#EnableTransactionManagement
public class TransactionConfig {
#Inject
private EntityManagerFactory entityMangerFactory;
#Bean
public JpaTransactionManager transactionManager(){
return new JpaTransactionManager(entityMangerFactory);
}
TestCase:
#RunWith(SpringJUnit4ClassRunner.class)
#SpringApplicationConfiguration(classes = { Application.class })
#ActiveProfiles(CommonConstants.SPRING_PROFILE_TEST)
#IntegrationTest
#WebAppConfiguration
public class UserRepositoryTest {
#Inject
UserRepository userRepo;
#Test
#Rollback(false)
#Transactional("transactionManager")
public void addUser() {
User user = BootstrapDataPopulator.getUser();
userRepo.save(user);
System.out.println(user.getId()); //Successfully outputs the id generate by hibernate
assertNotNull(user.getId());
}
}
^This test case executed successfully however I do not see any entiites persisted in the database as expected.
When I change the from userRepo.save(user) to userRepo.saveAndFlush(user) I get the following exception:
javax.persistence.TransactionRequiredException: no transaction is in progress
at org.hibernate.jpa.spi.AbstractEntityManagerImpl.checkTransactionNeeded(AbstractEntityManagerImpl.java:1171)
at org.hibernate.jpa.spi.AbstractEntityManagerImpl.flush(AbstractEntityManagerImpl.java:1332)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
Spring Boot AutoConfiguration Report: http://dumptext.com/YcGaR3Wf
Names of all Spring Beans Initialized: http://dumptext.com/jp9O6l8v
I am using Spring Data Neo4j (SDN) in my application as well. SDN comes with a default class Neo4jConfiguration which has:
#Bean(name = {"neo4jTransactionManager","transactionManager"})
#Qualifier("neo4jTransactionManager")
public PlatformTransactionManager neo4jTransactionManager() throws Exception {
return new JtaTransactionManagerFactoryBean(getGraphDatabaseService()).getObject();
}
The "transactionManager" overrides the bean defined in my TransactionConfig class. Hence the reason no Entity transaction was in progress. I stopped using the SDN class Neo4jConfiguration. This resolved my issue.

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

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 !!!!!

Resources