java.lang.NoClassDefFoundError: Could not initialize class Hibernate.util.HibernateUtil - java

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.

Related

SEVERE: Allocate exception for servlet [dispatcher] org.springframework.beans.factory.NoSuchBeanDefinitionException:

I have expanda.js. I am calling this dao in my formcontroller.java file but I get the following error.
I guess I need to define DAO as a bean. How can I do this in the SpringWebConfig.java file?
I do not have much control over spring, sorry
Console Error:
SEVERE: Allocate exception for servlet [dispatcher]
org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'com.esma.dao.ExpDao' available: expected
at least 1 bean which qualifies as autowire candidate. Dependency
annotations:
{#org.springframework.beans.factory.annotation.Autowired(required=true)}
at org.springframework.beans.factory.support.DefaultListableBeanFactory.raiseNoMatchingBeanFound(DefaultListableBeanFactory.java:1777)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1333)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:1287)
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:640)
at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:130)
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessProperties(AutowiredAnnotationBeanPostProcessor.java:399)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1415)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:608)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:531)
at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:335)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:234)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:333)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:208)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:944)
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:925)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:588)
at org.springframework.web.servlet.FrameworkServlet.configureAndRefreshWebApplicationContext(FrameworkServlet.java:702)
at org.springframework.web.servlet.FrameworkServlet.initWebApplicationContext(FrameworkServlet.java:578)
at org.springframework.web.servlet.FrameworkServlet.initServletBean(FrameworkServlet.java:530)
at org.springframework.web.servlet.HttpServletBean.init(HttpServletBean.java:170)
at javax.servlet.GenericServlet.init(GenericServlet.java:158)
at org.apache.catalina.core.StandardWrapper.initServlet(StandardWrapper.java:1134)
at org.apache.catalina.core.StandardWrapper.allocate(StandardWrapper.java:777)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:135)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:97)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:541)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:143)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:92)
at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:690)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:78)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:343)
at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:374)
at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:65)
at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:868)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1590)
at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49)
at java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1128)
at java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:628)
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
at java.base/java.lang.Thread.run(Thread.java:830)
ExpDao.java
package com.esma.dao;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import com.esma.model.Expense;
public class ExpDao {
JdbcTemplate template;
public void setTemplate(JdbcTemplate template) {
this.template = template;
}
public int save(Expense exp){
String sql="insert into Emp99(name,salary,designation) values('"+exp.getExpenseType()+"',"+exp.getQuantity()+","+exp.getPrice()+","+exp.getPaymentDate()+",'"+exp.getNote()+"' )";
return template.update(sql);
}
public List<Expense> getExpenses(){
return template.query("select * from expenses",new RowMapper<Expense>(){
public Expense mapRow(ResultSet result, int row) throws SQLException {
Expense e=new Expense();
e.setExpenseType(result.getString(2));
e.setQuantity(result.getInt(3));
e.setPrice(result.getInt(4));
e.setPaymentDate(result.getDate(5));
e.setNote(result.getString(6));
return e;
}
});
}
}
SpringRootConfig.js
package com.esma.config;
import org.apache.commons.dbcp2.BasicDataSource;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
#Configuration
#ComponentScan(basePackages ={"com.esma.dao"})
public class SpringRootConfig {
//TODO: Services, DAO, DataSource, Email Sender or some other business layer beans.
// In production the datasource configuration is done in properties file but for simplicity purpose it is hardcoded here.
#Bean
public BasicDataSource getDataSource(){
BasicDataSource ds = new BasicDataSource();
ds.setDriverClassName("com.mysql.jdbc.Driver");
ds.setUrl("jdbc:mysql://localhost:3306/apartmentmanagement");
ds.setUsername("root");
ds.setPassword("1234");
ds.setMaxTotal(2);
ds.setInitialSize(1);
ds.setTestOnBorrow(true);
ds.setValidationQuery("SELECT 1");
ds.setDefaultAutoCommit(true);
return ds;
}
}
SpringWebConfig.js
/**
*
*/
package com.esma.config;
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.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
import org.springframework.web.servlet.view.InternalResourceViewResolver;
import org.springframework.web.servlet.view.JstlView;
import com.esma.dao.ExpDao;
import com.esma.model.Expense;
#Configuration
#ComponentScan(basePackages = { "com.esma" })
#EnableWebMvc
public class SpringWebConfig implements WebMvcConfigurer {
#Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
// TODO Auto-generated method stub
System.out.println("Inside Resource Handler");
registry.addResourceHandler("/static/**").addResourceLocations("/static/");
}
#Bean
public ViewResolver viewResolver() {
InternalResourceViewResolver vr = new InternalResourceViewResolver();
vr.setViewClass(JstlView.class);
vr.setPrefix("/WEB-INF/view/");
vr.setSuffix(".jsp");
return vr;
}
#Bean
public ExpDao expenceDao() {
ExpDao exp = new ExpDao();
exp.setTemplate(com.esma.dao.ExpDao.class);
return exp;
}
}
FormController.js
package com.esma.controller;
import java.util.List;
import javax.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;
import com.esma.dao.ExpDao;
import com.esma.model.Expense;
#Controller
public class FormController {
#Autowired
ExpDao dao;
#RequestMapping(value = "/form", method = RequestMethod.GET)
public String form() {
new ModelAndView("expense", "expenseObject", new Expense());
return "expenseForm";// JSP form view
}
#RequestMapping(value = "/expense/save", method = RequestMethod.POST)
public String addExpense(#ModelAttribute("expenseObject") Expense expense, ModelMap model) {
dao.save(expense);
model.addAttribute("expenseType", expense.getExpenseType());
model.addAttribute("quantity", expense.getQuantity());
model.addAttribute("price", expense.getPrice());
model.addAttribute("paymentDate", expense.getPaymentDate());
model.addAttribute("note", expense.getNote());
System.out.println(model.getAttribute("expenseType"));
System.out.println(model.getAttribute("quantity"));
System.out.println(model.getAttribute("price"));
System.out.println(model.getAttribute("paymentDate"));
System.out.println(model.getAttribute("note"));
return "result";
}
#RequestMapping(value = "/list")
public String expenseList(Model m) {
List<Expense> list = dao.getExpenses();
m.addAttribute("list", list);
System.out.println("expense");
return "expenseList";// JSP form view
}
}
Hello Esma and welcome to stackoverflow.
Since you declared explecitely your bean of type ExpDao with #Bean annotation in the SpringWebConfig.js, The bean registred in the spring context is expenceDao which is the same method name in this code section:
#Bean
public ExpDao expenceDao() {
ExpDao exp = new ExpDao();
exp.setTemplate(com.esma.dao.ExpDao.class);
return exp;
}
So Spring container will create and register a bean of type ExpDao with name (or id ) expenceDao (which is the name of the method expenceDao()
and then you ask spring with this section of code to inject a bean with name expDao which is not found.
#Controller
public class FormController {
#Autowired
ExpDao dao;
// the rest of the code
}
So spring will return a NoSuchBeanDefinitionException because it didn't found a bean with name expDao.
In order to work, you can just change the method name expenceDao() to expDao() in SpringWebConfig.java file in order that spring create the bean with name expDao and not expenceDao.
Thanks.

Integrating Spring MVC 4 and Hibernate 5 [duplicate]

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)

Null pointer exception using powermock with mockito

I am trying to write a JUnit test case with Powermock and Mockito. I am calling a method from below test case. This method inturn calls from method1 and that call method2. I have already added #RunWith and #PrepareForTest annotations.
//this my test class:
package com.company.Abc.helpdesk.service;
import static org.junit.Assert.*;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.AnnotationConfiguration;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mockito;
import org.powermock.api.mockito.PowerMockito;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;
import com.company.vtest.login.dao.AbcDAO;
import com.company.vtest.login.entity.Login;
import static org.mockito.Mockito.*;
import static org.powermock.api.mockito.PowerMockito.when;
/**
* #author Joginder
*
*/
#RunWith(PowerMockRunner.class)
#PrepareForTest({ Session.class })
public class AdminServicesTestNikhil {
#Test
public void testRegisterNewAdmin() {
// Declare variables to be passed as params
Login rna = new Login(8005, "admin");
// Mock classes
AbcDAO mockDAO = mock(AbcDAO.class);
PowerMockito.mockStatic(Session.class);
// Mock method calls
when(AbcDAO.getSession()).thenReturn(any(Session.class));
// Call test method
AdminServices adminServices = new AdminServices();
assertEquals(adminServices.registerNewAdmin(rna), 0);
// Verify method calls
// Verify results
fail("Not yet implemented");
}
}
//here is the private method:
private static SessionFactory buildSessionFactory() {
// build session factory;
// Read from cfg
SessionFactory sessionFactory;
sessionFactory = new AnnotationConfiguration()
.addAnnotatedClass(com.company.Abc.login.entity.Login.class)
.addAnnotatedClass(
com.company.Abc.assessment.entity.CreatedAsmnt.class)
.addAnnotatedClass(
com.company.Abc.assessment.entity.QuesPerAsmnt.class)
.addAnnotatedClass(
com.company.Abc.assessment.entity.AnsOptions.class)
.addAnnotatedClass(
com.company.Abc.assessment.entity.TestTaker.class)
.addAnnotatedClass(
com.company.Abc.question.entity.QuestionBank.class)
.addAnnotatedClass(
com.company.Abc.question.entity.QuestionDetails.class)
.addAnnotatedClass(
com.company.Abc.question.entity.AnswerDetails.class)
.addAnnotatedClass(
com.company.Abc.assessment.entity.PanelRetrieval.class)
.addAnnotatedClass(
com.company.Abc.assessment.entity.ViewQA.class)
.addAnnotatedClass(
com.company.Abc.question.entity.Master.class)
.addAnnotatedClass(
com.company.Abc.question.entity.MasterT.class)
.addAnnotatedClass(
com.company.vtest.question.entity.MasterForm.class)
.addAnnotatedClass(ResultAnnotated.class)
.addAnnotatedClass(Candidate.class)
.addAnnotatedClass(AssessmentTaken.class)
.addAnnotatedClass(Section.class)
.addAnnotatedClass(SelTechInfo.class)
.addAnnotatedClass(AsmntSchedule.class).configure()
.buildSessionFactory();
return sessionFactory;
}
error trace:
java.lang.NullPointerException
at com.company.Abc.login.dao.AbcDAO.getSession(AbcDAO.java:83)
at com.company.Abc.helpdesk.service.AdminServicesTest.testRegisterNewAdmin(AdminServicesTest.java:54)
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 org.junit.internal.runners.TestMethod.invoke(TestMethod.java:66)
at org.powermock.modules.junit4.internal.impl.PowerMockJUnit44RunnerDelegateImpl$PowerMockJUnit44MethodRunner.runTestMethod(PowerMockJUnit44RunnerDelegateImpl.java:310)
at org.junit.internal.runners.MethodRoadie$2.run(MethodRoadie.java:86)
at org.junit.internal.runners.MethodRoadie.runBeforesThenTestThenAfters(MethodRoadie.java:94)
at org.powermock.modules.junit4.internal.impl.PowerMockJUnit44RunnerDelegateImpl$PowerMockJUnit44MethodRunner.executeTest(PowerMockJUnit44RunnerDelegateImpl.java:294)
at org.powermock.modules.junit4.internal.impl.PowerMockJUnit47RunnerDelegateImpl$PowerMockJUnit47MethodRunner.executeTestInSuper(PowerMockJUnit47RunnerDelegateImpl.java:127)
at org.powermock.modules.junit4.internal.impl.PowerMockJUnit47RunnerDelegateImpl$PowerMockJUnit47MethodRunner.executeTest(PowerMockJUnit47RunnerDelegateImpl.java:82)
at org.powermock.modules.junit4.internal.impl.PowerMockJUnit44RunnerDelegateImpl$PowerMockJUnit44MethodRunner.runBeforesThenTestThenAfters(PowerMockJUnit44RunnerDelegateImpl.java:282)
at org.junit.internal.runners.MethodRoadie.runTest(MethodRoadie.java:84)
at org.junit.internal.runners.MethodRoadie.run(MethodRoadie.java:49)
at org.powermock.modules.junit4.internal.impl.PowerMockJUnit44RunnerDelegateImpl.invokeTestMethod(PowerMockJUnit44RunnerDelegateImpl.java:207)
at org.powermock.modules.junit4.internal.impl.PowerMockJUnit44RunnerDelegateImpl.runMethods(PowerMockJUnit44RunnerDelegateImpl.java:146)
at org.powermock.modules.junit4.internal.impl.PowerMockJUnit44RunnerDelegateImpl$1.run(PowerMockJUnit44RunnerDelegateImpl.java:120)
at org.junit.internal.runners.ClassRoadie.runUnprotected(ClassRoadie.java:34)
at org.junit.internal.runners.ClassRoadie.runProtected(ClassRoadie.java:44)
at org.powermock.modules.junit4.internal.impl.PowerMockJUnit44RunnerDelegateImpl.run(PowerMockJUnit44RunnerDelegateImpl.java:122)
at org.powermock.modules.junit4.common.internal.impl.JUnit4TestSuiteChunkerImpl.run(JUnit4TestSuiteChunkerImpl.java:106)
at org.powermock.modules.junit4.common.internal.impl.AbstractCommonPowerMockRunner.run(AbstractCommonPowerMockRunner.java:53)
at org.powermock.modules.junit4.PowerMockRunner.run(PowerMockRunner.java:59)
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:467)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:683)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:390)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:197)
Instead of when(AbcDAO.getSession()).thenReturn(any(Session.class));, do
Session mockedSession = mock(Session.class);
when(AbcDAO.getSession()).thenReturn(mockedSession);
any() is just a pattern matcher. mock() will create a mock object using the given class.
Session mockSession = mock(Session.class);
// Mock a static method as below
PowerMockito.mockStatic(AbcDAO.class);
when(AbcDAO.getSession()).thenReturn(mockSession);
If you any method calls on session object in adminServices.registerNewAdmin()
set the required expectations on above mockSession object.
public class AbcDAO {
private static SessionFactory sessionFactory=null;
private static Session session;
public static Connection con = null;
private static SessionFactory buildSessionFactory() {
// build session factory;
// Read from cfg
SessionFactory sessionFactory;
sessionFactory = new AnnotationConfiguration()
.addAnnotatedClass(com.company.Abc.login.entity.Login.class)
.addAnnotatedClass(
com.company.Abc.assessment.entity.CreatedAsmnt.class)
.addAnnotatedClass(
com.company.Abc.assessment.entity.QuesPerAsmnt.class)
.addAnnotatedClass(
com.company.Abc.assessment.entity.AnsOptions.class)
.addAnnotatedClass(
com.company.Abc.assessment.entity.TestTaker.class)
.addAnnotatedClass(
com.company.Abc.question.entity.QuestionBank.class)
.addAnnotatedClass(
com.company.Abc.question.entity.QuestionDetails.class)
.addAnnotatedClass(
com.company.Abc.question.entity.AnswerDetails.class)
.addAnnotatedClass(
com.company.Abc.assessment.entity.PanelRetrieval.class)
.addAnnotatedClass(
com.company.Abc.assessment.entity.ViewQA.class)
.addAnnotatedClass(
com.company.Abc.question.entity.Master.class)
.addAnnotatedClass(
com.company.Abc.question.entity.MasterT.class)
.addAnnotatedClass(
com.company.vtest.question.entity.MasterForm.class)
.addAnnotatedClass(ResultAnnotated.class)
.addAnnotatedClass(Candidate.class)
.addAnnotatedClass(AssessmentTaken.class)
.addAnnotatedClass(Section.class)
.addAnnotatedClass(SelTechInfo.class)
.addAnnotatedClass(AsmntSchedule.class).configure()
.buildSessionFactory();
return sessionFactory;
}
static SessionFactory sessionFactory;
public static Session getSession() throws HibernateException {
// sessionFactory = AbcDAO.buildSessionFactory();
try {
if (sessionFactory != null)
session = sessionFactory.getCurrentSession();
else {
sessionFactory = AbcDAO.buildSessionFactory();
session = sessionFactory.openSession();
}
} catch (org.hibernate.HibernateException he) {
session = sessionFactory.openSession();
}
return session;
}
public void save(Object object) {
session.beginTransaction();
session.save(object);
session.close();
}

Invalid Object Name for Hibernate Sequence Generator

I am developing an application that accesses a database running SQL Server 2012 through the Hibernate framework. However, I cannot figure out how to make an instance of the SequenceGenerator annotation work; I get an exception whenever I attempt to save a new object instance to my database table. The class to be saved is the following:
import java.io.Serializable;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.SequenceGenerator;
import javax.persistence.Table;
#Entity
#Table(name="MESSAGES")
public class Message implements Serializable {
private static final long serialVersionUID = -3535373804021266134L;
#Id
#Column(name="MESSAGE_ID")
#GeneratedValue(strategy=GenerationType.SEQUENCE, generator="MESSAGE_GEN")
#SequenceGenerator(name="MESSAGE_GEN", sequenceName="MESSAGE_SEQ", initialValue=1, allocationSize=1)
private Long id;
#Column(name="TEXT")
private String text;
public Message(String text) {
this.text = text;
}
public Long getId() {
return id;
}
public String getText() {
return text;
}
}
An issue-provoking scenario could be the following transaction:
import org.hibernate.Session;
public class Manager {
public static void main(String[] args) {
Session session = Database.getSessionFactory().getCurrentSession();
session.beginTransaction();
Message message = new Message("Hello, World!");
session.save(message);
session.getTransaction().commit();
Database.getSessionFactory().close();
}
}
This results in the following stack trace related to the identifier sequence:
Exception in thread "main" org.hibernate.exception.SQLGrammarException: could not extract ResultSet
at org.hibernate.exception.internal.SQLStateConversionDelegate.convert(SQLStateConversionDelegate.java:123)
at org.hibernate.exception.internal.StandardSQLExceptionConverter.convert(StandardSQLExceptionConverter.java:49)
at org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:126)
at org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:112)
at org.hibernate.engine.jdbc.internal.ResultSetReturnImpl.extract(ResultSetReturnImpl.java:91)
at org.hibernate.id.SequenceGenerator.generateHolder(SequenceGenerator.java:122)
at org.hibernate.id.SequenceHiLoGenerator.generate(SequenceHiLoGenerator.java:73)
at org.hibernate.event.internal.AbstractSaveEventListener.saveWithGeneratedId(AbstractSaveEventListener.java:117)
at org.hibernate.event.internal.DefaultSaveOrUpdateEventListener.saveWithGeneratedOrRequestedId(DefaultSaveOrUpdateEventListener.java:209)
at org.hibernate.event.internal.DefaultSaveEventListener.saveWithGeneratedOrRequestedId(DefaultSaveEventListener.java:55)
at org.hibernate.event.internal.DefaultSaveOrUpdateEventListener.entityIsTransient(DefaultSaveOrUpdateEventListener.java:194)
at org.hibernate.event.internal.DefaultSaveEventListener.performSaveOrUpdate(DefaultSaveEventListener.java:49)
at org.hibernate.event.internal.DefaultSaveOrUpdateEventListener.onSaveOrUpdate(DefaultSaveOrUpdateEventListener.java:90)
at org.hibernate.internal.SessionImpl.fireSave(SessionImpl.java:715)
at org.hibernate.internal.SessionImpl.save(SessionImpl.java:707)
at org.hibernate.internal.SessionImpl.save(SessionImpl.java:702)
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 org.hibernate.context.internal.ThreadLocalSessionContext$TransactionProtectionWrapper.invoke(ThreadLocalSessionContext.java:356)
at com.sun.proxy.$Proxy8.save(Unknown Source)
at dk.radiometer.tests.hibernate.service.Manager.doTransaction(Manager.java:35)
at dk.radiometer.tests.hibernate.service.Manager.main(Manager.java:16)
Caused by: com.microsoft.sqlserver.jdbc.SQLServerException: Invalid object name 'MESSAGE_SEQ'.
at com.microsoft.sqlserver.jdbc.SQLServerException.makeFromDatabaseError(SQLServerException.java:216)
at com.microsoft.sqlserver.jdbc.SQLServerStatement.getNextResult(SQLServerStatement.java:1515)
at com.microsoft.sqlserver.jdbc.SQLServerPreparedStatement.doExecutePreparedStatement(SQLServerPreparedStatement.java:404)
at com.microsoft.sqlserver.jdbc.SQLServerPreparedStatement$PrepStmtExecCmd.doExecute(SQLServerPreparedStatement.java:350)
at com.microsoft.sqlserver.jdbc.TDSCommand.execute(IOBuffer.java:5696)
at com.microsoft.sqlserver.jdbc.SQLServerConnection.executeCommand(SQLServerConnection.java:1715)
at com.microsoft.sqlserver.jdbc.SQLServerStatement.executeCommand(SQLServerStatement.java:180)
at com.microsoft.sqlserver.jdbc.SQLServerStatement.executeStatement(SQLServerStatement.java:155)
at com.microsoft.sqlserver.jdbc.SQLServerPreparedStatement.executeQuery(SQLServerPreparedStatement.java:285)
at org.hibernate.engine.jdbc.internal.ResultSetReturnImpl.extract(ResultSetReturnImpl.java:82)
... 19 more
The issue seems related to the name of the sequence. My guess is that I need to manually create a sequence table of some sort for Hibernate to use, however, I do not know how to do this an have been unable to find a resource that seems related to my environment. If this is indeed the issue, please redirect me to some documentation for the protocol to follow. In addition, I am using the following programmatic Hibernate configuration:
import org.hibernate.SessionFactory;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;
public class Database {
private static final SessionFactory SESSION_FACTORY = buildSessionFactory();
private static SessionFactory buildSessionFactory() {
try {
Configuration cfg = buildConfiguration();
ServiceRegistry sr = new StandardServiceRegistryBuilder().applySettings(cfg.getProperties()).build();
SessionFactory sf = cfg.buildSessionFactory(sr);
return sf;
} catch (Throwable t) {
System.err.println("Initial SessionFactory creation failed: " + t);
throw new ExceptionInInitializerError(t);
}
}
private static Configuration buildConfiguration() {
return new Configuration()
.addAnnotatedClass(Message.class)
.setProperty("hibernate.connection.driver_class", "com.microsoft.sqlserver.jdbc.SQLServerDriver")
.setProperty("hibernate.connection.url", "jdbc:sqlserver://SERVER_NAME;databaseName=DATABASE_NAME;integratedSecurity=true;")
.setProperty("hibernate.connection.pool_size", "1")
.setProperty("hibernate.dialect", "org.hibernate.dialect.SQLServer2012Dialect")
.setProperty("hibernate.current_session_context_class", "thread")
.setProperty("hibernate.cache.provider_class", "org.hibernate.cache.internal.NoCacheProvider")
.setProperty("hibernate.show_sql", "true")
.setProperty("hibernate.hbm2ddl.auto", "update");
}
public static SessionFactory getSessionFactory() {
return SESSION_FACTORY;
}
}
Thanks in advance!
The solution to this issue is adding the catalog and schema properties to your #Table annotation.
#Table(name="<<TableName>>", catalog="<<DatabaseName>>", schema="SchemaName")
e.g
#Table(name="EVENTS", catalog="EVENTMANAGER", schema="DBO")
Catalog refers to the database name where the given table belongs
to.
Schema refers to the container (using oracle definition) to which
the database belongs, in microsoft SQL Server, databases are
generally created under the Database Operator (DBO) schema.
e.g. Hibernata Mapping File (hbm) which works for me.
<class name="Event" table="EVENTS" catalog="EVENTMANAGER" schema="DBO">
<id name="id" column="EVENT_ID">
<generator class="native"/>
</id>
<property name="date" type="timestamp" column="EVENT_DATE"/>
<property name="title" column="TITLE" not-null="true"/>
</class>

Using Singleton Class in spring mvc to get data

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.

Categories

Resources