what does this error message mean?
2016-01-23 19:07:24,914 WARN ta.neo4j.mapping.Neo4jPersistentProperty: 73 - Owning ClassInfo is null for field: private java.lang.Long com.xenoterracide.rpf.AbstractPersistable.id and propertyDescriptor: org.springframework.beans.GenericTypeAwarePropertyDescriptor[name=id]
here's this class
public abstract class AbstractPersistable implements Identified<Long> {
private Long id;
#Override
public Long getId() {
return this.id;
}
}
I restructured my packages, and the component scan for Neo4j as defined in my config, was no longer correct. So if you get this error make sure that the class is within the scan path of the neo4j session.
#Configuration
#Profile( Strings.Profiles.EMBEDDED )
class EmbeddedConfig extends Neo4jConfiguration {
#Bean
#Override
#Scope( value = "session", proxyMode = ScopedProxyMode.TARGET_CLASS )
public Session getSession() throws Exception {
return super.getSession();
}
#Bean
#Override
public Neo4jServer neo4jServer() {
return new InProcessServer();
}
#Bean
#Override
public SessionFactory getSessionFactory() {
return new SessionFactory( Strings.PackagePaths.getModelPackages() );
}
}
Related
This question already has answers here:
How to autowire #ConfigurationProperties into #Configuration?
(2 answers)
Closed 3 years ago.
Java 8 and Spring Boot 1.5.8 here. I have the following application.properties file:
logging:
config: 'logback.groovy'
myapp:
hystrixTimeoutMillis: 500
jwt:
expiry: 86400000
secret: 12345
machineId: 12345
spring:
cache:
type: none
Which maps to the following #ConfigurationProperties POJO:
#ConfigurationProperties(prefix = "myapp")
public class MyAppConfig {
private Jwt jwt;
private Long hystrixTimeoutMillis;
private String machineId;
public Jwt getJwt() {
return jwt;
}
public void setJwt(Jwt jwt) {
this.jwt = jwt;
}
public Long getHystrixTimeoutMillis() {
return hystrixTimeoutMillis;
}
public void setHystrixTimeoutMillis(Long hystrixTimeoutMillis) {
this.hystrixTimeoutMillis = hystrixTimeoutMillis;
}
public String getMachineId() {
return machineId;
}
public void setMachineId(String machineId) {
this.machineId = machineId;
}
public static class Jwt {
private Long expiry;
private String secret;
public Long getExpiry() {
return expiry;
}
public void setExpiry(Long expiry) {
this.expiry = expiry;
}
public String getSecret() {
return secret;
}
public void setSecret(String secret) {
this.secret = secret;
}
}
}
And I have the following #Configuration (injector) class:
#Configuration
public class MyAppInjector implements ApplicationContextAware {
private Logger log = LoggerFactory.getLogger(this.getClass());
private ApplicationContext applicationContext;
#Autowired
private MyAppConfig myAppConfig;
#Bean
public AuthService authService(MyAppConfig myAppConfig) {
return new JwtAuthService(myAppConfig);
}
}
And the following JwtAuthService class:
public class JwtAuthService implements AuthService {
private static final String BEARER_TOKEN_NAME = "Bearer";
private Logger log = LoggerFactory.getLogger(this.getClass());
private MyAppConfig myAppConfig;
#Autowired
public JwtAuthService(MyAppConfig myAppConfig) {
this.myAppConfig = myAppConfig;
}
#Override
public boolean isValidAuthToken(String authToken) {
return true;
}
}
At startup I get the following error:
***************************
APPLICATION FAILED TO START
***************************
Description:
Field myAppConfig in com.example.myapp.spring.MyAppInjector required a bean of type 'com.example.myapp.spring.MyAppConfig' that could not be found.
Action:
Consider defining a bean of type 'com.example.myapp.spring.MyAppConfig' in your configuration.
Why am I getting this error? Where am I injecting/configuring things incorrectly?
You are not declaring MyAppConfig as a bean anywhere in your example, #ConfigurationProperties doesn't make annotated class a bean. You can do it as part of MyAppInjector configuration:
#Configuration
public class MyAppInjector {
#Bean
public AuthService authService() {
return new JwtAuthService(myAppConfig());
}
#Bean
public MyAppConfig myAppConfig() {
return new MyAppConfig();
}
}
Class with #ConfigurationProperties should also be bean. You need to annotate it as #Component or manually register in #Configuration class with #Bean annotation (instead of trying to autowire it there)
I'm creating a Spring REST app using Spring Boot 2, Spring Data REST, Spring HATEOAS.
I created this controller:
#Api(tags = "City Entity")
#RepositoryRestController
#RequestMapping(path = "/api/v1")
#PreAuthorize("isAuthenticated()")
public class CityController {
#Autowired
private LocalValidatorFactoryBean validator;
#Autowired
private PagedBeanResourceAssembler<City> pagedBeanResourceAssembler;
#Autowired
private CityService cityService;
#InitBinder
protected void initBinder(WebDataBinder binder) {
binder.addValidators(validator);
}
#GetMapping(path = "/cities/search/autocomplete")
public ResponseEntity<?> autocomplete(#RequestParam(name = "city") String city, #RequestParam(name = "country", required = false) String country, Pageable pageable, Locale locale) {
return new ResponseEntity<>(pagedBeanResourceAssembler.toResource(cityService.autocomplete(city, country, pageable)), HttpStatus.OK);
}
}
The service method is:
#Transactional(readOnly = true)
public Page<City> autocomplete(String text, String country, Pageable pageable) {
//my logic
return elasticSearchManager.search(ElasticSearchUtil.getIndexName(City.class), null, City.class, filters, null, pageable);
}
As you can see City bean is not stored in the DB. In fact the bean is:
public class City implements Persistable<Long> {
private Long id;
#NotBlank
private String name;
private String district;
private String region;
private String zipCode;
#NotNull
#Size(min = 2, max = 2)
private String country;
}
and finally this is my PagedBeanResourceAssembler:
#Component
public class PagedBeanResourceAssembler<T> implements ResourceAssembler<Page<T>, PagedResources<T>> {
#Autowired
private EntityLinks entityLinks;
#Override
public PagedResources<T> toResource(Page<T> page) {
PagedResources<T> pagedResources = new PagedResources<T>(page.getContent(), asPageMetadata(page));
return pagedResources;
}
private PagedResources.PageMetadata asPageMetadata(Page<?> page) {
Assert.notNull(page, "Page must not be null!");
return new PagedResources.PageMetadata(page.getSize(), page.getNumber(), page.getTotalElements(), page.getTotalPages());
}
}
When I make a http call I see a WARNING message in the console:
08/02/2019 11:09:35,526 WARN http-nio-8082-exec-1 RepositoryRestMvcConfiguration$ResourceSupportHttpMessageConverter:205 - Failed to evaluate Jackson serialization for type [class org.springframework.hateoas.PagedResources]: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'org.springframework.hateoas.hal.Jackson2HalModule$HalResourcesSerializer': Instantiation of bean failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.hateoas.hal.Jackson2HalModule$HalResourcesSerializer]: No default constructor found; nested exception is java.lang.NoSuchMethodException: org.springframework.hateoas.hal.Jackson2HalModule$HalResourcesSerializer.<init>()
08/02/2019 11:09:35,527 WARN http-nio-8082-exec-1 MappingJackson2HttpMessageConverter:205 - Failed to evaluate Jackson serialization for type [class org.springframework.hateoas.PagedResources]: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'org.springframework.hateoas.hal.Jackson2HalModule$HalResourcesSerializer': Instantiation of bean failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.hateoas.hal.Jackson2HalModule$HalResourcesSerializer]: No default constructor found; nested exception is java.lang.NoSuchMethodException: org.springframework.hateoas.hal.Jackson2HalModule$HalResourcesSerializer.<init>()
Not using a PagedResources the error goes away. I don't understand where I'm doing something wrong. I got that HalResourcesSerializer has not a default constructor, but I don't use it directly and I don't understand either why with Entity persisted in the db a controller such this works fine.
How can I fix this problem continuing to use a PagedResource?
======== UPDATE ==========
I add my configuration to give a more detailed view:
CustomConfiguration:
#Configuration
#EnableRetry
#EnableTransactionManagement
#EnableJpaAuditing(auditorAwareRef = "springSecurityAuditorAware")
public class CustomConfiguration {
public static CustomConfiguration INSTANCE;
#PostConstruct
public void init() {
INSTANCE = this;
}
#Bean
public static PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer() {
return new PropertySourcesPlaceholderConfigurer();
}
#Bean
public static SpringSecurityAuditorAware springSecurityAuditorAware() {
return new SpringSecurityAuditorAware();
}
#Bean
public MessageSource messageSource() {
ReloadableResourceBundleMessageSource messageSource = new ReloadableResourceBundleMessageSource();
messageSource.setBasenames("classpath:/i18n/messages");
// messageSource.setDefaultEncoding("UTF-8");
// set to true only for debugging
messageSource.setUseCodeAsDefaultMessage(false);
messageSource.setCacheSeconds((int) TimeUnit.HOURS.toSeconds(1));
messageSource.setFallbackToSystemLocale(false);
return messageSource;
}
#Bean
public MessageSourceAccessor messageSourceAccessor() {
return new MessageSourceAccessor(messageSource());
}
/**
* Enable Spring bean validation https://docs.spring.io/spring/docs/current/spring-framework-reference/core.html#validation
*
* #return
*/
#Bean
public LocalValidatorFactoryBean validator() {
LocalValidatorFactoryBean factoryBean = new LocalValidatorFactoryBean();
factoryBean.setValidationMessageSource(messageSource());
return factoryBean;
}
#Bean
public MethodValidationPostProcessor methodValidationPostProcessor() {
MethodValidationPostProcessor methodValidationPostProcessor = new MethodValidationPostProcessor();
methodValidationPostProcessor.setValidator(validator());
return methodValidationPostProcessor;
}
/**
* Utility class from Google to work with phone numbers {#link https://github.com/googlei18n/libphonenumber}
*
* #return
*/
#Bean
public PhoneNumberUtil phoneNumberUtil() {
return PhoneNumberUtil.getInstance();
}
/**
* To enable SpEL expressions
*
* #return
*/
#Bean
public SecurityEvaluationContextExtension securityEvaluationContextExtension() {
return new SecurityEvaluationContextExtension();
}
/**
* Define the specific storage manager to use (disk, S3, etc)
*
* #return
*/
#Bean
public StorageManager storageManager() {
return new S3StorageManager();
}
/**
* GRACEFUL SHUTDOWN
*/
#Bean
public GracefulShutdown gracefulShutdown() {
return new GracefulShutdown();
}
#Bean
public ConfigurableServletWebServerFactory webServerFactory(final GracefulShutdown gracefulShutdown) {
TomcatServletWebServerFactory factory = new TomcatServletWebServerFactory();
factory.addConnectorCustomizers(gracefulShutdown);
return factory;
}
}
GlobalRepositoryRestConfigurer:
#Configuration
public class GlobalRepositoryRestConfigurer implements RepositoryRestConfigurer {
private Logger log = LogManager.getLogger();
#Autowired(required = false)
private Jackson2ObjectMapperBuilder objectMapperBuilder;
#Autowired
private Validator validator;
#Value("${cors.mapping}")
private String corsMapping;
#Value("#{'${cors.allowed.headers}'.split(',')}")
private String[] corsAllowedHeaders;
#Value("#{'${cors.exposed.headers}'.split(',')}")
private String[] corsExposedHeaders;
#Value("#{'${cors.allowed.methods}'.split(',')}")
private String[] corsAllowedMethod;
#Value("#{'${cors.allowed.origins}'.split(',')}")
private String[] corsAllowedOrigins;
#Value("${cors.max.age}")
private int corsMaxAge;
#Override
public void configureRepositoryRestConfiguration(RepositoryRestConfiguration config) {
config.getCorsRegistry().addMapping(corsMapping).exposedHeaders(corsExposedHeaders).allowedOrigins(corsAllowedOrigins)
.allowedHeaders(corsAllowedHeaders).allowedMethods(corsAllowedMethod).maxAge(corsMaxAge);
}
#Override
public void configureConversionService(ConfigurableConversionService conversionService) {
}
/**
* ValidationException serialiazer
*
* #return
*/
#Bean
public ValidationExceptionSerializer validationExceptionSerializer() {
return new ValidationExceptionSerializer();
}
#Bean
public CustomValidationExceptionSerializer customValidationExceptionSerializer() {
return new CustomValidationExceptionSerializer();
}
#Bean
public ConstraintViolationExceptionSerializer constraintViolationExceptionSerializer() {
return new ConstraintViolationExceptionSerializer();
}
/**
* Customize Object Mapper
*/
#Override
public void configureJacksonObjectMapper(ObjectMapper objectMapper) {
if (this.objectMapperBuilder != null) {
/**
* Custom serializer for ConstraintViolationException
* (https://jira.spring.io/browse/DATAREST-593)
*/
try {
SimpleModule constraintExceptionModule = new SimpleModule();
constraintExceptionModule.addSerializer(ConstraintViolationException.class, constraintViolationExceptionSerializer());
constraintExceptionModule.addSerializer(ValidationException.class, validationExceptionSerializer());
constraintExceptionModule.addSerializer(cloud.optix.server.exceptions.ValidationException.class, customValidationExceptionSerializer());
objectMapper.registerModule(constraintExceptionModule);
this.objectMapperBuilder.configure(objectMapper);
} catch (Exception e) {
log.error("", e);
}
}
}
#Override
public void configureValidatingRepositoryEventListener(ValidatingRepositoryEventListener validatingListener) {
validatingListener.addValidator("beforeCreate", validator);
validatingListener.addValidator("beforeSave", validator);
}
#Override
public void configureExceptionHandlerExceptionResolver(ExceptionHandlerExceptionResolver exceptionResolver) {
}
/**
* Adding converter to donwload files in{#link org.springframework.web.bind.annotation.RestController}
*
* #param messageConverters
*/
#Override
public void configureHttpMessageConverters(List<HttpMessageConverter<?>> messageConverters) {
// super.configureHttpMessageConverters(messageConverters);
messageConverters.add(new ResourceHttpMessageConverter());
}
}
WebMvcConfiguration:
#Configuration
// Enable entity links for Spring HATEOAS
#EnableHypermediaSupport(type = {HypermediaType.HAL})
public class WebMvcConfiguration implements WebMvcConfigurer {
#Autowired
private JwtTokenUtil jwtTokenUtil;
#Autowired
private TenantRestClient tenantRestClient;
#Value("${cors.mapping}")
private String corsMapping;
#Value("#{'${cors.allowed.headers}'.split(',')}")
private String[] corsAllowedHeaders;
#Value("#{'${cors.exposed.headers}'.split(',')}")
private String[] corsExposedHeaders;
#Value("#{'${cors.allowed.methods}'.split(',')}")
private String[] corsAllowedMethod;
#Value("#{'${cors.allowed.origins}'.split(',')}")
private String[] corsAllowedOrigins;
#Value("${cors.max.age}")
private int corsMaxAge;
#Autowired
public WebMvcConfiguration() {
}
#Bean
public LocaleResolver localeResolver() {
return new SmartLocaleResolver();
}
public class SmartLocaleResolver extends CookieLocaleResolver {
#Override
public Locale resolveLocale(HttpServletRequest request) {
String acceptLanguage = request.getHeader("Accept-Language");
if (acceptLanguage == null || acceptLanguage.trim().isEmpty()) {
return super.determineDefaultLocale(request);
}
return request.getLocale();
}
}
/**
* Custom exception in WEB MVC
*
* #return
*/
#Bean
public CustomErrorAttributes myCustomErrorAttributes() {
return new CustomErrorAttributes();
}
/**
* Global CORS security configuration
*
* #param registry
*/
#Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping(corsMapping).exposedHeaders(corsExposedHeaders).allowedOrigins(corsAllowedOrigins).allowedHeaders(corsAllowedHeaders)
.allowedMethods(corsAllowedMethod).maxAge(corsMaxAge);
}
#Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(new TenantInterceptor());
}
}
Try commenting out this line in your configuration:
this.objectMapperBuilder.configure(objectMapper);
RepositoryRestConfigurer configures the objectMapper for itself quite well I assume.
If you need it for automatically adding more modules from your classpath, then add/configure those modules manually.
You will get same error when you use RepresentationModelAssembler<Object, PersistentEntityResource> resourceAssembler as parameter to your controller method. When you use PersistentEntityResourceAssembler resourceAssembler, spring will create right instance for you.
I suggest you to try to examine class hierarchy of PagedBeanResourceAssembler class and find some more specific class/implementation.
The sample project i'm working with can be found attached here -
Spring Jira
This is my configuration
#EnableNeo4jRepositories(basePackages = "com.graph.repository")
public class DBConfig extends Neo4jConfiguration{
#Value("${neo4j.location}")
private String neo4jDatabaseLocation;
#Override
public SessionFactory getSessionFactory() {
return new SessionFactory(getConfiguration(), "com.graph.entity");
}
#Bean
public Configuration getConfiguration() {
Configuration configuration = new Configuration();
configuration.driverConfiguration()
.setDriverClassName("org.neo4j.ogm.drivers.embedded.driver.EmbeddedDriver")
.setURI(neo4jDatabaseLocation);
return configuration;
}
#Bean
#Override
public Session getSession() throws Exception {
return getSessionFactory().openSession();
}
}
Abstract Entity
public abstract class Entity {
#GraphId
private Long id;
public Long getId() {
return id;
}
#Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || id == null || getClass() != o.getClass()) return false;
Entity entity = (Entity) o;
if (!id.equals(entity.id)) return false;
return true;
}
#Override
public int hashCode() {
return (id == null) ? -1 : id.hashCode();
}
}
This is my Entity
#NodeEntity(label = "Patient")
public class Patient extends Entity {
private String patientId;
private String patientName;
private String otherPatientId;
private String sex;
private String dateOfBirth;
private String patientIdIssuer;
#Relationship(type = "STUDY", direction = Relationship.UNDIRECTED)
private Set<Study> studies;
Getters and Setters...
}
Study has nested entity/relationship and that has another nested entity/relationship. 1:N relationship
This is my repository
#Repository
public interface PatientRepository extends GraphRepository<Patient> {
}
And this is the calling method
public class Test() {
#Autowired
private PatientRepository patientRepository;
public void test() {
Patient patient = new Patient();
// set fields
patientRepository.save(patient); -> This is where I get NPE
}
}
Stack Trace :
Caused by: java.lang.NullPointerException: null
at org.neo4j.ogm.drivers.embedded.driver.EmbeddedDriver.nativeTransaction(EmbeddedDriver.java:180) ~[neo4j-ogm-embedded-driver-2.0.4.jar:na]
at org.neo4j.ogm.drivers.embedded.driver.EmbeddedDriver.newTransaction(EmbeddedDriver.java:148) ~[neo4j-ogm-embedded-driver-2.0.4.jar:na]
at org.neo4j.ogm.session.transaction.DefaultTransactionManager.openTransaction(DefaultTransactionManager.java:57) ~[neo4j-ogm-core-2.0.4.jar:na]
at org.neo4j.ogm.session.delegates.TransactionsDelegate.beginTransaction(TransactionsDelegate.java:37) ~[neo4j-ogm-core-2.0.4.jar:na]
at org.neo4j.ogm.session.Neo4jSession.beginTransaction(Neo4jSession.java:441) ~[neo4j-ogm-core-2.0.4.jar:na]
at org.neo4j.ogm.session.request.RequestExecutor.executeSave(RequestExecutor.java:84) ~[neo4j-ogm-core-2.0.4.jar:na]
at org.neo4j.ogm.session.delegates.SaveDelegate.save(SaveDelegate.java:75) ~[neo4j-ogm-core-2.0.4.jar:na]
at org.neo4j.ogm.session.delegates.SaveDelegate.save(SaveDelegate.java:44) ~[neo4j-ogm-core-2.0.4.jar:na]
at org.neo4j.ogm.session.Neo4jSession.save(Neo4jSession.java:425) ~[neo4j-ogm-core-2.0.4.jar:na]
Can someone please tell me what I'm doing wrong??
Note : I had this working earlier with sdn.3.x with GraphDatabaseService
Looks like the only thing missing is the #Configuration annotation on your Neo4jConfiguration class:
#org.springframework.context.annotation.Configuration
#EnableTransactionManagement
#EnableNeo4jRepositories(basePackages = "com.seyfert.matrix.graph.repository")
public class DBConfig extends Neo4jConfiguration{
...
There are are many questions of same type, but none works for me.
I have Spring MVC hibernate application.
Here are my two model classes
Config.java
public class Config implements java.io.Serializable {
private Integer configId;
private String configName;
private Set<ConfigFields> ConfigFieldses = new HashSet<ConfigFields>(0);
//getters and setters
#OneToMany(cascade=CascadeType.ALL, fetch=FetchType.EAGER, mappedBy="configuration")
public Set<ConfigFields> getConfigFieldses() {
return this.ConfigFieldses;
}
public void setConfigFieldses(Set<ConfigFields> ConfigFieldses) {
this.ConfigFieldses = ConfigFieldses;
}
}
ConfigFields.java
public class ConfigFields implements java.io.Serializable {
private Integer configFieldId;
private Confign config;
private String configFieldName;
//getteres and setters
#XmlTransient
#ManyToOne(fetch=FetchType.LAZY)
#JoinColumn(name="ConfigId")
public Config getConfig() {
return this.config;
}
public void setConfig(Config configu) {
this.config = config;
}
}
Here is GenericHibernateDao.java
#Repository
#Transactional
public class GenericHibernateDao<T extends Serializable>
implements GenericDao<T>{
#Resource
protected SessionFactory sessionFactory;
#Override
public void insert(T transientInstance) {
sessionFactory.getCurrentSession().persist(transientInstance);
}
#Override
public void update(T instance) {
sessionFactory.getCurrentSession().saveOrUpdate(instance);
}
#Override
public void delete(T persistentInstance) {
sessionFactory.getCurrentSession().delete(persistentInstance);
}
#SuppressWarnings("unchecked")
#Override
public T merge(Serializable detachedInstance) {
return (T) sessionFactory.getCurrentSession().merge(detachedInstance);
}
#SuppressWarnings("unchecked")
#Override
public T findById(Class<?> clazz, Serializable id) {
T t= (T) sessionFactory.openSession().get(clazz, id);
return t;
}
#SuppressWarnings("unchecked")
public List<T> findByNamedQuery(Class<T> clazz, String queryName, Map<String, Object> queryParams) {
Query namedQuery = sessionFactory.getCurrentSession().getNamedQuery(queryName);
for (String s : queryParams.keySet()) {
namedQuery.setParameter(s, queryParams.get(s));
}
return namedQuery.list();
}
}
In my controller I have this method
#RequestMapping(value = "/deleteConfig/{configId}", method = RequestMethod.POST)
#ResponseBody
#Transactional
public String deleteConfiguration(#PathVariable Integer configId, HttpServletResponse response) throws IOException {
try {
Config config=configService.findById(configId);
logger.info("Deleting configuration...");
configService.delete(config);
} catch(Exception e) {
logger.debug(e.getMessage());
response.sendError(HttpServletResponse.SC_BAD_REQUEST);
}
return "success";
}
My test case
#RunWith(SpringJUnit4ClassRunner.class)
#WebAppConfiguration("classpath:webapptest")
#ContextConfiguration(locations = {"classpath:test-applicationcontext.xml"})
public class ConfigurationsControllerTest {
private MockMvc springMvc;
#Autowired
WebApplicationContext wContext;
#Before
public void init() throws Exception {
springMvc = MockMvcBuilders.webAppContextSetup(wContext).build();
}
#Test
public void deleteConfiguration() throws Exception {
ResultActions resultActions=springMvc.perform(MockMvcRequestBuilders.post("/deleteConfig/117").accept(MediaType.APPLICATION_JSON));
resultActions.andDo(MockMvcResultHandlers.print());
resultActions.andExpect(MockMvcResultMatchers.status().isOk());
}
}
When I run the testcase in console, logger showing
Illegal attempt to associate a collection with two open sessions
And JUnit test case stacktrace is
org.springframework.web.util.NestedServletException: Request processing failed; nested exception is org.springframework.transaction.UnexpectedRollbackException: JTA transaction unexpectedly rolled back (maybe due to a timeout); nested exception is bitronix.tm.internal.BitronixRollbackException: transaction was marked as rollback only and has been rolled back
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:932)
at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:827)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:641)
at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:801)
at org.springframework.test.web.servlet.TestDispatcherServlet.service(TestDispatcherServlet.java:66)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:722)
at org.springframework.mock.web.MockFilterChain$ServletFilterProxy.doFilter(MockFilterChain.java:168)
In Config class, I have Set which is set to CASCADE ALL. SO I am able to insert set of configfields while inserting config too. But now I want to delete by passing config object. So it should delete 1 row from config table and few rows from configfields table based on configId.
What is wrong here? And how to solve without affecting application(I mean insert)
I am using JPA, Hibernate and Spring MVC. In the controller class all the methods works greatly. When I test them in the web browser the public String getModuleFormation(long id) method, that returns an object, and it gives me the following error:
org.hibernate.LazyInitializationException: could not initialize proxy - no Session
as a root cause, but yesterday I tried it, and it worked without problem in the localhost:45045/GestionModules/detail/xx URL.
What could cause this problem?
My detail.jsp:
<c:if test="${!empty detailModule}">
${detailModule.idModule}
${detailModule.libModule}
</c:if>
POJO Class + JPA :
#Entity
#Table(name="ModuleFormation")
public class ModuleFormation {
private long idModule;
private String libModule;
public ModuleFormation() {
// TODO Auto-generated constructor stub
}
public ModuleFormation(String libModule) {
this.libModule = libModule;
}
#Id
#GeneratedValue(strategy = GenerationType.AUTO, generator = "seqModule")
#SequenceGenerator(name="seqModule", sequenceName = "seqModuleFormation")
#Column(name="idModule")
public long getIdModule() {
return this.idModule;
}
public void setIdModule(long idModule) {
this.idModule = idModule;
}
#Column(name="libModule", nullable=false, length = 100)
public String getLibModule() {
return this.libModule;
}
public void setLibModule(String libModule) {
this.libModule = libModule;
}
}
DAO Class :
#Repository
public class ModuleFormationDAOImpl implements ModuleFormationDAO {
#Autowired
private SessionFactory sessionFactory;
public void ajouterModuleFormation(ModuleFormation module) {
sessionFactory.getCurrentSession().save(module);
}
public void supprimerModuleFormation(long idModule) {
ModuleFormation module = (ModuleFormation) sessionFactory.getCurrentSession().load(ModuleFormation.class, idModule);
if(module != null)
sessionFactory.getCurrentSession().delete(module);
}
public List<ModuleFormation> listModuleFormation() {
return sessionFactory.getCurrentSession().createQuery("from ModuleFormation")
.list();
}
public ModuleFormation getModuleFormation(long idModule) {
return (ModuleFormation) sessionFactory.getCurrentSession().load(ModuleFormation.class, idModule);
}
public void majModuleFormation(ModuleFormation module) {
sessionFactory.getCurrentSession().merge(module);
}
}
Service Class :
#Service
public class ModuleFormationServiceImpl implements ModuleFormationService {
#Autowired
private ModuleFormationDAO moduleDao;
#Transactional
public void ajouterModuleFormation(ModuleFormation module) {
moduleDao.ajouterModuleFormation(module);
}
#Transactional
public void supprimerModuleFormation(long idModule) {
moduleDao.supprimerModuleFormation(idModule);
}
#Transactional
public List<ModuleFormation> listModuleFormation() {
return moduleDao.listModuleFormation();
}
#Transactional
public ModuleFormation getModuleFormation(long idModule) {
return moduleDao.getModuleFormation(idModule);
}
#Transactional
public void majModuleFormation(ModuleFormation module) {
moduleDao.majModuleFormation(module);
}
}
Controller Class :
#Controller
public class ModuleFormationController {
#Autowired
private ModuleFormationService moduleService;
#RequestMapping("/module")
public String listModulesFormations(Map<String, Object> map) {
map.put("module", new ModuleFormation());
map.put("moduleList", moduleService.listModuleFormation());
return "module";
}
#RequestMapping(value = "/ajouter", method = RequestMethod.POST )
public String ajouterModuleFormation(#ModelAttribute("module")
ModuleFormation module,BindingResult result) {
moduleService.ajouterModuleFormation(module);
return "redirect:/module";
}
#RequestMapping(value = "/supprimer/{idModule}")
public String supprimerModuleFormation(#PathVariable("idModule")
long idModule) {
moduleService.supprimerModuleFormation(idModule);
return "redirect:/module";
}
#RequestMapping(value= "/detail/{idModule}")
public String getModuleFormation(#PathVariable("idModule")
long idModule,Map<String, Object> map) {
map.put("detailModule", moduleService.getModuleFormation(idModule));
return "/detail";
}
#RequestMapping(value= "/detail/modifier", method = RequestMethod.POST )
public String majModuleFormation(#ModelAttribute("detailModule")
ModuleFormation module, BindingResult result) {
moduleService.majModuleFormation(module);
return "detail/{idModule}";
}
}
The Javadoc on the Hibernate Session#load(Class, Serializable) method says:
Return the persistent instance of the given entity class with the given identifier,
assuming that the instance exists. This method might return a proxied instance that
is initialized on-demand, when a non-identifier method is accessed.
When you access a property on the object in your JSP the session which loaded the object has been closed.
Use Session#get(Class, Serializable) to ensure that you don't load a proxy.
Instead of sessionFactory.getCurrentSession().load(ModuleFormation.class, idModule), have you tried sessionFactory.getCurrentSession().get(ModuleFormation.class, idModule)?