I create a singleton class and calling a method inside it. I use spring mvc SimpleJdbcTemplate for retrieving data from database, but I get NullPointerException. Code I wrote is:
package in.dewsolutions.jc.utils;
import in.dewsolutions.jc.dao.ReportsDAO;
import in.dewsolutions.jc.dto.ReportsView;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import javax.annotation.PostConstruct;
import javax.sql.DataSource;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.config.PropertiesFactoryBean;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.jdbc.core.simple.ParameterizedRowMapper;
import org.springframework.jdbc.core.simple.SimpleJdbcTemplate;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Repository;
import org.springframework.stereotype.Service;
public class SingletonFilterData {
private static final Logger logger = Logger.getLogger(SingletonFilterData.class);
#Autowired
private SimpleJdbcTemplate simpleJdbcTemplate;
#Autowired
public void setDataSource(DataSource dataSource) {
this.simpleJdbcTemplate = new SimpleJdbcTemplate(dataSource);
}
private SingletonFilterData() // private defaul constructor
{
}
private static SingletonFilterData reference = null;
public static SingletonFilterData getInstance() {
if (reference == null) {
synchronized (SingletonFilterData.class) {
if (reference == null) {
reference = new SingletonFilterData();
}
}
}
return reference;
}
public List<ReportsView> findManuFacturer() {
// TODO Auto-generated method stub
List<ReportsView> manufacturer = new ArrayList<ReportsView>();
ReportsView rv = new ReportsView();
rv.setProductName("None");
rv.setProductId(0);
manufacturer.add(rv);
String query = "SELECT * FROM manufacturer ORDER BY name";
ParameterizedRowMapper<ReportsView> mapper = new ParameterizedRowMapper<ReportsView>() {
public ReportsView mapRow(ResultSet rs, int rowNum)
throws SQLException {
ReportsView reportsView = new ReportsView();
reportsView.setProductName(rs.getString("name"));
reportsView.setProductId(rs.getLong("id_manufacturer"));
return reportsView;
}
};
manufacturer.addAll(simpleJdbcTemplate.query(query, mapper));
return manufacturer;
}
The exception I get is:
type Exception report
message
description The server encountered an internal error () that prevented it from fulfilling this request.
exception
org.springframework.web.util.NestedServletException: Request processing failed; nested exception is java.lang.NullPointerException
org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:656)
org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:549)
javax.servlet.http.HttpServlet.service(HttpServlet.java:617)
javax.servlet.http.HttpServlet.service(HttpServlet.java:717)
org.displaytag.filter.ResponseOverrideFilter.doFilter(ResponseOverrideFilter.java:125)
root cause
java.lang.NullPointerException
in.dewsolutions.jc.utils.SingletonFilterData.findManuFacturer(SingletonFilterData.java:77)
in.dewsolutions.jc.controller.ReportsController.filterQuantity(ReportsController.java:169)
sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
java.lang.reflect.Method.invoke(Method.java:597)
org.springframework.web.bind.annotation.support.HandlerMethodInvoker.invokeHandlerMethod(HandlerMethodInvoker.java:176)
org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter.invokeHandlerMethod(AnnotationMethodHandlerAdapter.java:426)
org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter.handle(AnnotationMethodHandlerAdapter.java:414)
org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:790)
org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:719)
org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:644)
org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:549)
javax.servlet.http.HttpServlet.service(HttpServlet.java:617)
javax.servlet.http.HttpServlet.service(HttpServlet.java:717)
org.displaytag.filter.ResponseOverrideFilter.doFilter(ResponseOverrideFilter.java:125)
note The full stack trace of the root cause is available in the Apache Tomcat/6.0.29 logs.
How can I remove the Exception?
Using new SingletonFilterData() doesn't invoke the autowiring, so simpleJdbcTemplate remains null.
Instead of implementing getInstance(), you can configure Spring so that SingletonFilterData is a singleton and injected into ReportsController.
Related
This question already has answers here:
can not access a member of class org.springframework.aop.TruePointcut with modifiers public
(3 answers)
Closed 10 months ago.
This is my code (I removed a lot of graphics logic as to see if it would run a most basic file)
import java.util.Scanner;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.control.TextField;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.GridPane;
import javafx.stage.Stage;
import java.util.Scanner;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
class Client extends Application {
public static String host = "127.0.0.1";
public BufferedReader fromServer;
public PrintWriter toServer;
public Scanner consoleInput = new Scanner(System.in);
public Client() {
}
public static void main(String[] args) {
launch(args);
}
public void start(Stage displayStage) {
try {
System.out.println("HELLO");
} catch (Exception e) {
System.err.println("Client connection error!");
e.printStackTrace();
}
}
}
but the error messages are really bizarre and I'm not sure what exactly it means; it mentions a public access but afaik, public means anything can access it and I don't use reflection but its throwing errors regarding reflection and I'm really stumpted as to what could be causing this error.
Exception in Application constructor
Exception in thread "main" java.lang.reflect.InvocationTargetException
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:77)
at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.base/java.lang.reflect.Method.invoke(Method.java:568)
at java.base/sun.launcher.LauncherHelper$FXHelper.main(LauncherHelper.java:1071)
Caused by: java.lang.RuntimeException: Unable to construct Application instance: class eHillsClient.Client
at javafx.graphics#18/com.sun.javafx.application.LauncherImpl.launchApplication1(LauncherImpl.java:891)
at javafx.graphics#18/com.sun.javafx.application.LauncherImpl.lambda$launchApplication$2(LauncherImpl.java:196)
at java.base/java.lang.Thread.run(Thread.java:833)
Caused by: java.lang.IllegalAccessException: class com.sun.javafx.application.LauncherImpl (in module javafx.graphics) cannot access a member of class eHillsClient.Client with modifiers "public"
at java.base/jdk.internal.reflect.Reflection.newIllegalAccessException(Reflection.java:392)
at java.base/java.lang.reflect.AccessibleObject.checkAccess(AccessibleObject.java:674)
at java.base/java.lang.reflect.Constructor.newInstanceWithCaller(Constructor.java:489)
at java.base/java.lang.reflect.Constructor.newInstance(Constructor.java:480)
at javafx.graphics#18/com.sun.javafx.application.LauncherImpl.lambda$launchApplication1$8(LauncherImpl.java:803)
at javafx.graphics#18/com.sun.javafx.application.PlatformImpl.lambda$runAndWait$12(PlatformImpl.java:484)
at javafx.graphics#18/com.sun.javafx.application.PlatformImpl.lambda$runLater$10(PlatformImpl.java:457)
at java.base/java.security.AccessController.doPrivileged(AccessController.java:399)
at javafx.graphics#18/com.sun.javafx.application.PlatformImpl.lambda$runLater$11(PlatformImpl.java:456)
at javafx.graphics#18/com.sun.glass.ui.InvokeLaterDispatcher$Future.run(InvokeLaterDispatcher.java:96)
at javafx.graphics#18/com.sun.glass.ui.win.WinApplication._runLoop(Native Method)
at javafx.graphics#18/com.sun.glass.ui.win.WinApplication.lambda$runLoop$3(WinApplication.java:184)
... 1 more
Make Client class public because a main class in JavaFX Applicaions must have a public access modifier to be picked by getConstructor() method in Application class.In normal cases it wouldn't cause an error but your main class will not be an entry point to the program(in JavaFx Applicaions the entry points is Applicaion class).
You can further read here
I'm developing a Spring boot web application. and I'm working on spring boot to test the rest api to get hospital list, but i'am getting the following exception every time
org.springframework.web.util.NestedServletException: Request processing failed; nested exception is java.lang.NullPointerException
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:1013)
at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:897)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:634)
at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:882)
at org.springframework.test.web.servlet.TestDispatcherServlet.service(TestDispatcherServlet.java:66)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:741)
at org.springframework.mock.web.MockFilterChain$ServletFilterProxy.doFilter(MockFilterChain.java:166)
at org.springframework.mock.web.MockFilterChain.doFilter(MockFilterChain.java:133)
at org.springframework.test.web.servlet.MockMvc.perform(MockMvc.java:166)
at com.bezkoder.springjwt.Controller.HospitalControllerTest.testgetAllHospitals(HospitalControllerTest.java:134)
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.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)
at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:26)
at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:78)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:57)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
at org.mockito.internal.runners.DefaultInternalRunner$1.run(DefaultInternalRunner.java:78)
at org.mockito.internal.runners.DefaultInternalRunner.run(DefaultInternalRunner.java:84)
at org.mockito.internal.runners.StrictRunner.run(StrictRunner.java:39)
at org.mockito.junit.MockitoJUnitRunner.run(MockitoJUnitRunner.java:161)
at org.junit.runner.JUnitCore.run(JUnitCore.java:137)
at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:69)
at com.intellij.rt.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:33)
at com.intellij.rt.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:221)
at com.intellij.rt.junit.JUnitStarter.main(JUnitStarter.java:54)
Caused by: java.lang.NullPointerException
at com.bezkoder.springjwt.controllers.HospitalController.getAllHospitals(HospitalController.java:64)
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.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:190)
at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:138)
at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:104)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:892)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:797)
at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:87)
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:1039)
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:942)
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:1005)
... 36 more
this is my test
package com.bezkoder.springjwt.Controller;
import com.bezkoder.springjwt.controllers.HospitalController;
import com.bezkoder.springjwt.models.Hospital;
import com.bezkoder.springjwt.repository.HospitalRepository;
import com.bezkoder.springjwt.services.HospitalService;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.MockitoAnnotations;
import org.mockito.junit.MockitoJUnitRunner;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.mock.web.MockHttpServletResponse;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.MvcResult;
import org.springframework.test.web.servlet.RequestBuilder;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import java.util.ArrayList;
import java.util.List;
import static org.hamcrest.Matchers.is;
import static org.hamcrest.core.IsEqual.equalTo;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertThat;
#RunWith(MockitoJUnitRunner.class)
public class HospitalControllerTest {
#Mock
private HospitalService hospitalService;
#Mock
private HospitalRepository hospitalRepository;
#InjectMocks
private HospitalController hospitalController;
#Before
public void setUp() throws Exception {
mockMvc = MockMvcBuilders.standaloneSetup(hospitalController).build();
}
private MockMvc mockMvc;
private String mapToJson(Object object) throws JsonProcessingException {
ObjectMapper objectMapper = new ObjectMapper();
return objectMapper.writeValueAsString(object);
}
#Test
public void testcreateHospital() throws Exception {
Hospital hospital = new Hospital();
hospital.setId((long) 1);
hospital.setName("appellib");
hospital.setAdministrativeAddress("ad1234");
hospital.setFinessNumber(123456);
hospital.setSiretNumber(123456);
String uri = "/api/auth/hospital/add";
// String inputInJson = this.mapToJson(hospital);
String inputInJson = this.mapToJson(hospital);
// MvcResult result = mockMvc.perform(requestBuilder).andReturn();
MvcResult mvcResult = mockMvc.perform(MockMvcRequestBuilders.post(uri)
.contentType(MediaType.APPLICATION_JSON_VALUE)
.content(inputInJson)).andReturn();
int status = mvcResult.getResponse().getStatus();
assertEquals(200, status);
String content = mvcResult.getResponse().getContentAsString();
assertEquals(content, "Hospital is created successfully");
}
#Test
public void testgetAllHospitals() throws Exception{
String uri = "/api/auth/hospital/display";
Hospital hospital = new Hospital();
hospital.setId((long) 1);
hospital.setName("appellib");
hospital.setAdministrativeAddress("ad1234");
hospital.setFinessNumber(123456);
hospital.setSiretNumber(123456);
Hospital hospital1 = new Hospital();
hospital1.setId((long) 2);
hospital1.setName("Aled");
hospital1.setAdministrativeAddress("ad4567");
hospital1.setFinessNumber(98765);
hospital1.setSiretNumber(1256767);
List<Hospital> hospitalsList = new ArrayList<>();
hospitalsList.add(hospital);
hospitalsList.add(hospital1);
Mockito.when(hospitalService.findAll()).thenReturn(hospitalsList);
RequestBuilder requestBuilder = MockMvcRequestBuilders.get(uri).accept(MediaType.APPLICATION_JSON);
MvcResult result = mockMvc.perform(requestBuilder).andReturn();
String expectedJson = this.mapToJson(hospitalsList);
String outputInJson = result.getResponse().getContentAsString();
MockHttpServletResponse response = result.getResponse();
assertThat(outputInJson, is(equalTo(expectedJson)));
assertEquals(HttpStatus.OK.value(), response.getStatus());
}
}
and this is the function i'm testing
package com.bezkoder.springjwt.controllers;
import com.bezkoder.springjwt.models.Hospital;
import com.bezkoder.springjwt.payload.response.MessageResponse;
import com.bezkoder.springjwt.repository.HospitalRepository;
import com.bezkoder.springjwt.services.HospitalServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import java.util.List;
import java.util.logging.Logger;
#Controller
#RequestMapping("/api/auth/hospital")
public class HospitalController {
Logger logger = Logger.getLogger("com.Appel.lib.Controller.HospitalController");
#Autowired
HospitalServiceImpl hospitalService;
#Autowired
HospitalRepository hospitalRepository;
#PostMapping("/add")
public ResponseEntity<?> createHospital(#RequestBody Hospital hospital){
if (hospitalService.existsByName(hospital.getName())) {
return ResponseEntity
.badRequest()
.body(new MessageResponse("Error: name is already taken!"));
}
if (hospitalService.existsByAdministrativeAddress(hospital.getAdministrativeAddress())) {
return ResponseEntity
.badRequest()
.body(new MessageResponse("Error: administrative_address is already in use!"));
}
if (hospitalService.existsByFinessNumber(hospital.getFinessNumber())) {
return ResponseEntity
.badRequest()
.body(new MessageResponse("Error: finess_number is already taken!"));
}
if (hospitalService.existsBySiretNumber(hospital.getSiretNumber())) {
return ResponseEntity
.badRequest()
.body(new MessageResponse("Error: siret_number is already in use!"));
}
hospitalService.add(hospital);
return ResponseEntity.ok(new MessageResponse("Hospital registered successfully!"));
}
#GetMapping("/display")
public ResponseEntity<List<Hospital>> getAllHospitals() {
logger.info("Getting all Hospitals from hospital table...Call getAllHospitals ");
List<Hospital> hospitals = hospitalService.findAll();
logger.info("Data extracted from hospital table...");
return ResponseEntity.ok(hospitals) ;
}
}
i searched stackoverflow for any solution to a similar error, but i didn't find any, any solution suggested to fix this ?
Instead of :
return ResponseEntity.ok(hospitals) ;
Try this :
return ResponseEntity<List<hospitals>>(hospitals);
at com.bezkoder.springjwt.controllers.HospitalController.getAllHospitals(HospitalController.java:64)
check the object at line 64 it return null
This question already has answers here:
How to insert new items with Hibernate?
(3 answers)
Closed 6 years ago.
I'm trying to integrate Hibernate 5 with Spring MVC 4 application, using "Spring in Action" book as an example, but something goes wrong.
Here is simplified version of the code:
WebConfig
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.ViewResolver;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
import org.springframework.web.servlet.view.InternalResourceViewResolver;
#Configuration
#ComponentScan("temporaryApp")
#EnableWebMvc
public class WebConfig extends WebMvcConfigurerAdapter {
#Bean
public ViewResolver jspViewResolver() {
InternalResourceViewResolver resolver = new InternalResourceViewResolver();
resolver.setPrefix("/WEB-INF/views/");
resolver.setSuffix(".jsp");
resolver.setExposeContextBeansAsAttributes(true);
return resolver;
}
}
RootConfig
import org.apache.commons.dbcp.BasicDataSource;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.*;
import org.springframework.orm.hibernate5.LocalSessionFactoryBean;
import org.springframework.orm.hibernate5.HibernateTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import javax.sql.DataSource;
import java.util.Properties;
#Configuration
#ComponentScan(basePackages = {"temporaryApp"},
excludeFilters = {#ComponentScan.Filter(type = FilterType.ANNOTATION, value = EnableWebMvc.class)})
#PropertySource("classpath:app.properties")
#EnableTransactionManagement
public class RootConfig {
#Value("${db.driverClassName}")
private String driver;
#Value("${db.url}")
private String url;
#Value("${db.username}")
private String username;
#Value("${db.password}")
private String password;
#Bean
public BasicDataSource dataSource() {
BasicDataSource ds = new BasicDataSource();
ds.setDriverClassName(driver);
ds.setUrl(url);
ds.setUsername(username);
ds.setPassword(password);
ds.setInitialSize(3);
ds.setMaxActive(6);
return ds;
}
#Bean
public LocalSessionFactoryBean sessionFactory(DataSource dataSource) {
LocalSessionFactoryBean sfb = new LocalSessionFactoryBean();
sfb.setDataSource(dataSource);
sfb.setPackagesToScan("temporaryApp");
Properties props = new Properties();
props.setProperty("hibernate.dialect", "org.hibernate.dialect.MySQL5Dialect");
sfb.setHibernateProperties(props);
return sfb;
}
#Bean
public HibernateTransactionManager transactionManager() {
HibernateTransactionManager transactionManager = new HibernateTransactionManager();
transactionManager.setSessionFactory(sessionFactory(dataSource()).getObject());
return transactionManager;
}
}
WebAppInitializer
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer;
#Configuration
public class WebAppInitializer extends AbstractAnnotationConfigDispatcherServletInitializer {
#Override
protected String[] getServletMappings() {
return new String[]{"/"};
}
#Override
protected Class<?>[] getRootConfigClasses() {
return new Class<?>[]{RootConfig.class};
}
#Override
protected Class<?>[] getServletConfigClasses() {
return new Class<?>[]{WebConfig.class};
}
}
IndexController
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import temporaryApp.model.Message;
#Controller
#RequestMapping(value = "/")
public class IndexController {
#GetMapping
public String index(Model model) {
model.addAttribute(new Message());
return "index";
}
}
SaveController
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import temporaryApp.dao.Dao;
import temporaryApp.model.Message;
#Controller
#RequestMapping(value = "/save")
public class SaveController {
private Dao dao;
#PostMapping
public String save(#ModelAttribute ("message") Message message, Model model) {
dao.saveMessage(message);
model.addAttribute(new Message());
return "index";
}
#Autowired
public SaveController(Dao dao) {
this.dao = dao;
}
}
Dao
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;
import temporaryApp.model.Message;
import java.io.Serializable;
#Repository
#Transactional(value = "transactionManager")
public class Dao {
private final SessionFactory sessionFactory;
public void saveMessage(Message message) {
Serializable id = currentSession().save(message);
}
#Autowired
public Dao(SessionFactory sessionFactory) {
this.sessionFactory = sessionFactory;
}
private Session currentSession() {
return sessionFactory.getCurrentSession();
}
}
Message
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
#Entity
public class Message {
#Id
#GeneratedValue
private int id;
private String text;
public String getText() {
return text;
}
public void setText(String text) {
this.text = text;
}
}
Exception
org.springframework.web.util.NestedServletException: Request processing failed; nested exception is org.hibernate.exception.SQLGrammarException: error performing isolated work
org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:982)
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.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
root cause
org.hibernate.exception.SQLGrammarException: error performing isolated work
org.hibernate.exception.internal.SQLExceptionTypeDelegate.convert(SQLExceptionTypeDelegate.java:63)
org.hibernate.exception.internal.StandardSQLExceptionConverter.convert(StandardSQLExceptionConverter.java:42)
org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:111)
org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:97)
org.hibernate.resource.transaction.backend.jdbc.internal.JdbcIsolationDelegate.delegateWork(JdbcIsolationDelegate.java:79)
org.hibernate.id.enhanced.TableStructure$1.getNextValue(TableStructure.java:125)
org.hibernate.id.enhanced.NoopOptimizer.generate(NoopOptimizer.java:40)
org.hibernate.id.enhanced.SequenceStyleGenerator.generate(SequenceStyleGenerator.java:432)
org.hibernate.event.internal.AbstractSaveEventListener.saveWithGeneratedId(AbstractSaveEventListener.java:105)
org.hibernate.event.internal.DefaultSaveOrUpdateEventListener.saveWithGeneratedOrRequestedId(DefaultSaveOrUpdateEventListener.java:192)
org.hibernate.event.internal.DefaultSaveEventListener.saveWithGeneratedOrRequestedId(DefaultSaveEventListener.java:38)
org.hibernate.event.internal.DefaultSaveOrUpdateEventListener.entityIsTransient(DefaultSaveOrUpdateEventListener.java:177)
org.hibernate.event.internal.DefaultSaveEventListener.performSaveOrUpdate(DefaultSaveEventListener.java:32)
org.hibernate.event.internal.DefaultSaveOrUpdateEventListener.onSaveOrUpdate(DefaultSaveOrUpdateEventListener.java:73)
org.hibernate.internal.SessionImpl.fireSave(SessionImpl.java:682)
org.hibernate.internal.SessionImpl.save(SessionImpl.java:674)
org.hibernate.internal.SessionImpl.save(SessionImpl.java:669)
temporaryApp.dao.Dao.saveMessage(Dao.java:19)
temporaryApp.dao.Dao$$FastClassBySpringCGLIB$$e28af538.invoke(<generated>)
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.transaction.interceptor.TransactionInterceptor$1.proceedWithInvocation(TransactionInterceptor.java:99)
org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:282)
org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:96)
org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
org.springframework.aop.framework.CglibAopProxy$DynamicAdvisedInterceptor.intercept(CglibAopProxy.java:655)
temporaryApp.dao.Dao$$EnhancerBySpringCGLIB$$efb69a17.saveMessage(<generated>)
temporaryApp.controllers.SaveController.save(SaveController.java:20)
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:220)
org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:134)
org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:116)
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.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
root cause
com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: Table 'hibernate.hibernate_sequence' doesn't exist
sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
java.lang.reflect.Constructor.newInstance(Constructor.java:423)
com.mysql.jdbc.Util.handleNewInstance(Util.java:404)
com.mysql.jdbc.Util.getInstance(Util.java:387)
com.mysql.jdbc.SQLError.createSQLException(SQLError.java:942)
com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3966)
com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3902)
com.mysql.jdbc.MysqlIO.sendCommand(MysqlIO.java:2526)
com.mysql.jdbc.MysqlIO.sqlQueryDirect(MysqlIO.java:2673)
com.mysql.jdbc.ConnectionImpl.execSQL(ConnectionImpl.java:2549)
com.mysql.jdbc.PreparedStatement.executeInternal(PreparedStatement.java:1861)
com.mysql.jdbc.PreparedStatement.executeQuery(PreparedStatement.java:1962)
org.apache.commons.dbcp.DelegatingPreparedStatement.executeQuery(DelegatingPreparedStatement.java:96)
org.apache.commons.dbcp.DelegatingPreparedStatement.executeQuery(DelegatingPreparedStatement.java:96)
org.hibernate.id.enhanced.TableStructure.executeQuery(TableStructure.java:216)
org.hibernate.id.enhanced.TableStructure.access$300(TableStructure.java:46)
org.hibernate.id.enhanced.TableStructure$1$1.execute(TableStructure.java:138)
org.hibernate.id.enhanced.TableStructure$1$1.execute(TableStructure.java:126)
org.hibernate.jdbc.WorkExecutor.executeReturningWork(WorkExecutor.java:55)
org.hibernate.jdbc.AbstractReturningWork.accept(AbstractReturningWork.java:34)
org.hibernate.resource.transaction.backend.jdbc.internal.JdbcIsolationDelegate.delegateWork(JdbcIsolationDelegate.java:57)
org.hibernate.id.enhanced.TableStructure$1.getNextValue(TableStructure.java:125)
org.hibernate.id.enhanced.NoopOptimizer.generate(NoopOptimizer.java:40)
org.hibernate.id.enhanced.SequenceStyleGenerator.generate(SequenceStyleGenerator.java:432)
org.hibernate.event.internal.AbstractSaveEventListener.saveWithGeneratedId(AbstractSaveEventListener.java:105)
org.hibernate.event.internal.DefaultSaveOrUpdateEventListener.saveWithGeneratedOrRequestedId(DefaultSaveOrUpdateEventListener.java:192)
org.hibernate.event.internal.DefaultSaveEventListener.saveWithGeneratedOrRequestedId(DefaultSaveEventListener.java:38)
org.hibernate.event.internal.DefaultSaveOrUpdateEventListener.entityIsTransient(DefaultSaveOrUpdateEventListener.java:177)
org.hibernate.event.internal.DefaultSaveEventListener.performSaveOrUpdate(DefaultSaveEventListener.java:32)
org.hibernate.event.internal.DefaultSaveOrUpdateEventListener.onSaveOrUpdate(DefaultSaveOrUpdateEventListener.java:73)
org.hibernate.internal.SessionImpl.fireSave(SessionImpl.java:682)
org.hibernate.internal.SessionImpl.save(SessionImpl.java:674)
org.hibernate.internal.SessionImpl.save(SessionImpl.java:669)
temporaryApp.dao.Dao.saveMessage(Dao.java:19)
temporaryApp.dao.Dao$$FastClassBySpringCGLIB$$e28af538.invoke(<generated>)
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.transaction.interceptor.TransactionInterceptor$1.proceedWithInvocation(TransactionInterceptor.java:99)
org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:282)
org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:96)
org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
org.springframework.aop.framework.CglibAopProxy$DynamicAdvisedInterceptor.intercept(CglibAopProxy.java:655)
temporaryApp.dao.Dao$$EnhancerBySpringCGLIB$$efb69a17.saveMessage(<generated>)
temporaryApp.controllers.SaveController.save(SaveController.java:20)
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:220)
org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:134)
org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:116)
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.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
So, what am I doing wrong?
You didn't defined any strategy to your generated id for message.
By default, Hibernate will check on your database to find any sequence or strategy to generate values. Try this :
#GeneratedValue(strategy = GenerationType.IDENTITY)
I try to develop some server program using spring4 and jackrabbit. When i test the Controller class using JUnit, BeanCreationExceptrion error is occurs. I think this error associated with autowired variable. help me. how to solve this problem?
This is head of my Controller class.
package kr.ac.jbnu.sql.soremore.controller;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import javax.jcr.Node;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import kr.ac.jbnu.sql.soremore.model.RDML;
import kr.ac.jbnu.sql.soremore.model.Traceability;
import kr.ac.jbnu.sql.soremore.service.IRDMLConverter;
import kr.ac.jbnu.sql.soremore.service.IRDMLDBMgmt;
import kr.ac.jbnu.sql.soremore.service.IRDMLRDFMgmt;
import kr.ac.jbnu.sql.soremore.service.RDMLDBException;
import kr.ac.jbnu.sql.soremore.service.RDMLRDFException;
import kr.ac.jbnu.sql.soremore.service.RevisionControlException;
import kr.ac.jbnu.sql.soremore.service.rdf.RDFConverter;
import org.apache.log4j.Logger;
import org.jdom2.Document;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;
import com.hp.hpl.jena.rdf.model.Model;
import com.hp.hpl.jena.rdf.model.Property;
import com.hp.hpl.jena.rdf.model.Resource;
// reference
// http://crunchify.com/simplest-spring-mvc-hello-world-example-tutorial-spring-model-view-controller-tips/
#Controller
public class SoremoreController {
private static final int buffer_size = 1024;
static Logger logger = Logger.getLogger(SoremoreController.class.getName());
private static String fileName = "";
#Autowired
private ApplicationContext appContext = null;
#Autowired
private IRDMLConverter rdmlConverter = null;
#Autowired
private IRDMLRDFMgmt rdmlRDFMgmt = null;
#Autowired
private IRDMLDBMgmt rdmlDBMgmt = null;
#Autowired
private RDFConverter rdfConverter = null;
....
This is my test class.
package kr.ac.jbnu.sql.soremore.controller;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import kr.ac.jbnu.sql.soremore.model.RDML;
import kr.ac.jbnu.sql.soremore.model.Traceability;
import kr.ac.jbnu.sql.soremore.service.RDMLDBException;
import org.jdom2.Document;
import org.jdom2.JDOMException;
import org.jdom2.input.SAXBuilder;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.AbstractJUnit4SpringContextTests;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
#RunWith(SpringJUnit4ClassRunner.class)
//#ContextConfiguration(locations = { "classpath:/soremore-servlet.xml" })
#ContextConfiguration(locations = { "/application-config.xml" })
public class SoremoreControllerTest {
#Autowired
SoremoreController soremoreController = null;
#Test
public void storeRDML() {
// String[] hwpmlPaths = { "resource/sample_rdml/예제 1.xml",
// "resource/sample_rdml/예제 2.xml",
// "resource/sample_rdml/예제 3.xml",
// "resource/sample_rdml/예제 4.xml",
// "resource/sample_rdml/예제 5.xml",
// "resource/sample_rdml/예제 6.xml",
// "resource/sample_rdml/예제 7.xml",
// "resource/sample_rdml/예제 8.xml",
// "resource/sample_rdml/예제 9.xml",
// "resource/sample_rdml/예제 10.xml" };
//
// for (String hwpmlPath : hwpmlPaths) {
// soremoreController.storeRDML(hwpmlPath);
// }
ArrayList<RDML> rdmls = loadTestRDML();
boolean isSuccessful = false;
for (RDML rdml : rdmls) {
try {
soremoreController.storeRDML(rdml);
System.out.println();
isSuccessful = true;
} catch (Exception e) {
e.printStackTrace();
isSuccessful = false;
}
}
Assert.assertTrue(isSuccessful);
}
#Test
public void storeRDMLWithTraceability() throws IOException {
List<RDML>rdmls = null ;
String previousRDMLId = "xxx";
for (RDML rdml : rdmls) {
soremoreController.storeRDMLWithTraceability(rdml,
previousRDMLId, TraceabilityTypes.satisfy);
}
}
#Test
public void updateRDMLWithTraceability() {
String previousRDMLId1 = "xxx";
String previousRDMLId2 = "xxx";
String updatedTraceability = soremoreController.updateRDMLTraceability(
previousRDMLId1, previousRDMLId2, TraceabilityTypes.satisfy);
}
#Test
public void deleteRDMLWithTraceability() {
String previousRDMLId1 = "xxx";
String previousRDMLId2 = "xxx";
String removedTraceability = soremoreController.deleteRDMLTraceability(
previousRDMLId1, previousRDMLId2);
}
#Test
public void searchRDML() {
String rdmlKeyWord = "abc";
ArrayList<RDML> rdmls = soremoreController.searchRDML(rdmlKeyWord);
for (RDML rdml : rdmls) {
System.out.println(rdml);
}
}
#Test
public void searchRDML0() {
String rdmlKeyWord = "def";
ArrayList<RDML> rdmls = soremoreController.searchRDML(rdmlKeyWord);
for (RDML rdml : rdmls) {
System.out.println(rdml);
}
}
#Test
public void searchRDML1() {
String rdmlKeyWord = "2차년도계획서";
ArrayList<RDML> rdmls = soremoreController.searchRDML(rdmlKeyWord);
for (RDML rdml : rdmls) {
System.out.println(rdml);
}
}
#Test
public void getRDML() {
String rdmlID = "abc";
RDML rdml = soremoreController.getRDML(rdmlID);
}
#Test
public void getParentIDs() {
String rdmlID = "abcd";
ArrayList<String> parentIDs = soremoreController.getParentIDs(rdmlID);
for (String string : parentIDs) {
}
}
#Test
public void getChildIDs() {
String rdmlID = "abcd";
ArrayList<String> childIDs = soremoreController.getChildIDs(rdmlID);
for (String string : childIDs) {
}
}
public void getDirectLinkedTraceability() {
String rdmlID = "abcd";
ArrayList<Traceability> linkedTraceabilities = soremoreController
.getDirectLinkedTraceability(rdmlID);
for (Traceability traceability : linkedTraceabilities) {
}
}
public ArrayList<RDML> loadTestRDML() {
ArrayList<RDML> rdmls = new ArrayList<RDML>();
String xmlSource = "resource/sample_rdml";
File sourceDir = new File(xmlSource);
File[] sourceFiles = sourceDir.listFiles();
for (File file : sourceFiles) {
RDML rdml = new RDML();
rdml.setRdmlAsDocument(createDocument(file));
rdmls.add(rdml);
}
return rdmls;
}
private Document createDocument(File rdmlPathAsFile) {
SAXBuilder jdomBuilder = new SAXBuilder();
Document jdomDocument = null;
try {
jdomDocument = jdomBuilder.build(rdmlPathAsFile);
} catch (JDOMException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return jdomDocument;
}
}
This is my spring configuration xml file.
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-4.0.xsd">
<context:component-scan base-package="kr.ac.jbnu.sql.soremore" />
<bean id="viewResolver"
class="org.springframework.web.servlet.view.UrlBasedViewResolver">
<property name="viewClass"
value="org.springframework.web.servlet.view.JstlView" />
<property name="prefix" value="/WEB-INF/jsp/" />
<property name="suffix" value=".jsp" />
<property name="contentType" value="text/html; charset=UTF-8" />
</bean>
<!-- for file upload -->
<bean id="multipartResolver"
class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<!-- setting maximum upload size -->
<property name="maxUploadSize" value="20000000" />
</bean>
</beans>
This is head of class of one variable.
package kr.ac.jbnu.sql.soremore.service.rdml;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import javax.jcr.Node;
import javax.jcr.NodeIterator;
import javax.jcr.PathNotFoundException;
import javax.jcr.Repository;
import javax.jcr.RepositoryException;
import javax.jcr.Session;
import javax.jcr.SimpleCredentials;
import javax.jcr.UnsupportedRepositoryOperationException;
import javax.jcr.ValueFormatException;
import javax.jcr.lock.LockException;
import javax.jcr.nodetype.ConstraintViolationException;
import javax.jcr.nodetype.NoSuchNodeTypeException;
import javax.jcr.query.Query;
import javax.jcr.query.QueryManager;
import javax.jcr.query.QueryResult;
import javax.jcr.version.Version;
import javax.jcr.version.VersionException;
import javax.jcr.version.VersionHistory;
import javax.jcr.version.VersionIterator;
import javax.jcr.version.VersionManager;
import javax.xml.parsers.ParserConfigurationException;
import kr.ac.jbnu.sql.soremore.controller.SoremoreController;
import kr.ac.jbnu.sql.soremore.model.RDML;
import kr.ac.jbnu.sql.soremore.service.IRDMLDBMgmt;
import kr.ac.jbnu.sql.soremore.service.RDMLDBException;
import kr.ac.jbnu.sql.soremore.service.RevisionControlException;
import org.apache.jackrabbit.commons.JcrUtils;
import org.apache.log4j.Logger;
import org.jdom2.Attribute;
import org.jdom2.Document;
import org.jdom2.Element;
import org.jdom2.output.XMLOutputter;
import org.springframework.stereotype.Service;
#Service
public class RDMLDBMgmtImpl implements IRDMLDBMgmt {
static Logger logger = Logger.getLogger(SoremoreController.class.getName());
static private int docNumber = 0;
private Repository repository;
private Session session;
....
This is stacktrace.
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'kr.ac.jbnu.sql.soremore.controller.SoremoreControllerTest': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: kr.ac.jbnu.sql.soremore.controller.SoremoreController kr.ac.jbnu.sql.soremore.controller.SoremoreControllerTest.soremoreController; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [kr.ac.jbnu.sql.soremore.controller.SoremoreController] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {#org.springframework.beans.factory.annotation.Autowired(required=true)}
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:334)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1204)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.autowireBeanProperties(AbstractAutowireCapableBeanFactory.java:385)
at org.springframework.test.context.support.DependencyInjectionTestExecutionListener.injectDependencies(DependencyInjectionTestExecutionListener.java:117)
at org.springframework.test.context.support.DependencyInjectionTestExecutionListener.prepareTestInstance(DependencyInjectionTestExecutionListener.java:82)
at org.springframework.test.context.TestContextManager.prepareTestInstance(TestContextManager.java:212)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.createTest(SpringJUnit4ClassRunner.java:199)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner$1.runReflectiveCall(SpringJUnit4ClassRunner.java:251)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.methodBlock(SpringJUnit4ClassRunner.java:253)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:216)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:82)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:238)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:63)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:236)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:53)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:229)
at org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:60)
at org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:67)
at org.junit.runners.ParentRunner.run(ParentRunner.java:309)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:162)
at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:50)
at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:459)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:675)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:382)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:192)
Caused by: org.springframework.beans.factory.BeanCreationException: Could not autowire field: kr.ac.jbnu.sql.soremore.controller.SoremoreController kr.ac.jbnu.sql.soremore.controller.SoremoreControllerTest.soremoreController; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [kr.ac.jbnu.sql.soremore.controller.SoremoreController] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {#org.springframework.beans.factory.annotation.Autowired(required=true)}
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:555)
at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:87)
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:331)
... 26 more
Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [kr.ac.jbnu.sql.soremore.controller.SoremoreController] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {#org.springframework.beans.factory.annotation.Autowired(required=true)}
at org.springframework.beans.factory.support.DefaultListableBeanFactory.raiseNoSuchBeanDefinitionException(DefaultListableBeanFactory.java:1261)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1009)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:904)
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:527)
... 28 more
In order for Spring to autowire the SoremoreController field in your test case it needs a bean definition in the ApplicationContext for a bean of that type. That means you need to component-scan the package (or a parent package) where the SoremoreController is defined in the xml file you point out in the ContextConfiguration annotation.
Note that all autowired fields in SoremoreController instance must also have corresponding beans defined in the ApplicationContext, otherwise Spring will not be able to create that instance, causing your test to fail with stacktraces similar to the one you posted (but always explicitly pointing out - towards the end - the root cause of the problem).
The following is my HibernateUtil class:
package Hibernate.util;
import org.hibernate.cfg.AnnotationConfiguration;
import org.hibernate.SessionFactory;
public class HibernateUtil {
private static final SessionFactory sessionFactory;
static {
try {
// Create the SessionFactory from standard (hibernate.cfg.xml)
// config file.
sessionFactory = new AnnotationConfiguration().configure().buildSessionFactory();
} catch (Throwable ex) {
// Log the exception.
System.err.println("Initial SessionFactory creation failed." + ex);
throw new ExceptionInInitializerError(ex);
}
}
public static SessionFactory getSessionFactory() {
return sessionFactory;
}
}
My controller:
package Controllers;
import DAOImpl.ProductDAOImpl;
import Entities.Product;
import java.sql.SQLException;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
#Controller
public class ProductController {
#RequestMapping("/products.htm")
public String getAllProducts() throws SQLException
{
ProductDAOImpl mapping = new ProductDAOImpl();
Product p = new Product();
p.setCost(1000);
p.setName("Саморезы");
mapping.addProduct(p);
return "index";
}
}
But when I run web-app I have excpetion:
java.lang.NoClassDefFoundError: Could not initialize class Hibernate.util.HibernateUtil
DAOImpl.ProductDAOImpl.addProduct(ProductDAOImpl.java:24)
Controllers.ProductController.getAllProducts(ProductController.java:20)
sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
java.lang.reflect.Method.invoke(Method.java:606)
org.springframework.web.bind.annotation.support.HandlerMethodInvoker.invokeHandlerMethod(HandlerMethodInvoker.java:175)
org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter.invokeHandlerMethod(AnnotationMethodHandlerAdapter.java:446)
org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter.handle(AnnotationMethodHandlerAdapter.java:434)
org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:945)
org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:876)
org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:961)
org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:852)
javax.servlet.http.HttpServlet.service(HttpServlet.java:620)
org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:837)
javax.servlet.http.HttpServlet.service(HttpServlet.java:727)
org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52
Any Idea?
Might HibernateUtil must be registered in any place?
i think you don't have mysql-connector.jar in your Classpath
This class first of all must be on your classpath. And then make sure that ProductDAOImpl ge the sessionFactory(to eventually provide the session) via HibernateUtil.getSessionFactory().
You are anyway free to define this class as a bean in you application context if you like to do so.