I faced with following problem in spring-session
:
@RestController
public class TestService {
@Autowired
private SessionRepository sessionRepository;
@GetMapping("/test")
public void test() {
Session session = sessionRepository.createSession();
TestDomain testDomain = new TestDomain("a", 1);
session.setAttribute(session.getId(), testDomain);
sessionRepository.save(session);
Session session1 = sessionRepository.getSession(session.getId());
Object testDomainObj = session1.getAttribute(session1.getId());
// I wonder why TestDomainObj is not an instance of TestDomain??
System.out.println("Does testDomainObj from session represent the instance of TestDomain class: " + (testDomainObj instanceof TestDomain));
// java.lang.ClassCastException: com.example.demo.TestDomain cannot be cast to com.example.demo.TestDomain
TestDomain testDomain1 = (TestDomain) testDomainObj;
System.out.println(testDomain1);
}
}
I tried to search and found that after getting testDomainObj
it is the instance of Object class. So, it is clear that deserialized object loses its metainformation.
I configured JdbcOperationsSessionRepository
like this:
@Configuration
public class AppConfig {
@Bean
SessionRepository sessionFactoryBean(JdbcTemplate jdbcTemplate, PlatformTransactionManager transactionManager) {
return new JdbcOperationsSessionRepository(jdbcTemplate, transactionManager);
}
}
And activated it in application.properties
:
spring.session.store-type=jdbc
spring.session.jdbc.initializer.enabled=true
Last thing testDomain
object has been saved in Database after executing sessionRepository.save(session);
How to understand and cope with this problem?