Exception Thrown by CrudRepository save method - exception

I am using CrudRepository save method to persist Profile Object in my Spring boot project as below:
MyService2.java:
public Profile getProfile(String profileId, String email){
Profile profile = null;
MyClass myObj=new MyClass();
Profile profile = new Profile(profileId, email);
return myRepository.save(profile);;
}
MyService1.java:
public Profile getProfile(String profileId, String email){
try{
return myService2.getProfile(profileId,email);
}
catch(Exception e){
{
throw new MyCustomException(errorMessage, errorCode);
}
}
MyRepository.java
public interface MyRepository extends PagingAndSortingRepository<Profile, String> {
........
}
Profile.java:
#Entity
public class Profile extends BaseDomain {
#Id
private String id;
private String username;
public Profile() {
//this is no argument constructor
}
public Profile(final String id,final String email) {
this.id = id;
this.username= email;
}
//Getter and Setter
}
In Profile object profileId is primaryKey and unique constraint is applied email field in Database table.
getProfile method is getting called from another Service MyService1 class and that service class method is being called from controller.
Now Issue what i am facing is even if i am passing a emailId in the method which is already available in the Database, profile object is being created and no exception is being caught in MyService1. Constraint violation Exception is only being caught in Controller where we are using created profile object further.
Exception message in controller is as follows:
org.springframework.dao.DataIntegrityViolationException: could not execute statement; SQL [n/a]; constraint [null]; nested exception is org.hibernate.exception.ConstraintViolationException: could not execute statement
StackTrace is as below:
org.springframework.orm.jpa.vendor.HibernateJpaDialect.convertHibernateAccessException(HibernateJpaDialect.java:278), org.springframework.orm.jpa.vendor.HibernateJpaDialect.translateExceptionIfPossible(HibernateJpaDialect.java:244), org.springframework.orm.jpa.JpaTransactionManager.doCommit(JpaTransactionManager.java:521), org.springframework.transaction.support.AbstractPlatformTransactionManager.processCommit(AbstractPlatformTransactionManager.java:761), org.springframework.transaction.support.AbstractPlatformTransactionManager.commit(AbstractPlatformTransactionManager.java:730), org.springframework.transaction.interceptor.TransactionAspectSupport.commitTransactionAfterReturning(TransactionAspectSupport.java:483), org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:290), org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:96), org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179), org.springframework.aop.interceptor.ExposeInvocationInterceptor.invoke(ExposeInvocationInterceptor.java:92), org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179), org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:213), com.sun.proxy.$Proxy147.createProfile(Unknown Source), com.cp.controllers.api.MyController.createAccount(MyController.java:827), com.cp.controllers.api.MyController$$FastClassBySpringCGLIB$$5cafd35f.invoke(), org.springframework.cglib.proxy.MethodProxy.invoke(MethodProxy.java:204), org.springframework.aop.framework.CglibAopProxy$CglibMethodInvocation.invokeJoinpoint(CglibAopProxy.java:720), org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:157), org.springframework.aop.aspectj.AspectJAfterThrowingAdvice.invoke(AspectJAfterThrowingAdvice.java:62), org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179), org.springframework.aop.aspectj.AspectJAfterThrowingAdvice.invoke(AspectJAfterThrowingAdvice.java:62), org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179), org.springframework.aop.interceptor.ExposeInvocationInterceptor.invoke(ExposeInvocationInterceptor.java:92), org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179), org.springframework.aop.framework.CglibAopProxy$DynamicAdvisedInterceptor.intercept(CglibAopProxy.java:655), com.cp.controllers.api.MyController$$EnhancerBySpringCGLIB$$1e2efb29.createAccount(), sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method), sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62), sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43), java.lang.reflect.Method.invoke(Method.java:498), org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:221), org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:136), org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:114), org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:827), org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:738), org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:85), org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:963), org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:897), org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:970), org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:872), javax.servlet.http.HttpServlet.service(HttpServlet.java:648), org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:846), javax.servlet.http.HttpServlet.service(HttpServlet.java:729), org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:230), org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:165), org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52), org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:192), org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:165), org.springframework.security.web.FilterChainProxy.doFilterInternal(FilterChainProxy.java:208), org.springframework.security.web.FilterChainProxy.doFilter(FilterChainProxy.java:177), org.springframework.web.filter.DelegatingFilterProxy.invokeDelegate(DelegatingFilterProxy.java:346), org.springframework.web.filter.DelegatingFilterProxy.doFilter(DelegatingFilterProxy.java:262), org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:192), org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:165), org.springframework.web.filter.RequestContextFilter.doFilterInternal(RequestContextFilter.java:99), org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107), org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:192), org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:165), org.springframework.web.filter.HttpPutFormContentFilter.doFilterInternal(HttpPutFormContentFilter.java:87), org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107), org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:192), org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:165), org.springframework.web.filter.HiddenHttpMethodFilter.doFilterInternal(HiddenHttpMethodFilter.java:77), org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107), org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:192), org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:165), org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:197), org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107), org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:192), org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:165), org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:198), org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:108), org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:522), org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:140), org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:79), org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:87), org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:349), org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:1110), org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:66), org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:785), org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1425), org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49), java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142), java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617), org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61), java.lang.Thread.run(Thread.java:745)
When i pass profileId as null in getProfile method, then Exception is successfully being caught in MyService1 catch block.
Can anybody please explain me this behavior of CrudRepository Save method.
Thanks

Related

JPA JSON column access via Jackson Eclipselink & Mysql

I'm trying to use a JPA entity to access a JSON column in mysql with my current eclipse link provider:
<provider>org.eclipse.persistence.jpa.PersistenceProvider</provider>
I am aware of this but I do not believe I am using hibernate.
How to map a MySQL JSON column to a Java entity property using JPA and Hibernate
This is the error i'm getting:
Exception [EclipseLink-30005] (Eclipse Persistence Services - 2.5.2.v20140319-9ad6abd): org.eclipse.persistence.exceptions.PersistenceUnitLoadingException
Exception Description: An exception was thrown while searching for persistence archives with ClassLoader: sun.misc.Launcher$AppClassLoader#659e0bfd
Internal Exception: javax.persistence.PersistenceException: Exception [EclipseLink-28018] (Eclipse Persistence Services - 2.5.2.v20140319-9ad6abd): org.eclipse.persistence.exceptions.EntityManagerSetupException
Exception Description: Predeployment of PersistenceUnit [IntellectPU] failed.
Internal Exception: Exception [EclipseLink-7347] (Eclipse Persistence Services - 2.5.2.v20140319-9ad6abd): org.eclipse.persistence.exceptions.ValidationException
Exception Description: The class [filtec.db.TestCriteria] specifies type level convert metadata without specifying an attribute name for each. An attribute name must be provided for all type level convert metadata to ensure the correct application to a super class attribute.
at org.eclipse.persistence.exceptions.PersistenceUnitLoadingException.exceptionSearchingForPersistenceResources(PersistenceUnitLoadingException.java:127)
at org.eclipse.persistence.jpa.PersistenceProvider.createEntityManagerFactoryImpl(PersistenceProvider.java:107)
at org.eclipse.persistence.jpa.PersistenceProvider.createEntityManagerFactory(PersistenceProvider.java:177)
at javax.persistence.Persistence.createEntityManagerFactory(Persistence.java:79)
at javax.persistence.Persistence.createEntityManagerFactory(Persistence.java:54)
at filtec.db.EM.getEntityManager(EM.java:50)
This is my entity class:
#Entity
#Table(name = "TestCriteria")
#Convert(converter=JpaConverterJson.class)
public class TestCriteria implements Serializable {
/** Auto generated Serial ID by Eclipse */
private static final long serialVersionUID = 3680147569249120166L;
/** TRACE log. */
protected static final Logger TRACE = Logger.getLogger(TestCriteria.class.getName());
/** The container type ID. */
#Id
#Column(name="ContainerTypeId", unique=true)
private int containerTypeId;
/** The JSON document containing the sample criteria array. */
#Column(name="SampleCriteriaMap")
#Convert(converter = JpaConverterJson.class)
private Map<String, Object> sampleCriteriaMap;
and my converter class:
#Converter
public class JpaConverterJson implements AttributeConverter<Object, String> {
/** TRACE log. */
protected static final Logger TRACE = Logger.getLogger(JpaConverterJson.class.getName());
/** single instance as we don't expect much multi-threading. */
private final static ObjectMapper OBJECT_MAPPER = new ObjectMapper();
#Override
public String convertToDatabaseColumn(Object meta) {
try {
return OBJECT_MAPPER.writeValueAsString(meta);
} catch (JsonProcessingException ex) {
return null;
// or throw an error
}
}
#Override
public Object convertToEntityAttribute(String dbData) {
try {
return OBJECT_MAPPER.readValue(dbData, Object.class);
} catch (IOException ex) {
TRACE.severe("Unexpected IOEx decoding json from database: " + dbData);
return null;
}
}
}
Can anyone advise on what I've not configured correctly?

springboot server returns error 400 after post request using postman

whenever I try to send this over postman:
{
"date": "2021-11-05 12:32:32",
"start": "start",
"destination": "destination",
"provider": "provider",
"driver":1,
"vehicule":1
}
i get an error 400, bad request, i'm using both the #restController and #requestBody annotations while also setting the content type to json.
i get this error on the debugger:
2021-11-09 16:57:52.086 WARN 11748 --- [nio-8080-exec-1] .w.s.m.s.DefaultHandlerExceptionResolver : Resolved [org.springframework.http.converter.HttpMessageNotReadableException: JSON parse error: Cannot deserialize value of type `java.util.Date` from String "2021-11-06 12:32:32.0": not a valid representation (error: Failed to parse Date value '2021-11-06 12:32:32.0': Cannot parse date "2021-11-06 12:32:32.0": while it seems to fit format 'yyyy-MM-dd'T'HH:mm:ss.SSSX', parsing fails (leniency? null)); nested exception is com.fasterxml.jackson.databind.exc.InvalidFormatException: Cannot deserialize value of type `java.util.Date` from String "2021-11-06 12:32:32.0": not a valid representation (error: Failed to parse Date value '2021-11-06 12:32:32.0': Cannot parse date "2021-11-06 12:32:32.0": while it seems to fit format 'yyyy-MM-dd'T'HH:mm:ss.SSSX', parsing fails (leniency? null))
at [Source: (PushbackInputStream); line: 3, column: 17] (through reference chain: com.siam.HRAssistTool.Entity.Schedule["date"])]
I don't understand how i should fix this what i assume date format related issue
when I remove the time from the json body and only leave the date, I get this error:
2021-11-09 17:34:55.418 WARN 11748 --- [nio-8080-exec-4] .w.s.m.s.DefaultHandlerExceptionResolver : Resolved [org.springframework.http.converter.HttpMessageNotReadableException: JSON parse error: Cannot construct instance of `com.siam.HRAssistTool.Entity.Vehicule` (although at least one Creator exists): no int/Int-argument constructor/factory method to deserialize from Number value (1); nested exception is com.fasterxml.jackson.databind.exc.MismatchedInputException: Cannot construct instance of `com.siam.HRAssistTool.Entity.Vehicule` (although at least one Creator exists): no int/Int-argument constructor/factory method to deserialize from Number value (1)
at [Source: (PushbackInputStream); line: 8, column: 20] (through reference chain: com.siam.HRAssistTool.Entity.Schedule["vehicule"])]
my schedule entity:
#Entity
public class Schedule implements Serializable {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id ;
private Date date ;
private String Start;
private String destination;
#OneToOne( fetch = FetchType.LAZY)
private Staff driver;
#OneToOne(fetch = FetchType.LAZY)
private Vehicule vehicule;
private String provider;
//constructors, getters and setters
}
my controller :
#RestController
public class ScheduleController {
#Autowired
ScheduleService scheduleService;
#PostMapping(value="/schedule/create")
public #ResponseBody String createSchedule( #RequestBody Schedule schedule) {
System.out.println(schedule.toString());
return scheduleService.addSchedule(schedule);
}
//other crud operation
}
First of all, replace Date with LocalDate, which is part of the new Java Time API. with this you can configure Jackson to handle serialization and deserialization of such a complex type easily. Add the following dependency:
<dependency>
<groupId>com.fasterxml.jackson.datatype</groupId>
<artifactId>jackson-datatype-jsr310</artifactId>
<version>2.11.0</version>
</dependency>
And then configure Jackson accordingly:
#Configuration
public class JacksonConfiguration {
#Bean
public ObjectMapper objectMapper() {
ObjectMapper objectMapper = new ObjectMapper();
JavaTimeModule javaTimeModule = new JavaTimeModule();
objectMapper.registerModule(javaTimeModule);
objectMapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false);
return objectMapper;
}
}
Then, please avoid using Entities in your Controller, either as a response or request type. Instead, use DTOs which are specific representations for your core model Entities.
public class ScheduleCreationDto {
private LocalDate date;
private String Start;
private String destination;
private Long driverId; // I am guessing the ID is a Long
private Long vehiculeId; // I am guessing the ID is a Long
private String provider;
//constructors, getters and setters
}
This should now be used as the request body:
#RestController
public class ScheduleController {
#Autowired
ScheduleService scheduleService;
#PostMapping(value="/schedule/create")
public #ResponseBody String createSchedule(#RequestBody ScheduleCreationDto scheduleCreationDto) {
return scheduleService.addSchedule(schedule);
}
//other crud operation
}
You also need to change ScheduleService so that it creates a Schedule based on ScheduleCreationDto. Most of the properties require a simple mapping, but others (driverId and vehiculeId) requires you to actually get those Entities from the Database using the provided ID. Something similar to the following should be done in your ScheduleService:
#Service
public class ScheduleService {
#Autowired
ScheduleRepository scheduleRepository;
#Autowired
DriverRepository driverRepository;
#Autowired
VehiculeRepository vehiculeRepository;
public String addSchedule(ScheduleCreationDto scheduleCreationDto) {
Optional<Driver> driver = driverRepository.findById(scheduleCreationDto.getDriverId());
Optional<Vehicule> vehicule = vehiculeRepository.findById(scheduleCreationDto.getVehiculeId());
if (driver.isPresent() && vehicule.isPresent()) {
Schedule schedule = new Schedule(scheduleCreationDto.getDate(), scheduleCreationDto.getStart(),
scheduleCreationDto.getDestination(), driver.get(), vehicule.get(), scheduleCreationDto.getProvider());
scheduleRepository.save(schedule);
}
return // whatever String you want to return, you should actually return the created Schedule, but that is a different topic
}
//other crud operation
}
400 error bad request with postman and Spring Boot API, in my case, happend for three reasons:
1.The first, is that the json format for the request is wrong, like sending:
{ key: value }
Or:
{ "key" : "value"
This is clarely not you case.
2.The second cause was sending the keys different from what the object was expecting.For example:
#PostMapping
public ResponseEntity<Object> save(#RequestResponse #Valid
ClassOfReciveObject reciveObject){
return ResponseEntity.status(HttpStatus.CREATED).body("OK");
}
If the ClassOfObjectRecived has properties :
{
public String age;
public String name;
}
And you are sending in postman others keys, you will get a bad Request
{
"country":"Brazil",
"Continent":"America"
}
3.The third case i got this error was because of the private access modifier for the atributes of this class, change it for public, or find ways to resolve it
public class ClassOfObjectRecived {
public String param1;
public String param2;
}

org.springframework.beans.factory.BeanCreationException: Error creating bean with name '': Bean instantiation via constructor failed;

i'm trying using mysql,spring and vaadin.
the app should access to the db and show the table on the index page
in the code i have the interface repository extending jparepository,
the service :
public class UtenteService {
private UtenteRepository utenterep;
public UtenteService(UtenteRepository utenterepository){
this.utenterep=utenterepository;
}
public List<Utente> findAll(){
return this.utenterep.findAll();
}
public void save(Utente u){
if(u==null){
return;
}
utenterep.save(u);
}
}
and the view where i call the service :
public class HelloView extends HorizontalLayout implements AfterNavigationObserver {
#Autowired
private UtenteService utenteService;
private TextField name;
private Button sayHello;
private Grid<Utente> utenti = new Grid<>(Utente.class);
private Binder<Utente> binder;
public HelloView(UtenteService utenteService1) {
this.utenteService=utenteService1;
HorizontalLayout hor = new HorizontalLayout();
setId("hello-view");
name = new TextField("Your name");
sayHello = new Button("Say hello");
setVerticalComponentAlignment(Alignment.END, name, sayHello);
sayHello.addClickListener( e-> {
Notification.show("Hello " + name.getValue());
});
hor.add(name, sayHello);
add(hor);
configureGrid();
hor.add(utenti);
updategrid();
}
private void updategrid() {
// TODO Auto-generated method stub
utenti.setItems(utenteService.findAll());
}
private void configureGrid() {
utenti.setSizeFull();
utenti.setColumns("id","nome","password","id_ruolo");
binder = new Binder<>(Utente.class);
binder.bindInstanceFields(this);
binder.setBean(new Utente());
}
#Override
public void afterNavigation(AfterNavigationEvent event) {
// TODO Auto-generated method stub
utenti.setItems(utenteService.findAll());
}
ERROR
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'it.tirocinio.application.views.hello.HelloView': Bean instantiation via constructor failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [it.tirocinio.application.views.hello.HelloView]: Constructor threw exception; nested exception is java.lang.IllegalStateException: There are no instance fields found for automatic binding
Usually the last error is the root cause, there should be a stack trace that shows where the error occurred.
Looking at the last error in the text you posted, you see java.lang.IllegalStateException: There are no instance fields found for automatic binding.
So the error is likely because you are calling bindInstanceFields(this), but there are no matching fields. Your entity Utente has a field nome, but in HelloView it's called name.

Mockito: how to verify method was called inside another method, which always throws Exception?

I am testing a method with an expected exception.
I also need to verify that some code was called (on a mocked object) after the exception is thrown, but verification is being ignored.
Here is the code:
public class ExceptionHandler {
#Autowired
private Sender sender;
public void handle(Exception exception) throws Exception {
if (!SomeException.class.isAssignableFrom(exception.getClass())) {
sender.sendMessage(ExceptionUtils.getStackTrace(exception));
}
throw exception;
}
}
Here is the test code:
#Mock
private Sender sender;
#InjectMocks
private ExceptionHandler handler;
#Test
public void testHandler() throws Exception {
SomeException someException = new SomeException();
try {
handler.handle(someException);
} catch (SomeException thrownResult) {
assertEquals(someException, thrownResult);
}
verify(sender, times(1)).sendMessage(Mockito.anyString());
}
I also need to verify that some code was called (on a mocked object)
after the exception is thrown, but verification is being ignored.
This is not true, this line is actually executed:
verify(sender, times(1)).sendMessage(Mockito.anyString());
But it fails verification with this error:
Wanted but not invoked: sender.sendMessage();
<...>
Actually, there were zero interactions with this mock.
As expected, that method was never invoked, because condition !SomeException.class.isAssignableFrom(exception.getClass()) was not satisfied - you invoke handler.handle with instance of SomeException.

#ManagedBean issues getting relational data

I have this weird problem that throws not really useful errors. I'm trying to display data from Entity Bean in Primefaces table. I have two projects, one for front end, other one for backend. Thing is, the Entity Bean has #OneToMany and #ManyToOne relation, and they seem to cause the problems, because if I null them no errors happen, but I need that data so it's not a solution.
BACKEND:
Key parts of entity:
#Entity
#Table(name = "business_process_tasks")
public class BusinessProcessTasks implements java.io.Serializable {
....
#ManyToOne(fetch=FetchType.EAGER)
#JoinColumn(name="process")
public Process getProcess() {
return process;
}
public void setProcess(Process process) {
this.process = process;
}
#OneToMany(mappedBy = "processTask")
public List<BusinessProcessTasksMeta> getMeta() {
return meta;
}
public void setMeta(List<BusinessProcessTasksMeta> meta) {
this.meta = meta;
}
}
Key parts of EJB:
#Override
public List<BusinessProcessTasks> getList(int processId) {
EntityManager em = emf.createEntityManager();
String q = "SELECT t from " + BusinessProcessTasks.class.getName() + " t where process="+processId;
Query query = em.createQuery(q);
List<BusinessProcessTasks> items = query.getResultList();
for(int i = 0;i<items.size();i++){
BusinessProcessTasks t = (BusinessProcessTasks) items.get(i);
//IF I SET THESE TO NULL NO ERRORS SHOW
t.setProcess(null);
t.setMeta(null);
}
em.close();
return items;
}
FRONTEND:
Key parts of #ManagedBean:
#ManagedBean(name = "processTasksTableBean")
#ViewScoped
public class ProcessTasksTableBean {
.....
#PostConstruct
void initialiseSession() {
System.out.println("Bean running");
FacesContext.getCurrentInstance().getExternalContext().getSession(true);
//GETTING ID FROM URL
HttpServletRequest request = (HttpServletRequest) FacesContext
.getCurrentInstance().getExternalContext().getRequest();
pageProcessId = Integer.parseInt(request.getParameter("id"));
processTasksBeanRemote = doLookup();
//ONLY PLACE IN PROJECT WHERE ERROR IS REFERENCED IN CONSOLE IS HERE
processTasksList = processTasksBeanRemote.getList(pageProcessId);
}
.....
}
Eclipse console - log is very long, if required I will post it all, now just key parts:
09:34:58,377 SEVERE [javax.enterprise.resource.webcontainer.jsf.application] (http-localhost-127.0.0.1-8189-3) Error Rendering View[/ProcessTasks.xhtml]: java.lang.IllegalStateException: JBAS011048: Failed to construct component instance
Caused by: java.lang.RuntimeException: ClassNotFoundException marshaling EJB parameters
Caused by: java.lang.ClassNotFoundException: org.hibernate.collection.internal.PersistentBag from [Module "deployment.bpmweb.war:main" from Service Module Loader]
09:34:58,403 ERROR [org.apache.catalina.core.ContainerBase.[jboss.web].[default-host].[/bpmweb].[Faces Servlet]] (http-localhost-127.0.0.1-8189-3) Servlet.service() for servlet Faces Servlet threw exception: java.lang.ClassNotFoundException: org.hibernate.collection.internal.PersistentBag from [Module "deployment.bpmweb.war:main" from Service Module Loader]
Issue resolved, I downloaded latest Hibernate core from http://mvnrepository.com/artifact/org.hibernate/hibernate-core/4.3.4.Final and all seems fine. Quite wierd, since I add my Jboss runtime libs to each project through build path.