Spring cannot bind DAOImpl class java.lang.NullPointerException - spring-mvc

I have my service endpoint invoking get() method on my DAO, but fails with java.lang.NullPointerException. while debuging it seems Spring cannot find the implementation of my DAO
ContactEndoint
package com.spring.contacts;
#Endpoint
#Configuration
#ComponentScan(basePackages="com.spring.contacts")
#EnableWebMvc
public class ContactEndpoint {
private static final String NAMESPACE_URI = "http://spring.io/guides/gs-producing-web-service";
#Autowired
private ContactDAO contactDAO;
//Default constructor
public ContactEndpoint(){
}
#Autowired
public ContactEndpoint(ContactDAO contactDAO) {
this.contactDAO = contactDAO;
}
#Cacheable(cacheName="imageCache", keyGenerator=#KeyGenerator(name="StringKeyCache"))
#PayloadRoot(namespace = NAMESPACE_URI, localPart = "getContactRequest")
#RequestMapping(value = "/editContact", method = RequestMethod.GET)
#ResponsePayload
public GetContactResponse getContact(#RequestPayload GetContactRequest request){
GetContactResponse response = new GetContactResponse();
response.setContact(contactDAO.get(request.getId()));
return response;
}
ContactDAO
package com.spring.contacts.dao;
public interface ContactDAO {
public Contact get(int contactId);
ContactDAOImpl
package com.spring.contacts.dao;
#Repository("contactDAO")
public class ContactDAOImpl implements ContactDAO {
private JdbcTemplate jdbcTemplate;
//default constructor
public ContactDAOImpl(){
}
public ContactDAOImpl(DataSource dataSource) {
jdbcTemplate = new JdbcTemplate(dataSource);
}
#Override
public Contact get(int contactId) {
String sql = "SELECT * FROM contact WHERE contact_id=" + contactId;
return jdbcTemplate.query(sql, new ResultSetExtractor<Contact>() {
#Override
public Contact extractData(ResultSet rs) throws SQLException,
DataAccessException {
if (rs.next()) {
Contact contact = new Contact();
contact.setId(rs.getInt("contact_id"));
contact.setName(rs.getString("name"));
contact.setEmail(rs.getString("email"));
contact.setAdress(rs.getString("address"));
contact.setTelephone(rs.getString("telephone"));
return contact;
}
return null;
}
});
}
WebServiceConfig
package com.spring.contacts;
#EnableWs
#Configuration
#ComponentScan("com.spring")
public class WebServiceConfig extends WsConfigurerAdapter {
#Bean
public ServletRegistrationBean messageDispatcherServlet(ApplicationContext applicationContext) {
MessageDispatcherServlet servlet = new MessageDispatcherServlet();
servlet.setApplicationContext(applicationContext);
servlet.setTransformWsdlLocations(true);
return new ServletRegistrationBean(servlet, "/ws/*");
}
#Bean(name = "countries")
public DefaultWsdl11Definition defaultWsdl11Definition(XsdSchema countriesSchema) {
DefaultWsdl11Definition wsdl11Definition = new DefaultWsdl11Definition();
wsdl11Definition.setPortTypeName("CountriesPort");
wsdl11Definition.setLocationUri("/ws");
wsdl11Definition.setTargetNamespace("http://spring.io/guides/gs-producing-web-service");
wsdl11Definition.setSchema(countriesSchema);
return wsdl11Definition;
}
#Bean(name = "contacts")
public DefaultWsdl11Definition defaultContactsWsdl11Definition(XsdSchema contactsSchema){
DefaultWsdl11Definition wsdl11Definition = new DefaultWsdl11Definition();
wsdl11Definition.setPortTypeName("ContactsPort");
wsdl11Definition.setLocationUri("/ws/JDBC");
wsdl11Definition.setTargetNamespace("http://spring.io/guides/gs-producing-web-service");
wsdl11Definition.setSchema(contactsSchema);
return wsdl11Definition;
}
#Bean
public XsdSchema countriesSchema() {
return new SimpleXsdSchema(new ClassPathResource("countries/countries.xsd"));
}
#Bean
public XsdSchema contactsSchema(){
return new SimpleXsdSchema(new ClassPathResource("contacts/contact.xsd"));
}
StackTrace
java.lang.NullPointerException: null
at com.spring.contacts.dao.ContactDAOImpl.get(ContactDAOImpl.java:85) ~[ContactDAOImpl.class:na]
at com.spring.contacts.dao.ContactDAOImpl$$FastClassBySpringCGLIB$$f0feb335.invoke(<generated>) ~[spring-core-4.1.6.RELEASE.jar:na]
at org.springframework.cglib.proxy.MethodProxy.invoke(MethodProxy.java:204) ~[spring-core-4.1.6.RELEASE.jar:4.1.6.RELEASE]
at org.springframework.aop.framework.CglibAopProxy$CglibMethodInvocation.invokeJoinpoint(CglibAopProxy.java:717) ~[spring-aop-4.1.6.RELEASE.jar:4.1.6.RELEASE]
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:157) ~[spring-aop-4.1.6.RELEASE.jar:4.1.6.RELEASE]
at org.springframework.dao.support.PersistenceExceptionTranslationInterceptor.invoke(PersistenceExceptionTranslationInterceptor.java:136) ~[spring-tx-4.1.6.RELEASE.jar:4.1.6.RELEASE]
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179) ~[spring-aop-4.1.6.RELEASE.jar:4.1.6.RELEASE]
at org.springframework.aop.framework.CglibAopProxy$DynamicAdvisedInterceptor.intercept(CglibAopProxy.java:653) ~[spring-aop-4.1.6.RELEASE.jar:4.1.6.RELEASE]
at com.spring.contacts.dao.ContactDAOImpl$$EnhancerBySpringCGLIB$$5f3048d3.get(<generated>) ~[spring-core-4.1.6.RELEASE.jar:na]
at com.spring.contacts.ContactEndpoint.getContact(ContactEndpoint.java:45) ~[ContactEndpoint.class:na]
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:1.7.0_25]
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57) ~[na:1.7.0_25]
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:1.7.0_25]
at java.lang.reflect.Method.invoke(Method.java:606) ~[na:1.7.0_25]
at org.springframework.ws.server.endpoint.MethodEndpoint.invoke(MethodEndpoint.java:134) ~[spring-ws-core-2.2.1.RELEASE.jar:2.2.1.RELEASE]
at org.springframework.ws.server.endpoint.adapter.DefaultMethodEndpointAdapter.invokeInternal(DefaultMethodEndpointAdapter.java:291) ~[spring-ws-core-2.2.1.RELEASE.jar:2.2.1.RELEASE]
at org.springframework.ws.server.endpoint.adapter.AbstractMethodEndpointAdapter.invoke(AbstractMethodEndpointAdapter.java:55) ~[spring-ws-core-2.2.1.RELEASE.jar:2.2.1.RELEASE]
at org.springframework.ws.server.MessageDispatcher.dispatch(MessageDispatcher.java:236) [spring-ws-core-2.2.1.RELEASE.jar:2.2.1.RELEASE]
at org.springframework.ws.server.MessageDispatcher.receive(MessageDispatcher.java:176) [spring-ws-core-2.2.1.RELEASE.jar:2.2.1.RELEASE]
at org.springframework.ws.transport.support.WebServiceMessageReceiverObjectSupport.handleConnection(WebServiceMessageReceiverObjectSupport.java:89) ~[spring-ws-core-2.2.1.RELEASE.jar:2.2.1.RELEASE]
at org.springframework.ws.transport.http.WebServiceMessageReceiverHandlerAdapter.handle(WebServiceMessageReceiverHandlerAdapter.java:61) ~[spring-ws-core-2.2.1.RELEASE.jar:2.2.1.RELEASE]
at org.springframework.ws.transport.http.MessageDispatcherServlet.doService(MessageDispatcherServlet.java:293) ~[spring-ws-core-2.2.1.RELEASE.jar:2.2.1.RELEASE]
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:966) ~[spring-webmvc-4.1.6.RELEASE.jar:4.1.6.RELEASE]
at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:868) ~[spring-webmvc-4.1.6.RELEASE.jar:4.1.6.RELEASE]
at javax.servlet.http.HttpServlet.service(HttpServlet.java:648) ~[servlet-api.jar:na]
at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:842) ~[spring-webmvc-4.1.6.RELEASE.jar:4.1.6.RELEASE]
at javax.servlet.http.HttpServlet.service(HttpServlet.java:729) ~[servlet-api.jar:na]
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:291) ~[catalina.jar:8.0.21]
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206) ~[catalina.jar:8.0.21]
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52) ~[tomcat-websocket.jar:8.0.21]
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:239) ~[catalina.jar:8.0.21]
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206) ~[catalina.jar:8.0.21]
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:219) ~[catalina.jar:8.0.21]
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:106) ~[catalina.jar:8.0.21]
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:502) ~[catalina.jar:8.0.21]
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:142) ~[catalina.jar:8.0.21]
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:79) ~[catalina.jar:8.0.21]
at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:610) ~[catalina.jar:8.0.21]
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:88) ~[catalina.jar:8.0.21]
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:518) ~[catalina.jar:8.0.21]
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1091) ~[tomcat-coyote.jar:8.0.21]
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:668) ~[tomcat-coyote.jar:8.0.21]
at org.apache.coyote.http11.Http11NioProtocol$Http11ConnectionHandler.process(Http11NioProtocol.java:223) ~[tomcat-coyote.jar:8.0.21]
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1517) ~[tomcat-coyote.jar:8.0.21]
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.run(NioEndpoint.java:1474) ~[tomcat-coyote.jar:8.0.21]
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145) ~[na:1.7.0_25]
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615) ~[na:1.7.0_25]
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61) ~[tomcat-util.jar:8.0.21]
at java.lang.Thread.run(Thread.java:724) ~[na:1.7.0_25]

I fixed it by injecting datasource to DAOImpl using #Autowired
#Autowired
public ContactDAOImpl(DataSource dataSource) {
jdbcTemplate = new JdbcTemplate(dataSource);
}

Related

Thymeleaf templateResolver WebApplicationContext throw nullpointexception

When I use thymeleaf in SpringMVC,the ServletContext throw nullpointexception ,here my code and trace stack
#Configuration
public class ViewResolverConfig {
#Bean
public ITemplateResolver templateResolver() {
WebApplicationContext webApplicationContext = ContextLoader.getCurrentWebApplicationContext();
ServletContextTemplateResolver templateResolver = new ServletContextTemplateResolver(webApplicationContext.getServletContext());
templateResolver.setPrefix("/WEB-INF/templates/");
templateResolver.setSuffix(".html");
templateResolver.setCharacterEncoding("UTF-8");
templateResolver.setTemplateMode(TemplateMode.HTML);
return templateResolver;
}
#Bean
public SpringTemplateEngine templateEngine(ITemplateResolver templateResolver) {
SpringTemplateEngine templateEngine = new SpringTemplateEngine();
templateEngine.setTemplateResolver(templateResolver);
return templateEngine;
}
#Bean
public ViewResolver viewResolver(SpringTemplateEngine templateEngine) {
ThymeleafViewResolver viewResolver = new ThymeleafViewResolver();
viewResolver.setCharacterEncoding("UTF-8");
viewResolver.setTemplateEngine(templateEngine);
return viewResolver;
}}
here is the buttom error
Caused by: java.lang.NullPointerException: null
at com.lh.config.WebConfig.templateResolver(WebConfig.java:46)
at com.lh.config.WebConfig$$EnhancerBySpringCGLIB$$ede505eb.CGLIB$templateResolver$3()
at com.lh.config.WebConfig$$EnhancerBySpringCGLIB$$ede505eb$$FastClassBySpringCGLIB$$6ff8b31b.invoke()
at org.springframework.cglib.proxy.MethodProxy.invokeSuper(MethodProxy.java:244)
at org.springframework.context.annotation.ConfigurationClassEnhancer$BeanMethodInterceptor.intercept(ConfigurationClassEnhancer.java:331)
at com.lh.config.WebConfig$$EnhancerBySpringCGLIB$$ede505eb.templateResolver()
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:154)
... 63 common frames omitted
but I dont know why the WebApplicationContext is null

Unsupported Operation Exception Java.Sql.Date [duplicate]

This question already has an answer here:
Convert between LocalDate and sql.Date [duplicate]
(1 answer)
Closed 4 years ago.
hello i need to display a date column in a tableview; in the database I declare the field fecha_nacimiento as date , i used a datepicker to insert that data into the database, so far its Ok with that operation so the next step was formatting the tableview cell to display the date data correctly, with the help of this site i did that, but when i need to retrieve the date data from the database i am getting an error, something like this:
Caused by: java.lang.UnsupportedOperationException
at java.sql.Date.toInstant(Unknown Source)
this is some of my controller code
public void initialize(URL arg0, ResourceBundle arg1) {
clienteid.setCellValueFactory(new PropertyValueFactory <Persona, Integer>("id_cliente"));
nombrescol.setCellValueFactory(new PropertyValueFactory <Persona, String>("nombres"));
apellidoscol.setCellValueFactory(new PropertyValueFactory <Persona, String>("apellidos"));
//fechacli.setCellValueFactory(new PropertyValueFactory <Persona, LocalDate>("fechacliente"));//
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd/MM/yyyy");
fechacli.setCellFactory(column -> {
return new TableCell<Persona, LocalDate>() {
#Override
protected void updateItem(LocalDate item, boolean empty) {
super.updateItem(item, empty);
if (item == null || empty) {
setText(null);
} else {
setText(formatter.format(item));
}
}
};
});
seleccionaregistros();
seleccionanombre();
seleccionapellido();
}
public void seleccionaregistros() {
ObservableList <Persona> data =FXCollections.observableArrayList();
Connection conn=null;{
try {
conn = DriverManager.getConnection("jdbc:sqlserver://localhost:1433;databaseName=prueba", "sa", "milkas87");
Statement mostrar=conn.createStatement();
ResultSet rs;
rs= mostrar.executeQuery("select * from cliente");
while ( rs.next() )
{
data.add(new Persona(
rs.getString("nombre"),
rs.getString("apellido"),
rs.getInt("id"),
rs.getDate(4).toInstant().atZone(ZoneId.systemDefault()).toLocalDate())
);
tablacliente.setItems(data);
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}
this is my persona class code
package application;
import java.time.LocalDate;
import javafx.beans.property.IntegerProperty;
import javafx.beans.property.ObjectProperty;
import javafx.beans.property.SimpleIntegerProperty;
import javafx.beans.property.SimpleObjectProperty;
import javafx.beans.property.SimpleStringProperty;
import javafx.beans.property.StringProperty;
public class Persona {
private StringProperty nombres;
private StringProperty apellidos;
private IntegerProperty id_cliente;
private ObjectProperty <LocalDate>fechacliente;
public Persona (String nombres, String apellidos, Integer id_cliente, LocalDate fechacliente) {
this.nombres= new SimpleStringProperty (nombres);
this.apellidos= new SimpleStringProperty ( apellidos);
this.id_cliente=new SimpleIntegerProperty (id_cliente);
this.fechacliente= new SimpleObjectProperty<>(fechacliente);
}
public LocalDate getFechaCliente() {
return fechacliente.get();
}
public void setFechaCliente(LocalDate fechacliente) {
this.fechacliente = new SimpleObjectProperty<>(fechacliente);
}
public ObjectProperty<LocalDate> fechaClienteProperty() {
return fechacliente;
}
public String getNombres() {
return nombres.get();
}
public void setNombres(String nombres) {
this.nombres=new SimpleStringProperty (nombres);
}
public String getApellidos() {
return apellidos.get();
}
public void setApellidos(String apellidos) {
this.apellidos=new SimpleStringProperty ( apellidos);
}
public Integer getId_cliente() {
return id_cliente.get();
}
public void setid_cliente(Integer id_cliente) {
this.id_cliente=new SimpleIntegerProperty (id_cliente);
}
}
id have been reading, and i found that can't truncate or pass the data beetween Localdate and Date, so any help could be truly helpful. regards.
all the errors here:
javafx.fxml.LoadException:
/C:/Users/ROA%20PC/eclipse-workspace/Conexion/bin/application/Vista.fxml
at javafx.fxml.FXMLLoader.constructLoadException(FXMLLoader.java:2601)
at javafx.fxml.FXMLLoader.loadImpl(FXMLLoader.java:2579)
at javafx.fxml.FXMLLoader.loadImpl(FXMLLoader.java:2441)
at javafx.fxml.FXMLLoader.loadImpl(FXMLLoader.java:3214)
at javafx.fxml.FXMLLoader.loadImpl(FXMLLoader.java:3175)
at javafx.fxml.FXMLLoader.loadImpl(FXMLLoader.java:3148)
at javafx.fxml.FXMLLoader.loadImpl(FXMLLoader.java:3124)
at javafx.fxml.FXMLLoader.loadImpl(FXMLLoader.java:3104)
at javafx.fxml.FXMLLoader.load(FXMLLoader.java:3097)
at application.Main.start(Main.java:23)
at com.sun.javafx.application.LauncherImpl.lambda$launchApplication1$162(LauncherImpl.java:863)
at com.sun.javafx.application.PlatformImpl.lambda$runAndWait$175(PlatformImpl.java:326)
at com.sun.javafx.application.PlatformImpl.lambda$null$173(PlatformImpl.java:295)
at java.security.AccessController.doPrivileged(Native Method)
at com.sun.javafx.application.PlatformImpl.lambda$runLater$174(PlatformImpl.java:294)
at com.sun.glass.ui.InvokeLaterDispatcher$Future.run(InvokeLaterDispatcher.java:95)
at com.sun.glass.ui.win.WinApplication._runLoop(Native Method)
at com.sun.glass.ui.win.WinApplication.lambda$null$148(WinApplication.java:191)
at java.lang.Thread.run(Unknown Source)
Caused by: java.lang.UnsupportedOperationException
at java.sql.Date.toInstant(Unknown Source)
at application.ConexionController.seleccionaregistros(ConexionController.java:190)
at application.ConexionController.initialize(ConexionController.java:92)
at javafx.fxml.FXMLLoader.loadImpl(FXMLLoader.java:2548)
... 17 more
Exception in Application start method
java.lang.reflect.InvocationTargetException
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at com.sun.javafx.application.LauncherImpl.launchApplicationWithArgs(LauncherImpl.java:389)
at com.sun.javafx.application.LauncherImpl.launchApplication(LauncherImpl.java:328)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at sun.launcher.LauncherHelper$FXHelper.main(Unknown Source)
Caused by: java.lang.RuntimeException: Exception in Application start method
at com.sun.javafx.application.LauncherImpl.launchApplication1(LauncherImpl.java:917)
at com.sun.javafx.application.LauncherImpl.lambda$launchApplication$155(LauncherImpl.java:182)
at java.lang.Thread.run(Unknown Source)
Caused by: java.lang.NullPointerException: Root cannot be null
at javafx.scene.Scene.<init>(Scene.java:336)
at javafx.scene.Scene.<init>(Scene.java:235)
at application.Main.start(Main.java:27)
at com.sun.javafx.application.LauncherImpl.lambda$launchApplication1$162(LauncherImpl.java:863)
at com.sun.javafx.application.PlatformImpl.lambda$runAndWait$175(PlatformImpl.java:326)
at com.sun.javafx.application.PlatformImpl.lambda$null$173(PlatformImpl.java:295)
at java.security.AccessController.doPrivileged(Native Method)
at com.sun.javafx.application.PlatformImpl.lambda$runLater$174(PlatformImpl.java:294)
at com.sun.glass.ui.InvokeLaterDispatcher$Future.run(InvokeLaterDispatcher.java:95)
at com.sun.glass.ui.win.WinApplication._runLoop(Native Method)
at com.sun.glass.ui.win.WinApplication.lambda$null$148(WinApplication.java:191)
... 1 more
Exception running application application.Main
The java.sql.Date is a java.util.Date subclass that holds no time information, so you can’t convert it to an Instant class.
Fortunately, there is a toLocalDate method that does just that, convert it directly to LocalDate.
It should be like this:
rs.getDate(4).toLocalDate();
For further reference take a look at the JavaDoc https://docs.oracle.com/javase/8/docs/api/java/sql/Date.html#toInstant--

spring boot javax.persistence.EntityNotFoundException in many to one however data exist

Consider code bellow
Beneficiaire class :
#Entity
#Table(uniqueConstraints=
#UniqueConstraint(name="u_benef_noBenef", columnNames="noBenef"))
public class Beneficiaire implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy=GenerationType.IDENTITY)
private Integer idBenef;
#Column(nullable=false)
private Integer noApBenef;
#Column(nullable=false)
private Integer noBenef;
#Column(columnDefinition="character varying(100) not null")
private String nomBenef;
#DateTimeFormat(pattern="dd/MM/yyyy")
#Column(nullable=false)
private LocalDate dateNaissanceBenef;
#ManyToOne(cascade=CascadeType.ALL)
#JoinColumn(name="id_cat_beneficiaire",
foreignKey=#ForeignKey(name="fk_benef_idCatBenef"),
nullable=false)
private CategorieBeneficiaire categorieBeneficiaire;
#ManyToOne(cascade=CascadeType.ALL)
#JoinColumn(name="id_sexe",
foreignKey=#ForeignKey(name="fk_benef_idSexe"),
nullable=false)
private Sexe sexe;
#ManyToOne(cascade=CascadeType.ALL)
#JoinColumn(name="id_assure",
foreignKey=#ForeignKey(name="fk_benef_idAssure"),
nullable=false)
private Assure assure;
#ManyToOne(cascade=CascadeType.ALL)
#JoinColumn(name="id_attributaire",
foreignKey=#ForeignKey(name="fk_benef_idAttrib"),
nullable=false)
private Attributaire attributaire;
#ManyToOne(cascade=CascadeType.ALL)
#JoinColumn(name="id_prestation",
foreignKey=#ForeignKey(name="fk_benef_idPrestation"),
nullable=false)
private Prestation prestation;
#DateTimeFormat(pattern="dd/MM/yyyy")
#Column(nullable=false)
private LocalDate dateEffetPrestation;
#Column(precision=8, nullable=false)
private BigDecimal mntMensuelPrestation;
private Integer trimestreDerniereEmission;
private Integer anneeDerniereEmission;
#Column(columnDefinition="integer default 1 not null", insertable=false)
private Integer estActifBenef;
#Column(columnDefinition="timestamp default current_timestamp not null", insertable=false)
private LocalDateTime dateheureCreationBenef;
#ManyToOne(cascade=CascadeType.ALL)
#JoinColumn(name="id_utilisateur",
foreignKey=#ForeignKey(name="utilisateur_id_fk"),
nullable=true)
private Utilisateur utilisateur;
/*#OneToMany(mappedBy="beneficiairePj", cascade=CascadeType.ALL, orphanRemoval=true)
private List<PieceJustificative> pieceJustificatives = new ArrayList<PieceJustificative>();*/
public Beneficiaire() {
//For JPA
}
public Beneficiaire(Integer noBenef, String nomBenef, Integer noApBenef,
CategorieBeneficiaire categorieBeneficiaire, Sexe sexe, Assure assure, Attributaire attributaire,
Prestation prestation) {
super();
this.noBenef = noBenef;
this.nomBenef = nomBenef;
this.noApBenef = noApBenef;
this.categorieBeneficiaire = categorieBeneficiaire;
this.sexe = sexe;
this.assure = assure;
this.attributaire = attributaire;
this.prestation = prestation;
}
public Integer getIdBenef() {
return idBenef;
}
public void setIdBenef(Integer idBenef) {
this.idBenef = idBenef;
}
public Integer getNoBenef() {
return noBenef;
}
public void setNoBenef(Integer noBenef) {
this.noBenef = noBenef;
}
public String getNomBenef() {
return nomBenef;
}
public void setNomBenef(String nomBenef) {
this.nomBenef = nomBenef;
}
public Integer getNoApBenef() {
return noApBenef;
}
public void setNoApBenef(Integer noApBenef) {
this.noApBenef = noApBenef;
}
public LocalDate getDateNaissanceBenef() {
return dateNaissanceBenef;
}
public void setDateNaissanceBenef(LocalDate dateNaissanceBenef) {
this.dateNaissanceBenef = dateNaissanceBenef;
}
public CategorieBeneficiaire getCategorieBeneficiaire() {
return categorieBeneficiaire;
}
public void setCategorieBeneficiaire(CategorieBeneficiaire categorieBeneficiaire) {
this.categorieBeneficiaire = categorieBeneficiaire;
}
public Sexe getSexe() {
return sexe;
}
public void setSexe(Sexe sexe) {
this.sexe = sexe;
}
public Assure getAssure() {
return assure;
}
public void setAssure(Assure assure) {
this.assure = assure;
}
public Attributaire getAttributaire() {
return attributaire;
}
public void setAttributaire(Attributaire attributaire) {
this.attributaire = attributaire;
}
public Prestation getPrestation() {
return prestation;
}
public void setPrestation(Prestation prestation) {
this.prestation = prestation;
}
public LocalDate getDateEffetPrestation() {
return dateEffetPrestation;
}
public void setDateEffetPrestation(LocalDate datteEffetPrestation) {
this.dateEffetPrestation = datteEffetPrestation;
}
public BigDecimal getMntMensuelPrestation() {
return mntMensuelPrestation;
}
public void setMntMensuelPrestation(BigDecimal mntMensuelPrestation) {
this.mntMensuelPrestation = mntMensuelPrestation;
}
public Integer getTrimestreDerniereEmission() {
return trimestreDerniereEmission;
}
public void setTrimestreDerniereEmission(Integer trimestreDerniereEmission)
{
this.trimestreDerniereEmission = trimestreDerniereEmission;
}
public Integer getAnneeDerniereEmission() {
return anneeDerniereEmission;
}
public void setAnneeDerniereEmission(Integer anneeDerniereEmission) {
this.anneeDerniereEmission = anneeDerniereEmission;
}
public Integer getEstActifBenef() {
return estActifBenef;
}
public void setEstActifBenef(Integer estActifBenef) {
this.estActifBenef = estActifBenef;
}
public LocalDateTime getDateheureCreationBenef() {
return dateheureCreationBenef;
}
public void setDateheureCreationBenef(LocalDateTime dateheureCreationBenef)
{
this.dateheureCreationBenef = dateheureCreationBenef;
}
public Utilisateur getUtilisateur() {
return utilisateur;
}
public void setUtilisateur(Utilisateur utilisateur) {
this.utilisateur = utilisateur;
}
//For Test Equal, override equals() and hashCode()
#Override
public boolean equals(Object o) {
if (this == o)
return true;
if (o == null || getClass() != o.getClass())
return false;
Beneficiaire beneficiaire = (Beneficiaire) o;
return noBenef.equals(beneficiaire.getNoBenef());
}
#Override
public int hashCode() {
return Objects.hash(noBenef);
}
}
PieceJustificative class :
#Entity
#Table(uniqueConstraints=
#UniqueConstraint(name="u_pj_noPj", columnNames="noPj"))
public class PieceJustificative implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy=GenerationType.IDENTITY)
private Integer idPj;
#Column(nullable=false)
private Integer noPj;
#DateTimeFormat(pattern="dd/MM/yyyy")
#Column(nullable=false)
private LocalDate dateDebutValiditePj;
#DateTimeFormat(pattern="dd/MM/yyyy")
#Column(nullable=false)
private LocalDate dateFinValiditePj;
#DateTimeFormat(pattern="dd/MM/yyyy")
#Column(nullable=false)
private LocalDate dateSignaturePj;
#Column(columnDefinition="timestamp default current_timestamp not null", insertable=false)
private LocalDateTime dateHeureSaisiePj;
private LocalDateTime dateHeureValidationPj;
#Column(columnDefinition="integer default 0 not null", insertable=false)
private Integer estValidePj;
/*#ManyToOne(optional=false, fetch=FetchType.LAZY)
*/
#ManyToOne
#JoinColumn(name="id_type_pj",
foreignKey=#ForeignKey(name="fk_pj_id_type_pj"),
nullable=false)
private TypePj typePj;
/*#ManyToOne(optional=false, fetch=FetchType.LAZY)
#JoinColumn(name="id_beneficiaire",
foreignKey=#ForeignKey(name="fk_pj_id_beneficiaire"))
*/
/*#ManyToOne(optional=false)*/
#ManyToOne
#JoinColumn(name="idBenef",
foreignKey=#ForeignKey(name="fk_pj_id_beneficiaire"),
nullable=false)
private Beneficiaire beneficiairePj;
#ManyToOne
#JoinColumn(name="id_utilisateur_saisie",
foreignKey=#ForeignKey(name="fk_pj_id_utilisateur_saisie"))
private Utilisateur utilisateurSaisiePj;
#ManyToOne
#JoinColumn(name="id_utilisateur_valide",
foreignKey=#ForeignKey(name="fk_pj_id_utilisateur_valide"))
private Utilisateur utilisateurValidationPj;
protected PieceJustificative() {
//For JPA
}
public Integer getIdPj() {
return idPj;
}
public void setIdPj(Integer idPj) {
this.idPj = idPj;
}
public Integer getNoPj() {
return noPj;
}
public void setNoPj(Integer noPj) {
this.noPj = noPj;
}
public LocalDate getDateDebutValiditePj() {
return dateDebutValiditePj;
}
public void setDateDebutValiditePj(LocalDate dateDebutValiditePj) {
this.dateDebutValiditePj = dateDebutValiditePj;
}
public LocalDate getDateFinValiditePj() {
return dateFinValiditePj;
}
public void setDateFinValiditePj(LocalDate dateFinValiditePj) {
this.dateFinValiditePj = dateFinValiditePj;
}
public LocalDate getDateSignaturePj() {
return dateSignaturePj;
}
public void setDateSignaturePj(LocalDate dateSignaturePj) {
this.dateSignaturePj = dateSignaturePj;
}
public LocalDateTime getDateHeureSaisiePj() {
return dateHeureSaisiePj;
}
public void setDateHeureSaisiePj(LocalDateTime dateHeureSaisiePj) {
this.dateHeureSaisiePj = dateHeureSaisiePj;
}
public LocalDateTime getDateHeureValidationPj() {
return dateHeureValidationPj;
}
public void setDateHeureValidationPj(LocalDateTime dateHeureValidationPj) {
this.dateHeureValidationPj = dateHeureValidationPj;
}
public Integer getEstValidePj() {
return estValidePj;
}
public void setEstValidePj(Integer estValidePj) {
this.estValidePj = estValidePj;
}
/**
* #return the typePj
*/
public TypePj getTypePj() {
return typePj;
}
/**
* #param typePj the typePj to set
*/
public void setTypePj(TypePj typePj) {
this.typePj = typePj;
}
public Beneficiaire getBeneficiairePj() {
return beneficiairePj;
}
public void setBeneficiairePj(Beneficiaire beneficiairePj) {
this.beneficiairePj = beneficiairePj;
}
public Utilisateur getUtilisateurSaisiePj() {
return utilisateurSaisiePj;
}
public void setUtilisateurSaisiePj(Utilisateur utilisateurSaisiePj) {
this.utilisateurSaisiePj = utilisateurSaisiePj;
}
public Utilisateur getUtilisateurValidationPj() {
return utilisateurValidationPj;
}
public void setUtilisateurValidationPj(Utilisateur utilisateurValidationPj) {
this.utilisateurValidationPj = utilisateurValidationPj;
}
//For Test Equal, override equals() and hashCode()
#Override
public boolean equals(Object o) {
if (this == o)
return true;
if (o == null || getClass() != o.getClass())
return false;
PieceJustificative pieceJustificative = (PieceJustificative) o;
return noPj.equals(pieceJustificative.getNoPj());
}
#Override
public int hashCode() {
return Objects.hash(noPj);
}
}
My thymeleaf rendered view for list of PieceJustificative :
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org"
xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout"
layout:decorator="layouts/layout">
<head>
<meta charset="UTF-8" />
<title>Liste des pièces justificatives</title>
<!-- <link th:href="#{/css/form.css}" rel="stylesheet"/> -->
</head>
<body>
<div id="content" layout:fragment="content">
<div class="w3-container">
<h2>Liste des pièces justificatives</h2>
<!-- <table class="w3-table-all w3-hoverable"> -->
<table id="customers">
<thead>
<!-- <tr class="w3-light-grey"> -->
<tr >
<th>N° pièce jointe</th>
<th>Type pièce jointe</th>
<th>N° bénéficiaire</th>
<th>Nom bénéficiaire</th>
<th>Date début validité</th>
<th>Date fin validité</th>
<th>Date signature</th>
<th>Modifier</th>
<th>Supprimer</th>
</tr>
</thead>
<tr th:each="pieceJustificative : ${pieceJustificatives}">
<td th:text="${pieceJustificative.noPj}">N°</td>
<td th:text="${pieceJustificative.typePj.libelleTypePj}">libelleTypePj</td>
<td th:text="${pieceJustificative.beneficiairePj.noBenef}">noBenef</td>
<td th:text="${pieceJustificative.beneficiairePj.nomBenef}">nomBenef</td>
<td th:text="${#temporals.format(pieceJustificative.dateDebutValiditePj, 'dd/MM/yyyy')}">dateDebutValiditePj</td>
<td th:text="${#temporals.format(pieceJustificative.dateFinValiditePj, 'dd/MM/yyyy')}">dateFinValiditePj</td>
<td th:text="${#temporals.format(pieceJustificative.dateSignaturePj, 'dd/MM/yyyy')}">dateSignaturePj</td>
<td>Modifier</td>
<td>Supprimer</td>
</tr>
</table>
</div>
<p>
Ajouter pièce justificative
</p>
</div><!-- end div content -->
When I tried to render this list of PieceJustificative, I got this exception, however the Beneficiaire with id 57271 exist in my database :
javax.persistence.EntityNotFoundException: Unable to find ne.cnss.pension.beneficiaire.Beneficiaire with id 57271
at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl$JpaEntityNotFoundDelegate.handleEntityNotFound(EntityManagerFactoryBuilderImpl.java:144) ~[hibernate-entitymanager-5.0.12.Final.jar:5.0.12.Final]
at org.hibernate.event.internal.DefaultLoadEventListener.load(DefaultLoadEventListener.java:227) ~[hibernate-core-5.0.12.Final.jar:5.0.12.Final]
at org.hibernate.event.internal.DefaultLoadEventListener.proxyOrLoad(DefaultLoadEventListener.java:278) ~[hibernate-core-5.0.12.Final.jar:5.0.12.Final]
at org.hibernate.event.internal.DefaultLoadEventListener.doOnLoad(DefaultLoadEventListener.java:121) ~[hibernate-core-5.0.12.Final.jar:5.0.12.Final]
at org.hibernate.event.internal.DefaultLoadEventListener.onLoad(DefaultLoadEventListener.java:89) ~[hibernate-core-5.0.12.Final.jar:5.0.12.Final]
at org.hibernate.internal.SessionImpl.fireLoad(SessionImpl.java:1129) ~[hibernate-core-5.0.12.Final.jar:5.0.12.Final]
at org.hibernate.internal.SessionImpl.internalLoad(SessionImpl.java:1022) ~[hibernate-core-5.0.12.Final.jar:5.0.12.Final]
at org.hibernate.type.EntityType.resolveIdentifier(EntityType.java:639) ~[hibernate-core-5.0.12.Final.jar:5.0.12.Final]
at org.hibernate.type.EntityType.resolve(EntityType.java:431) ~[hibernate-core-5.0.12.Final.jar:5.0.12.Final]
at org.hibernate.engine.internal.TwoPhaseLoad.doInitializeEntity(TwoPhaseLoad.java:154) ~[hibernate-core-5.0.12.Final.jar:5.0.12.Final]
at org.hibernate.engine.internal.TwoPhaseLoad.initializeEntity(TwoPhaseLoad.java:128) ~[hibernate-core-5.0.12.Final.jar:5.0.12.Final]
at org.hibernate.loader.Loader.initializeEntitiesAndCollections(Loader.java:1133) ~[hibernate-core-5.0.12.Final.jar:5.0.12.Final]
at org.hibernate.loader.Loader.processResultSet(Loader.java:992) ~[hibernate-core-5.0.12.Final.jar:5.0.12.Final]
at org.hibernate.loader.Loader.doQuery(Loader.java:930) ~[hibernate-core-5.0.12.Final.jar:5.0.12.Final]
at org.hibernate.loader.Loader.doQueryAndInitializeNonLazyCollections(Loader.java:336) ~[hibernate-core-5.0.12.Final.jar:5.0.12.Final]
at org.hibernate.loader.Loader.doList(Loader.java:2617) ~[hibernate-core-5.0.12.Final.jar:5.0.12.Final]
at org.hibernate.loader.Loader.doList(Loader.java:2600) ~[hibernate-core-5.0.12.Final.jar:5.0.12.Final]
at org.hibernate.loader.Loader.listIgnoreQueryCache(Loader.java:2429) ~[hibernate-core-5.0.12.Final.jar:5.0.12.Final]
at org.hibernate.loader.Loader.list(Loader.java:2424) ~[hibernate-core-5.0.12.Final.jar:5.0.12.Final]
at org.hibernate.loader.hql.QueryLoader.list(QueryLoader.java:501) ~[hibernate-core-5.0.12.Final.jar:5.0.12.Final]
at org.hibernate.hql.internal.ast.QueryTranslatorImpl.list(QueryTranslatorImpl.java:371) ~[hibernate-core-5.0.12.Final.jar:5.0.12.Final]
at org.hibernate.engine.query.spi.HQLQueryPlan.performList(HQLQueryPlan.java:216) ~[hibernate-core-5.0.12.Final.jar:5.0.12.Final]
at org.hibernate.internal.SessionImpl.list(SessionImpl.java:1326) ~[hibernate-core-5.0.12.Final.jar:5.0.12.Final]
at org.hibernate.internal.QueryImpl.list(QueryImpl.java:87) ~[hibernate-core-5.0.12.Final.jar:5.0.12.Final]
at org.hibernate.jpa.internal.QueryImpl.list(QueryImpl.java:606) ~[hibernate-entitymanager-5.0.12.Final.jar:5.0.12.Final]
at org.hibernate.jpa.internal.QueryImpl.getResultList(QueryImpl.java:483) ~[hibernate-entitymanager-5.0.12.Final.jar:5.0.12.Final]
at org.hibernate.jpa.criteria.compile.CriteriaQueryTypeQueryAdapter.getResultList(CriteriaQueryTypeQueryAdapter.java:50) ~[hibernate-entitymanager-5.0.12.Final.jar:5.0.12.Final]
at org.springframework.data.jpa.repository.support.SimpleJpaRepository.findAll(SimpleJpaRepository.java:329) ~[spring-data-jpa-1.11.8.RELEASE.jar:na]
at org.springframework.data.jpa.repository.support.SimpleJpaRepository.findAll(SimpleJpaRepository.java:74) ~[spring-data-jpa-1.11.8.RELEASE.jar:na]
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:1.8.0_131]
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) ~[na:1.8.0_131]
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:1.8.0_131]
at java.lang.reflect.Method.invoke(Method.java:498) ~[na:1.8.0_131]
at org.springframework.data.repository.core.support.RepositoryFactorySupport$QueryExecutorMethodInterceptor.executeMethodOn(RepositoryFactorySupport.java:504) ~[spring-data-commons-1.13.8.RELEASE.jar:na]
at org.springframework.data.repository.core.support.RepositoryFactorySupport$QueryExecutorMethodInterceptor.doInvoke(RepositoryFactorySupport.java:489) ~[spring-data-commons-1.13.8.RELEASE.jar:na]
at org.springframework.data.repository.core.support.RepositoryFactorySupport$QueryExecutorMethodInterceptor.invoke(RepositoryFactorySupport.java:461) ~[spring-data-commons-1.13.8.RELEASE.jar:na]
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179) ~[spring-aop-4.3.12.RELEASE.jar:4.3.12.RELEASE]
at org.springframework.data.projection.DefaultMethodInvokingMethodInterceptor.invoke(DefaultMethodInvokingMethodInterceptor.java:56) ~[spring-data-commons-1.13.8.RELEASE.jar:na]
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179) ~[spring-aop-4.3.12.RELEASE.jar:4.3.12.RELEASE]
at org.springframework.transaction.interceptor.TransactionInterceptor$1.proceedWithInvocation(TransactionInterceptor.java:99) ~[spring-tx-4.3.12.RELEASE.jar:4.3.12.RELEASE]
at org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:282) ~[spring-tx-4.3.12.RELEASE.jar:4.3.12.RELEASE]
at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:96) ~[spring-tx-4.3.12.RELEASE.jar:4.3.12.RELEASE]
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179) ~[spring-aop-4.3.12.RELEASE.jar:4.3.12.RELEASE]
at org.springframework.dao.support.PersistenceExceptionTranslationInterceptor.invoke(PersistenceExceptionTranslationInterceptor.java:136) ~[spring-tx-4.3.12.RELEASE.jar:4.3.12.RELEASE]
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179) ~[spring-aop-4.3.12.RELEASE.jar:4.3.12.RELEASE]
at org.springframework.data.jpa.repository.support.CrudMethodMetadataPostProcessor$CrudMethodMetadataPopulatingMethodInterceptor.invoke(CrudMethodMetadataPostProcessor.java:133) ~[spring-data-jpa-1.11.8.RELEASE.jar:na]
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179) ~[spring-aop-4.3.12.RELEASE.jar:4.3.12.RELEASE]
at org.springframework.aop.interceptor.ExposeInvocationInterceptor.invoke(ExposeInvocationInterceptor.java:92) ~[spring-aop-4.3.12.RELEASE.jar:4.3.12.RELEASE]
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179) ~[spring-aop-4.3.12.RELEASE.jar:4.3.12.RELEASE]
at org.springframework.data.repository.core.support.SurroundingTransactionDetectorMethodInterceptor.invoke(SurroundingTransactionDetectorMethodInterceptor.java:57) ~[spring-data-commons-1.13.8.RELEASE.jar:na]
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179) ~[spring-aop-4.3.12.RELEASE.jar:4.3.12.RELEASE]
at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:213) ~[spring-aop-4.3.12.RELEASE.jar:4.3.12.RELEASE]
at com.sun.proxy.$Proxy162.findAll(Unknown Source) ~[na:na]
at ne.cnss.pension.piecejustificative.PieceJustificativeService.listeDesPiecesJustificatives(PieceJustificativeService.java:101) ~[classes/:na]
at ne.cnss.pension.piecejustificative.PieceJustificativeController.listeDesCategoriesPieceJustificatives(PieceJustificativeController.java:117) ~[classes/:na]
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:1.8.0_131]
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) ~[na:1.8.0_131]
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:1.8.0_131]
at java.lang.reflect.Method.invoke(Method.java:498) ~[na:1.8.0_131]
at org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:205) ~[spring-web-4.3.12.RELEASE.jar:4.3.12.RELEASE]
at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:133) ~[spring-web-4.3.12.RELEASE.jar:4.3.12.RELEASE]
at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:97) ~[spring-webmvc-4.3.12.RELEASE.jar:4.3.12.RELEASE]
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:827) ~[spring-webmvc-4.3.12.RELEASE.jar:4.3.12.RELEASE]
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:738) ~[spring-webmvc-4.3.12.RELEASE.jar:4.3.12.RELEASE]
at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:85) ~[spring-webmvc-4.3.12.RELEASE.jar:4.3.12.RELEASE]
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:967) ~[spring-webmvc-4.3.12.RELEASE.jar:4.3.12.RELEASE]
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:901) ~[spring-webmvc-4.3.12.RELEASE.jar:4.3.12.RELEASE]
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:970) ~[spring-webmvc-4.3.12.RELEASE.jar:4.3.12.RELEASE]
at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:861) ~[spring-webmvc-4.3.12.RELEASE.jar:4.3.12.RELEASE]
at javax.servlet.http.HttpServlet.service(HttpServlet.java:635) ~[tomcat-embed-core-8.5.23.jar:8.5.23]
at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:846) ~[spring-webmvc-4.3.12.RELEASE.jar:4.3.12.RELEASE]
at javax.servlet.http.HttpServlet.service(HttpServlet.java:742) ~[tomcat-embed-core-8.5.23.jar:8.5.23]
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:231) ~[tomcat-embed-core-8.5.23.jar:8.5.23]
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-8.5.23.jar:8.5.23]
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52) ~[tomcat-embed-websocket-8.5.23.jar:8.5.23]
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) ~[tomcat-embed-core-8.5.23.jar:8.5.23]
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-8.5.23.jar:8.5.23]
at org.springframework.web.filter.RequestContextFilter.doFilterInternal(RequestContextFilter.java:99) ~[spring-web-4.3.12.RELEASE.jar:4.3.12.RELEASE]
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) ~[spring-web-4.3.12.RELEASE.jar:4.3.12.RELEASE]
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) ~[tomcat-embed-core-8.5.23.jar:8.5.23]
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-8.5.23.jar:8.5.23]
at org.springframework.web.filter.HttpPutFormContentFilter.doFilterInternal(HttpPutFormContentFilter.java:108) ~[spring-web-4.3.12.RELEASE.jar:4.3.12.RELEASE]
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) ~[spring-web-4.3.12.RELEASE.jar:4.3.12.RELEASE]
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) ~[tomcat-embed-core-8.5.23.jar:8.5.23]
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-8.5.23.jar:8.5.23]
at org.springframework.web.filter.HiddenHttpMethodFilter.doFilterInternal(HiddenHttpMethodFilter.java:81) ~[spring-web-4.3.12.RELEASE.jar:4.3.12.RELEASE]
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) ~[spring-web-4.3.12.RELEASE.jar:4.3.12.RELEASE]
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) ~[tomcat-embed-core-8.5.23.jar:8.5.23]
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-8.5.23.jar:8.5.23]
at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:197) ~[spring-web-4.3.12.RELEASE.jar:4.3.12.RELEASE]
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) ~[spring-web-4.3.12.RELEASE.jar:4.3.12.RELEASE]
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) ~[tomcat-embed-core-8.5.23.jar:8.5.23]
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-8.5.23.jar:8.5.23]
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:199) ~[tomcat-embed-core-8.5.23.jar:8.5.23]
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:96) [tomcat-embed-core-8.5.23.jar:8.5.23]
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:478) [tomcat-embed-core-8.5.23.jar:8.5.23]
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:140) [tomcat-embed-core-8.5.23.jar:8.5.23]
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:81) [tomcat-embed-core-8.5.23.jar:8.5.23]
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:87) [tomcat-embed-core-8.5.23.jar:8.5.23]
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:342) [tomcat-embed-core-8.5.23.jar:8.5.23]
at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:803) [tomcat-embed-core-8.5.23.jar:8.5.23]
at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:66) [tomcat-embed-core-8.5.23.jar:8.5.23]
at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:868) [tomcat-embed-core-8.5.23.jar:8.5.23]
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1459) [tomcat-embed-core-8.5.23.jar:8.5.23]
at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49) [tomcat-embed-core-8.5.23.jar:8.5.23]
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142) [na:1.8.0_131]
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617) [na:1.8.0_131]
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61) [tomcat-embed-core-8.5.23.jar:8.5.23]
at java.lang.Thread.run(Thread.java:748) [na:1.8.0_131]
Try fetch=FetchType.EAGER
Default is lazy. It should work.

when i injected empdao object into controller and tried to use that object showing nullpointerexception

public class Maincontroll implements Controller {
Empdao dao;
public void setDao(Empdao dao) {
this.dao = dao;
}
public Empdao getDao() {
return dao;
}
#Override
public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response) throws Exception {
Employee e = new Employee();
e.setName(request.getParameter("name"));
e.setEmail(request.getParameter("email"));
e.setMobile(request.getParameter("mobile"));
e.setAddress(request.getParameter("address"));
int i = dao.save(e);
System.out.println("ivalue is : "+i);
return new ModelAndView("sucess");
}
}
java.lang.NullPointerException
at nxt.Maincontroll.handleRequest(Maincontroll.java:30)
at org.springframework.web.servlet.mvc.SimpleControllerHandlerAdapter.handle(SimpleControllerHandlerAdapter.java:48)
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:771)
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:716)
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:647)
at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:552)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:622)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:729)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:292)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:207)
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:240)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:207)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:212)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:106)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:502)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:141)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:79)
at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:616)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:88)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:509)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1104)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:684)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1520)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.run(NioEndpoint.java:1476)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
at java.lang.Thread.run(Thread.java:745)
Where exactly are you injecting the dao object into your controller? The getter and setter don't constitute injection. They are simply what the container uses to inject beans. Do you have an xml configuration of this bean?

java.lang.NullPointerException for Multi Screens JavaFX/FXML

So, I'm doing a JavaFX multiview GUI application.
Below is the code so that you can refer to it, don't read through it to find an error yet, I'll explain the problem underneath first ;)
I have a main - which starts the application
public class MyFXMLMain extends Application {
#Override
public void start(Stage stage) throws Exception {
Parent root = FXMLLoader.load(getClass().getResource("Wireframe.fxml"));
stage.setTitle("My Fitness App");
Scene mainScene = new Scene(root,805,809);
stage.setScene(mainScene);
stage.show();
}
public static void main(String[] args) {
launch(args);
}
ScreensController - that controls loading/setting screens.
public class ScreensController extends StackPane {
private HashMap<String, Node> screens = new HashMap<>();
public ScreensController() {
super();
}
public void addScreen(String name, Node screen) {
screens.put(name, screen);
}
public Node getScreen(String name) {
return screens.get(name);
}
public boolean loadScreen(String name, String resource) {
try {
FXMLLoader myLoader = new FXMLLoader(getClass().getResource(resource));
Parent loadScreen = (Parent) myLoader.load();
ControlledScreen myScreenController = ((ControlledScreen) myLoader.getController());
myScreenController.setScreenParent(this);
addScreen(name, loadScreen);
return true;
}catch(Exception e) {
System.out.println(e.getMessage());
return false;
}
}
public boolean setScreen(final String name) {
if (screens.get(name) != null) { //screen loaded
final DoubleProperty opacity = opacityProperty();
if (!getChildren().isEmpty()) { //if there is more than one screen
Timeline fade = new Timeline(
new KeyFrame(Duration.ZERO, new KeyValue(opacity, 1.0)),
new KeyFrame(new Duration(1000), new EventHandler<ActionEvent>() {
#Override
public void handle(ActionEvent t) {
getChildren().remove(0); //remove the displayed screen
getChildren().add(0, screens.get(name)); //add the screen
Timeline fadeIn = new Timeline(
new KeyFrame(Duration.ZERO, new KeyValue(opacity, 0.0)),
new KeyFrame(new Duration(800), new KeyValue(opacity, 1.0)));
fadeIn.play();
}
}, new KeyValue(opacity, 0.0)));
fade.play();
} else {
setOpacity(0.0);
getChildren().add(screens.get(name)); //no one else been displayed, then just show
Timeline fadeIn = new Timeline(
new KeyFrame(Duration.ZERO, new KeyValue(opacity, 0.0)),
new KeyFrame(new Duration(2500), new KeyValue(opacity, 1.0)));
fadeIn.play();
}
return true;
} else {
System.out.println("screen hasn't been loaded!!! \n");
return false;
}
}
public boolean unloadScreen(String name) {
if (screens.remove(name) == null) {
System.out.println("Screen didn't exist");
return false;
} else {
return true;
}
}
}
A screen framework - that links the screens to the FXML files.
public class ScreensFramework extends Application {
public static String MAIN_SCREEN = "MyFXMLController";
public static String MAIN_SCREEN_FXML = "Wireframe.fxml";
public static String calendarScreen = "CalendarscreenController";
public static String calendarScreenFXML = "Calendarscreen.fxml";
public static String guideScreen = "GuideScreenController";
public static String guideScreenFXML ="Guidescreen.fxml";
#Override
public void start(Stage primaryStage) {
ScreensController mainContainer = new ScreensController();
mainContainer.loadScreen(ScreensFramework.MAIN_SCREEN, ScreensFramework.MAIN_SCREEN_FXML);
mainContainer.loadScreen(ScreensFramework.calendarScreen,ScreensFramework.calendarScreenFXML);
mainContainer.loadScreen(ScreensFramework.guideScreen,ScreensFramework.guideScreenFXML);
mainContainer.setScreen(ScreensFramework.MAIN_SCREEN);
Group root = new Group();
root.getChildren().addAll(mainContainer);
Scene scene = new Scene(root);
primaryStage.setScene(scene);
primaryStage.show();
}
}
An FXML controller - which links to the FXML files and tells FXML what to do when something is clicked.
public class MyFXMLController implements ControlledScreen{
#FXML private TextField givenName;
#FXML private Text targetText;
//#FXML private static TableView<Mass> theTable;
//#FXML private static TableColumn<Mass, String> dateCol;
//#FXML private static TableColumn<Mass, String> massCol;
#FXML private static LineChart<Number,Number> weightChart;
#FXML private static NumberAxis axisX;
#FXML private static NumberAxis axisY;
#FXML private static Label myLabel;
//private static User theUser = new User();
private static ScreensController myController;
#Override
public void setScreenParent(ScreensController screenPage) {
myController = screenPage;
}
#FXML protected void handlePressedCalendarButtonAction(ActionEvent event){
System.out.println("Hello");
}
#FXML protected void mouseclickedcal(MouseEvent mec){
myController.setScreen(ScreensFramework.calendarScreen);
}
}
A controlledscreen - that does this:
public interface ControlledScreen {
public void setScreenParent(ScreensController screenPage);
}
And a CalendarScreenController - that controls one of the multi screens
public class CalendarScreenController implements Initializable, ControlledScreen {
ScreensController myController;
#Override
public void initialize(URL url, ResourceBundle rb) {
}
public void setScreenParent(ScreensController screenParent){
myController = screenParent;
}
#FXML
private void goToMain(ActionEvent event){
myController.setScreen(ScreensFramework.MAIN_SCREEN);
}
}
PROBLEM BELOW
When I run my program it works fine, but then if I click on a button that activates the calendar onclick code here:
#FXML protected void mouseclickedcal(MouseEvent mec){
myController.setScreen(ScreensFramework.calendarScreen);
}
which should set the screen to CalendarScreen.fxml,one of my multi screens but instead, it causes an error below:
java.lang.RuntimeException: java.lang.reflect.InvocationTargetException
at javafx.fxml.FXMLLoader$ControllerMethodEventHandler.handle(Unknown Source)
at com.sun.javafx.event.CompositeEventHandler.dispatchBubblingEvent(Unknown Source)
at com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(Unknown Source)
at com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(Unknown Source)
at com.sun.javafx.event.CompositeEventDispatcher.dispatchBubblingEvent(Unknown Source)
at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(Unknown Source)
at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(Unknown Source)
at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(Unknown Source)
at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(Unknown Source)
at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(Unknown Source)
at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(Unknown Source)
at com.sun.javafx.event.EventUtil.fireEventImpl(Unknown Source)
at com.sun.javafx.event.EventUtil.fireEvent(Unknown Source)
at javafx.event.Event.fireEvent(Unknown Source)
at javafx.scene.Scene$ClickGenerator.postProcess(Unknown Source)
at javafx.scene.Scene$ClickGenerator.access$8600(Unknown Source)
at javafx.scene.Scene$MouseHandler.process(Unknown Source)
at javafx.scene.Scene$MouseHandler.process(Unknown Source)
at javafx.scene.Scene$MouseHandler.access$1900(Unknown Source)
at javafx.scene.Scene.impl_processMouseEvent(Unknown Source)
at javafx.scene.Scene$ScenePeerListener.mouseEvent(Unknown Source)
at com.sun.javafx.tk.quantum.GlassViewEventHandler$MouseEventNotification.run(Unknown Source)
at com.sun.javafx.tk.quantum.GlassViewEventHandler$MouseEventNotification.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at com.sun.javafx.tk.quantum.GlassViewEventHandler.handleMouseEvent(Unknown Source)
at com.sun.glass.ui.View.handleMouseEvent(Unknown Source)
at com.sun.glass.ui.View.notifyMouse(Unknown Source)
at com.sun.glass.ui.win.WinApplication._runLoop(Native Method)
at com.sun.glass.ui.win.WinApplication.access$100(Unknown Source)
at com.sun.glass.ui.win.WinApplication$3$1.run(Unknown Source)
at java.lang.Thread.run(Unknown Source)
Caused by: java.lang.reflect.InvocationTargetException
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at sun.reflect.misc.Trampoline.invoke(Unknown Source)
at sun.reflect.GeneratedMethodAccessor1.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at sun.reflect.misc.MethodUtil.invoke(Unknown Source)
... 31 more
Caused by: java.lang.NullPointerException
at myfxml.MyFXMLController.mouseclickedcal(MyFXMLController.java:125)
... 40 more
Line 125 is the code:
#FXML protected void mouseclickedcal(MouseEvent mec){
myController.setScreen(ScreensFramework.calendarScreen);
}
Thank you so much for having a look at this. I can't seem to find the error ;(
Turns out I had 2 mains and they were conflicting and also in my xml code I was calling something that didn't exist in its controller.

Resources