WARNING: Exception encountered during context initialization - java

Before it work but now it is not working.And previously when it worked i use to get session Null in CrediCarddao.java for updating the customer status and inserting new creditcard record into database.
Apr 14, 2017 9:32:36 AM org.springframework.context.support.FileSystemXmlApplicationContext prepareRefresh
INFO: Refreshing org.springframework.context.support.FileSystemXmlApplicationContext#68de145: startup date [Fri Apr 14 09:32:36 CDT 2017]; root of context hierarchy
Apr 14, 2017 9:32:36 AM org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
INFO: Loading XML bean definitions from file [C:\BCJ_DEC_2016\workspace\CoreJava\creditcardprocess\spring.xml]
Apr 14, 2017 9:32:37 AM org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter initControllerAdviceCache
INFO: Looking for #ControllerAdvice: org.springframework.context.support.FileSystemXmlApplicationContext#68de145: startup date [Fri Apr 14 09:32:36 CDT 2017]; root of context hierarchy
Apr 14, 2017 9:32:37 AM org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter initControllerAdviceCache
INFO: Looking for #ControllerAdvice: org.springframework.context.support.FileSystemXmlApplicationContext#68de145: startup date [Fri Apr 14 09:32:36 CDT 2017]; root of context hierarchy
Apr 14, 2017 9:32:37 AM org.springframework.context.support.FileSystemXmlApplicationContext refresh
WARNING: Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'creditCardDao' defined in file [C:\BCJ_DEC_2016\workspace\CoreJava\creditcardprocess\target\classes\com\bcj\creditcardprocess\dao\CreditCardDao.class]: Instantiation of bean failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [com.bcj.creditcardprocess.dao.CreditCardDao]: Constructor threw exception; nested exception is java.lang.NullPointerException
Exception in thread "main" org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'creditCardDao' defined in file [C:\BCJ_DEC_2016\workspace\CoreJava\creditcardprocess\target\classes\com\bcj\creditcardprocess\dao\CreditCardDao.class]: Instantiation of bean failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [com.bcj.creditcardprocess.dao.CreditCardDao]: Constructor threw exception; nested exception is java.lang.NullPointerException
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateBean(AbstractAutowireCapableBeanFactory.java:1155)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1099)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:513)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:483)
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:306)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:302)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:197)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:761)
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:866)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:542)
at org.springframework.context.support.FileSystemXmlApplicationContext.(FileSystemXmlApplicationContext.java:140)
at org.springframework.context.support.FileSystemXmlApplicationContext.(FileSystemXmlApplicationContext.java:84)
at com.bcj.creditcardprocess.CreditCardMain.main(CreditCardMain.java:15)
Caused by: org.springframework.beans.BeanInstantiationException: Failed to instantiate [com.bcj.creditcardprocess.dao.CreditCardDao]: Constructor threw exception; nested exception is java.lang.NullPointerException
at org.springframework.beans.BeanUtils.instantiateClass(BeanUtils.java:154)
at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:89)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateBean(AbstractAutowireCapableBeanFactory.java:1147)
... 13 more
Caused by: java.lang.NullPointerException
at com.bcj.creditcardprocess.dao.CreditCardDao.(CreditCardDao.java:22)
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
at java.lang.reflect.Constructor.newInstance(Constructor.java:423)
at org.springframework.beans.BeanUtils.instantiateClass(BeanUtils.java:142)
... 15 more
CreditCardMain.java*
package com.bcj.creditcardprocess;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.FileSystemXmlApplicationContext;
import com.bcj.creditcardprocess.service.CreditCardService;
public class CreditCardMain {
public static void main(String[] args) {
#SuppressWarnings("resource")
ApplicationContext context = new FileSystemXmlApplicationContext("spring.xml");
CreditCardService obj = (CreditCardService) context.getBean("cCardService");
//CreditCardService cCardService = new CreditCardService();
obj.processCreditCard();
}
}
CreditCardService.java
package com.bcj.creditcardprocess.service;
import java.util.Iterator;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.bcj.creditcardprocess.dao.CreditCardDao;
import com.bcj.creditcardprocess.model.Customer;
#Service
public class CreditCardService {
#Autowired
private CreditCardDao cCardDao;
public void setcCardDao(CreditCardDao cCardDao) {
this.cCardDao = cCardDao;
}
public void processCreditCard() {
List<Customer> customerList = cCardDao.getCustomerList();
// creating a pool of 5 threads
ExecutorService executor = Executors.newFixedThreadPool(5);
for (Iterator iterator = customerList.iterator(); iterator.hasNext();) {
Customer cust = (Customer) iterator.next();
System.out.println(cust);
WorkerThread thread = new WorkerThread();
thread.threadmain(customerList);
//Runnable worker = new WorkerThread(cust);
// calling execute method of ExecutorService
//executor.execute(worker);
/*WorkerThread thread = new WorkerThread();
thread.threadmain(customerList);
}
executor.shutdown();
while (!executor.isTerminated()) {
}
System.out.println("Finished all threads");*/
/*
* List<Object> result = (List<Object>) customerList; Iterator itr =
* result.iterator(); while(itr.hasNext()){ Object[] obj = (Object[])
* itr.next();
*
* System.out.println(String.valueOf(obj[0])+" "+String.valueOf(obj[1]
* ));
*
*/
/*
* for (int i = 0; i < 10; i++) { Runnable worker = new WorkerThread(obj
* ); executor.execute(worker);//calling execute method of
* ExecutorService }
*/
/*executor.shutdown();
while (!executor.isTerminated()) {
}
System.out.println("Finished all threads");*/
}
}
}
WorkerThread.java
package com.bcj.creditcardprocess.service;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.Random;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.bcj.creditcardprocess.dao.CreditCardDao;
import com.bcj.creditcardprocess.model.CreditCard;
import com.bcj.creditcardprocess.model.Customer;
#Service
public class WorkerThread implements Runnable {
#Autowired
private CreditCardDao cCardDao;
public void setcCardDao(CreditCardDao cCardDao) {
this.cCardDao = cCardDao;
}
public WorkerThread() {
}
WorkerThread(Customer cust2) {
this.cust = cust2;
}
Customer cust;
public void run() {
System.out.println(Thread.currentThread().getName() + " (Start) message = " + cust.getFirstName());
try {
getCutomerDetailsByTextFile();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName() + " (End)");
}
public synchronized void getCutomerDetailsByTextFile() throws IOException {
FileReader fr = new FileReader("details.txt");
BufferedReader br = new BufferedReader(fr);
String line = "";
while ((line = br.readLine()) != null) {
System.out.println(line);
String[] details = line.split(" ");
if (details[0].equalsIgnoreCase(cust.getFirstName()) && details[1].equalsIgnoreCase(cust.getLastName())
&& details[2].equals(cust.getSsn())) {
System.out.println(" ssn had");
if (Integer.parseInt(details[3]) > 700 && Integer.parseInt(cust.getAnnualIncome()) > 100000) {
CreditCard card = new CreditCard();
card.setCreditLimit(5000);
card.setCustomerId(cust.getId());
generateCardNumber(card, cust);
cust.setStatus("Approved");
} else if (Integer.parseInt(details[3]) > 600 && Integer.parseInt(details[3]) < 700
&& Integer.parseInt(cust.getAnnualIncome()) > 70000) {
CreditCard card = new CreditCard();
card.setCreditLimit(3000);
card.setCustomerId(cust.getId());
generateCardNumber(card, cust);
cust.setStatus("Approved");
} else {
cCardDao.updateCustomer(cust);
cust.setStatus("Declined");
}
break;
}
}
}
public void threadmain(List<Customer> customerList) {
ExecutorService executor = Executors.newFixedThreadPool(5);
for (Iterator iterator = customerList.iterator(); iterator.hasNext();) {
Customer cust = (Customer) iterator.next();
Runnable worker = new WorkerThread(cust);
executor.execute(worker);// calling execute method of
// ExecutorService
}
executor.shutdown();
while (!executor.isTerminated()) {
}
System.out.println("Finished all threads");
}
private void generateCardNumber(CreditCard cCard, Customer cust) {
Random rand = new Random();
String cardNumber = Integer.toString(rand.nextInt(9999) + 1000) + Integer.toString(rand.nextInt(9999) + 1000)
+ Integer.toString(rand.nextInt(9999) + 1000) + Integer.toString(rand.nextInt(9999) + 1000);
String cvv = Integer.toString(rand.nextInt(999) + 100);
Calendar cal = Calendar.getInstance();
Date today = cal.getTime();
cal.add(Calendar.YEAR, 3); // to get previous year add -1
Date next = cal.getTime();
SimpleDateFormat adf = new SimpleDateFormat("MM/YY");
String expiryDate = adf.format(next);
cCard.setCardNumber(cardNumber);
cCard.setCvv(cvv);
cCard.setExpiryDate(expiryDate);
cCardDao.persistCreditCard(cCard, cust);
}
}
CreditCardDao.java
package com.bcj.creditcardprocess.dao;
import java.util.List;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;
import com.bcj.creditcardprocess.model.CreditCard;
import com.bcj.creditcardprocess.model.Customer;
#Repository
#Transactional
public class CreditCardDao {
#Autowired
private SessionFactory sessionFactory;
private Session session = sessionFactory.getCurrentSession();
public SessionFactory getSessionFactory() {
return sessionFactory;
}
public void setSessionFactory(SessionFactory sessionFactory) {
this.sessionFactory = sessionFactory;
}
// Session session = sessionFactory.getCurrentSession();
List<Customer> custs;
public List<Customer> getCustomerList() {
Transaction tx = session.beginTransaction();
List custs = session.createQuery("FROM Customer WHERE status='New'").list();
return custs;
}
public void persistCreditCard(CreditCard cCard, Customer cust) {
int x = cCard.getCustomerId();
Session session = sessionFactory.getCurrentSession();
Transaction tx = session.beginTransaction();
session.persist(cCard);
session.update(cust);
System.out.println("customer saved sucessfully" + cCard);
}
public void updateCustomer(Customer cust) {
Session session = sessionFactory.getCurrentSession();
Transaction tx = session.beginTransaction();
session.update(cust);
}
}
Spring.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context" xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd">
<mvc:annotation-driven />
<context:component-scan base-package="com.bcj.creditcardprocess" />
<bean
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/views/" />
<property name="suffix" value=".jsp" />
</bean>
<bean id="cCardService" class="com.bcj.creditcardprocess.service.CreditCardService" />
<bean id="cCardDao" class="com.bcj.creditcardprocess.dao.CreditCardDao" />
<tx:annotation-driven transaction-manager="transactionManager" />
<bean id="transactionManager"
class="org.springframework.orm.hibernate4.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"
destroy-method="close">
<property name="driverClassName" value="com.mysql.jdbc.Driver" />
<property name="url" value="jdbc:mysql://localhost:3306/citibank" />
<property name="username" value="root" />
<property name="password" value="root" />
</bean>
<!--Hibernate 4 SessionFactory Bean definition -->
<bean id="sessionFactory"
class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="annotatedClasses">
<list>
<value>com.bcj.creditcardprocess.model.CreditCard</value>
<value>com.bcj.creditcardprocess.model.Customer</value>
</list>
</property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect
</prop>
<prop key="hibernate.hbm2ddl.auto">update
</prop>
<prop key="hibernate.show_sql">true</prop>
<!-- <prop key="hibernate.current_session_context_class">thread</prop> -->
</props>
</property>
</bean>
</beans>
POM.xml
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.bcj</groupId>
<artifactId>creditcardprocess</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<name>creditcardprocess</name>
<url>http://maven.apache.org</url>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>3.8.1</version>
<scope>test</scope>
</dependency>
<!-- https://mvnrepository.com/artifact/org.springframework/spring-tx -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-tx</artifactId>
<version>4.3.7.RELEASE</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.hibernate/hibernate-core -->
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>4.3.3.Final</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.springframework/spring-webmvc -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>4.3.7.RELEASE</version>
</dependency>
<!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>6.0.6</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>4.3.7.RELEASE</version>
</dependency>
<!-- https://mvnrepository.com/artifact/commons-dbcp/commons-dbcp -->
<dependency>
<groupId>commons-dbcp</groupId>
<artifactId>commons-dbcp</artifactId>
<version>1.4</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>4.3.7.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>4.3.7.RELEASE</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>servlet-api</artifactId>
<version>2.5</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-orm</artifactId>
<version>4.3.7.RELEASE</version>
</dependency>
</dependencies>
</project>

Maybe try to change
private Session session = sessionFactory.getCurrentSession();
to a function
public Session getSession() {
return sessionFactory.getCurrentSession();
}
I am thinking during the class initialization, the class is trying initialize private Session session. And sessionFactory is not ready yet.

Your getSessionFactory() in CreditCardDao.java is throwing the nullPointerExceptionbecause You haven't initialized the SessionFactory so it's initialy pointing to null.
You would do that like this:
private SessionFactory sessionFactory=//build sessionfactory code
Note that the SessionFactoryshould be created once only, you can use the singleton design pattern for that.

Related

Spring JPA with Hibernate transactions deadlock

I have a Spring (core) 5.3.18 application configured with a mixed XML/annotation-driven approach.
To access the backing MariaDB, I use Hibernate core 5.6.7.Final and JPA (javax.persistence-api:2.2) with an HikariCP 4.0.3 connection pool.
The data source is an HikariDataSource with a default connection pool size of 10, and with the leakDetectionThreshold set to 6 seconds (transactions are really short).
The configured JpaTransactionManager fom spring uses as entityManagerFactory a LocalContainerEntityManagerFactoryBean that configures Hibernate via the HibernateJpaVendorAdapter.
At runtime, with just one thread performing DB operations everything works fine.
When multiple threads start requiring the DB at the same time though, threads get stuck on what seems like a starvation condition, all waiting to retrieve a connection.
HikariCP reports the following leak, reported 10 times for all of the connections available in the pool:
java.lang.Exception: Apparent connection leak detected
at com.zaxxer.hikari.HikariDataSource.getConnection(HikariDataSource.java:128)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
...
In my tests, for N threads running apparently I needed a connection pool size of exactly N*2 to avoid this behaviour, which led me to think that by some mistake (or expected behaviour unknown to me) the application I set up consumes two connections for every transaction, instead of just one.
This would explain why not even one request succeeds when all threads are sent requests at the same time, but it's just my guess: each of them acquires the first connection object at some point, and then when they try to acquire the second they all get stuck at the same time.
I really can't figure out what's happening behind Spring's and JPA's magic though. In my understanding of the documentation, a public method of a #Transactional class be wrapped in a spring proxy that gets the connection just before the transaction occurs, and closes it (actually causing the connection to return to the pool instead of bein phisically closed, see also When are connections returned to the connection pool with Spring JPA (Hibernate) Entity Manager?) after the transactin is committed/rolled-back.
Something's amiss, though. I would really appreciate any help or hint about what to do, I've been stuck on this for ages.
Below is the XML spring configuration. There are no additional persistence.xml nor hibernate.properties/cfg.xml.
<bean id="dataSourceHikari" class="com.zaxxer.hikari.HikariDataSource" destroy-method="close">
<property name="driverClassName" value="org.mariadb.jdbc.Driver" />
<property name="jdbcUrl" value="${db.url}" />
<property name="username" value="${db.user}" />
<property name="password" value="${db.password}" />
<property name="dataSourceProperties">
<props>
<prop key="autoReconnect">true</prop>
<prop key="zeroDateTimeBehavior">convertToNull</prop>
</props>
</property>
<property name="validationTimeout" value="3000" />
<property name="readOnly" value="false" />
<property name="connectionTimeout" value="60000" />
<property name="maxLifetime" value="60000" />
<property name="maximumPoolSize" value="${db.maxPoolSize:10}" />
<property name="leakDetectionThreshold" value="6000" />
</bean>
<tx:annotation-driven transaction-manager="transactionManager" />
<bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="dataSource" ref="dataSourceHikari" />
<property name="packagesToScan" value="my.application.package" />
<property name="jpaVendorAdapter">
<bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter" />
</property>
<property name="jpaProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.MySQL5InnoDBDialect</prop>
</props>
</property>
</bean>
<bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
<property name="entityManagerFactory" ref="entityManagerFactory" />
</bean>
My DB layer instead looks like this below.
Each application thread simply invokes DBLayerClass#createSession(String) on the #Autowired DBLayerClass myDBObj once for every incoming request.
import javax.persistence.EntityManager;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
/* other stuff */
#Component
#Transactional(readOnly = false, rollbackFor = {RuntimeException.class, MyCustomExceptions.class})
public class DBLayerClass {
#PersistenceContext
private EntityManager entityManager;
public Session createSession(String sessionId) throws MyCustomExceptions {
try {
if (getSessionById(sessionId) != null)
throw new MyCustomExceptions("...");
Session session = new Session(sessionId);
entityManager.persist(session);
return session;
} catch (EntityExistsException e) {
throw new MyCustomExceptions("...", e);
} catch (PersistenceException e) {
throw new MyCustomExceptions("...", e);
}
}
private Session getSessionById(String sessionId) throws MyCustomExceptions {
try {
CriteriaBuilder cb = entityManager.getCriteriaBuilder();
CriteriaQuery<Session> cq = cb.createQuery(Session.class);
Root<Session> from = cq.from(Session.class);
cq.where(cb.equal(from.get("sessionId"), sessionId));
TypedQuery<Session> q = entityManager.createQuery(cq);
return q.getSingleResult();
} catch (NoResultException e) {
return null;
} catch (PersistenceException e) {
throw new MyCustomExceptions("...", e);
}
}
}
The fields on my #Entity classes use #Id #GeneratedValue(strategy = GenerationType.SEQUENCE) annotations for Long primary keys, and other regular annotations such as #Column or #Temporal. Most fancy ones are collections with #OneToMany.
I re-wrote a simpler and basic test scenario, made to start a bunch of worker threads which keep sending db requests in a loop. A handful of createSession(...) might work at first, but the test starves soon enough and the above leaks are reported by HikariCP.
#RunWith(SpringJUnit4ClassRunner.class)
#ContextConfiguration(locations = { "classpath:/META-INF/spring/dao-test.xml" })
public class MyTestClass {
#Autowired
private DBLayerClass db;
#Test
public void testConcurrentUsage() throws Exception {
Callable<Exception> c = new Callable<Exception>() {
private AtomicLong nextId = new AtomicLong(0);
#Override
public Exception call() throws Exception {
try {
long id;
while ((id = nextId.incrementAndGet()) < 100L) {
db.createSession(String.format("session-%d", id));
}
return null;
} catch (Exception e) {
return e;
}
}
};
final int nThreads = 30;
Thread[] threads = new Thread[nThreads];
ArrayList<Future<Exception>> threadResults = new ArrayList<>(nThreads);
for (int i = 0; i < threads.length; i++) {
FutureTask<Exception> threadResult = new FutureTask<>(c);
threadResults.add(threadResult);
threads[i] = new Thread(threadResult);
threads[i].start();
}
for (Future<Exception> result : threadResults) {
Exception e = result.get();
if (e != null) {
for (Thread thread : threads) {
thread.stop();
}
throw e;
}
}
}
Finally, these below are the dependencies:
<dependency>
<groupId>org.mariadb.jdbc</groupId>
<artifactId>mariadb-java-client</artifactId>
<version>3.0.4</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>5.3.18</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.3.18</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-beans</artifactId>
<version>5.3.18</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>5.3.18</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-tx</artifactId>
<version>5.3.18</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-orm</artifactId>
<version>5.3.18</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>5.6.7.Final</version>
</dependency>
<dependency>
<groupId>javax.persistence</groupId>
<artifactId>javax.persistence-api</artifactId>
<version>2.2</version>
</dependency>
<dependency>
<groupId>org.hibernate.validator</groupId>
<artifactId>hibernate-validator</artifactId>
<version>6.0.23.Final</version>
</dependency>
<dependency>
<groupId>com.zaxxer</groupId>
<artifactId>HikariCP</artifactId>
<version>4.0.3</version>
</dependency>

java.lang.IllegalArgumentException: org.hibernate.hql.internal.ast.QuerySyntaxException: News is not mapped [from News where status =: active]

I connected Spring 5.0.19.RELEASE and Hibernate 5.2.10.Final.
I'm getting an error: java.lang.IllegalArgumentException: org.hibernate.hql.internal.ast.QuerySyntaxException: News is not mapped [from News where status =: active].
The same error is also obtained with other requests (for example "from News").
The work of the application reaches the DAO layer and executes a query from the database.
When I trying to get information from BD and display this list in the web app.
I'm a newbie in Java.
I tried the options below:
why-org-hibernate-hql-internal-ast-querysyntaxexception-customer-is-not-mapped
Hibernate error - QuerySyntaxException: users is not mapped [from
users]
but it doesn't work.
I hope to get help in my confused situation.
My DataBase in MySQL
CREATE TABLE `news` (
`idnews` int NOT NULL AUTO_INCREMENT,
`title` varchar(200) COLLATE utf8_bin DEFAULT NULL,
`brief` varchar(500) COLLATE utf8_bin DEFAULT NULL,
`content` varchar(5000) COLLATE utf8_bin DEFAULT NULL,
`date` timestamp NULL DEFAULT NULL,
`status` varchar(45) COLLATE utf8_bin NOT NULL,
PRIMARY KEY (`idnews`)
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8 COLLATE=utf8_bin
Error:
Jun 22, 2021 9:10:23 AM org.apache.catalina.core.StandardWrapperValve invoke
SEVERE: Servlet.service() for servlet [dispatcher] in context with path [/spring-myproject] threw exception [Request processing failed; nested exception is java.lang.IllegalArgumentException: org.hibernate.hql.internal.ast.QuerySyntaxException: News is not mapped [from News where status =: active]] with root cause
org.hibernate.hql.internal.ast.QuerySyntaxException: News is not mapped
at org.hibernate.hql.internal.ast.util.SessionFactoryHelper.requireClassPersister(SessionFactoryHelper.java:171)
at org.hibernate.hql.internal.ast.tree.FromElementFactory.addFromElement(FromElementFactory.java:91)
at org.hibernate.hql.internal.ast.tree.FromClause.addFromElement(FromClause.java:79)
at org.hibernate.hql.internal.ast.HqlSqlWalker.createFromElement(HqlSqlWalker.java:324)
at org.hibernate.hql.internal.antlr.HqlSqlBaseWalker.fromElement(HqlSqlBaseWalker.java:3696)
at org.hibernate.hql.internal.antlr.HqlSqlBaseWalker.fromElementList(HqlSqlBaseWalker.java:3585)
at org.hibernate.hql.internal.antlr.HqlSqlBaseWalker.fromClause(HqlSqlBaseWalker.java:720)
at org.hibernate.hql.internal.antlr.HqlSqlBaseWalker.query(HqlSqlBaseWalker.java:576)
at org.hibernate.hql.internal.antlr.HqlSqlBaseWalker.selectStatement(HqlSqlBaseWalker.java:313)
at org.hibernate.hql.internal.antlr.HqlSqlBaseWalker.statement(HqlSqlBaseWalker.java:261)
at org.hibernate.hql.internal.ast.QueryTranslatorImpl.analyze(QueryTranslatorImpl.java:266)
at org.hibernate.hql.internal.ast.QueryTranslatorImpl.doCompile(QueryTranslatorImpl.java:189)
at org.hibernate.hql.internal.ast.QueryTranslatorImpl.compile(QueryTranslatorImpl.java:141)
at org.hibernate.engine.query.spi.HQLQueryPlan.<init>(HQLQueryPlan.java:115)
at org.hibernate.engine.query.spi.HQLQueryPlan.<init>(HQLQueryPlan.java:77)
at org.hibernate.engine.query.spi.QueryPlanCache.getHQLQueryPlan(QueryPlanCache.java:153)
at org.hibernate.internal.AbstractSharedSessionContract.getQueryPlan(AbstractSharedSessionContract.java:546)
at org.hibernate.internal.AbstractSharedSessionContract.createQuery(AbstractSharedSessionContract.java:655)
at org.hibernate.internal.AbstractSharedSessionContract.createQuery(AbstractSharedSessionContract.java:679)
at org.hibernate.internal.AbstractSharedSessionContract.createQuery(AbstractSharedSessionContract.java:102)
at myproject.dao.impl.SQLNewsDAO.all(SQLNewsDAO.java:28)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:78)
at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.base/java.lang.reflect.Method.invoke(Method.java:567)
at org.springframework.aop.support.AopUtils.invokeJoinpointUsingReflection(AopUtils.java:343)
at org.springframework.aop.framework.ReflectiveMethodInvocation.invokeJoinpoint(ReflectiveMethodInvocation.java:197)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:163)
at org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:295)
at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:98)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:185)
at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:212)
at jdk.proxy3/jdk.proxy3.$Proxy26.all(Unknown Source)
at myproject.service.impl.NewsServiceImpl.takeAll(NewsServiceImpl.java:28)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:78)
at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.base/java.lang.reflect.Method.invoke(Method.java:567)
at org.springframework.aop.support.AopUtils.invokeJoinpointUsingReflection(AopUtils.java:343)
at org.springframework.aop.framework.ReflectiveMethodInvocation.invokeJoinpoint(ReflectiveMethodInvocation.java:197)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:163)
at org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:295)
at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:98)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:185)
at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:212)
at jdk.proxy3/jdk.proxy3.$Proxy27.takeAll(Unknown Source)
at myproject.command.GoToMainIndexPage.execute(GoToMainIndexPage.java:27)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:78)
at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.base/java.lang.reflect.Method.invoke(Method.java:567)
at org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:209)
at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:136)
at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:102)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:893)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:799)
at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:87)
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:991)
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:925)
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:981)
at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:873)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:626)
at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:858)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:733)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:231)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:202)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:97)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:542)
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:888)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1597)
at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49)
at java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1130)
at java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:630)
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
at java.base/java.lang.Thread.run(Thread.java:831)
Entity:
package myproject.entity;
import java.io.Serializable;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
#Entity
#Table(name="news")
public class News implements Serializable {
private static final long serialVersionUID = 5421029433949953632L;
#Id
#GeneratedValue(strategy=GenerationType.IDENTITY)
#Column(name="idnews")
private int idnews;
#Column(name="title")
private String title;
#Column(name="brief")
private String brief;
#Column(name="content")
private String content;
#Column(name="date")
private LocalDateTime date;
#Column(name="status")
private String status;
public News() {
}
public News(int idnews, String title, String brief) {
super();
this.setIdnews(idnews);
this.title = title;
this.setBrief(brief);
}
public News(int idnews, String title, String brief, String content, LocalDateTime date) {
super();
this.setIdnews(idnews);
this.title = title;
this.setBrief(brief);
this.setContent(content);
this.setDate(date);
}
public int getIdnews() {
return idnews;
}
public void setIdnews(int idnews) {
this.idnews = idnews;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getBrief() {
return brief;
}
public void setBrief(String brief) {
this.brief = brief;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
public String getDate() {
DateTimeFormatter newFormat = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm");
String formattedDateTime = date.format(newFormat);
return formattedDateTime;
}
public void setDate(LocalDateTime date) {
this.date = date;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
#Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((brief == null) ? 0 : brief.hashCode());
result = prime * result + ((content == null) ? 0 : content.hashCode());
result = prime * result + ((date == null) ? 0 : date.hashCode());
result = prime * result + idnews;
result = prime * result + ((status == null) ? 0 : status.hashCode());
result = prime * result + ((title == null) ? 0 : title.hashCode());
return result;
}
#Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
News other = (News) obj;
if (brief == null) {
if (other.brief != null)
return false;
} else if (!brief.equals(other.brief))
return false;
if (content == null) {
if (other.content != null)
return false;
} else if (!content.equals(other.content))
return false;
if (date == null) {
if (other.date != null)
return false;
} else if (!date.equals(other.date))
return false;
if (idnews != other.idnews)
return false;
if (status == null) {
if (other.status != null)
return false;
} else if (!status.equals(other.status))
return false;
if (title == null) {
if (other.title != null)
return false;
} else if (!title.equals(other.title))
return false;
return true;
}
#Override
public String toString() {
return "id: " + this.idnews + "\n" +
"title:" + this.title + "\n" +
"brief:" + this.brief + "\n" +
"content: " + this.content + "\n" +
"date: " + this.date + "\n" +
"status: " + this.status;
}
}
Controller layer
package myproject.command;
import java.io.IOException;
import java.util.List;
import javax.servlet.ServletException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import myproject.entity.News;
import myproject.service.NewsService;
import myproject.service.ServiceException;
#Controller
#RequestMapping("/mainIndexPage")
public class GoToMainIndexPage {
#Autowired
private NewsService newsService;
#RequestMapping("/showMainPage")
public String execute(Model theModel) throws ServletException, IOException, ServiceException {
List<News> news = newsService.takeAll();
theModel.addAttribute("news", news);
return "main_index_page";
}
}
Service layer
package myproject.service.impl;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import myproject.dao.DAOException;
import myproject.dao.NewsDAO;
import myproject.entity.News;
import myproject.service.NewsService;
import myproject.service.ServiceException;
#Service
public class NewsServiceImpl implements NewsService {
#Autowired
private NewsDAO newsDAO;
//#Override
#Transactional
public List<News> takeAll() throws ServiceException {
System.out.println(1);
List<News> news;
try {
news = newsDAO.all();
} catch (DAOException e) {
throw new ServiceException(e.getMessage(), e);
}
return news;
}
}
DAO layer
package myproject.dao.impl;
import java.util.List;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.query.Query;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;
import myproject.dao.DAOException;
import myproject.dao.NewsDAO;
import myproject.entity.News;
#Repository
public class SQLNewsDAO implements NewsDAO {
// need to inject the session factory
#Autowired
private SessionFactory sessionFactory;
#Override
#Transactional
public List<News> all() throws DAOException {
System.out.println(2);
Session currentSession = sessionFactory.getCurrentSession();
Query<News> theQuery = currentSession.createQuery("from News where status =: active", News.class); /*"from News where status = 'active'"*/
List<News> news = theQuery.getResultList();
return news;
}
}
ApplicationContext
<?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:context="http://www.springframework.org/schema/context"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx.xsd">
<!-- Step 3: Add support for component scanning -->
<context:component-scan base-package="myproject" />
<!-- Step 4: Add support for conversion, formatting and validation support -->
<mvc:annotation-driven />
<!-- Step 5: Define Spring MVC view resolver -->
<bean
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/view/" />
<property name="suffix" value=".jsp" />
</bean>
<!-- Step 6 Add support for reading web resources: css, images, js, etc
... -->
<mvc:resources location="/resources/"
mapping="/resources/**" />
<bean
class="org.springframework.context.support.ResourceBundleMessageSource"
id="messageSource">
<property value="resources/messages" name="basenames" />
</bean>
<!-- Step 7 Define Database DataSource / connection pool -->
<bean id="myDataSource"
class="com.mchange.v2.c3p0.ComboPooledDataSource"
destroy-method="close">
<property name="driverClass" value="com.mysql.jdbc.Driver" />
<property name="jdbcUrl"
value="jdbc:mysql://localhost:3306/news_management_spring_hibernate?allowPublicKeyRetrieval=true&useSSL=false&serverTimezone=UTC" />
<property name="user" value="111" />
<property name="password" value="111" />
<!-- these are connection pool properties for C3P0 -->
<property name="minPoolSize" value="5" />
<property name="maxPoolSize" value="20" />
<property name="maxIdleTime" value="30000" />
</bean>
<!-- Step 8 Setup Hibernate session factory -->
<bean id="sessionFactory"
class="org.springframework.orm.hibernate5.LocalSessionFactoryBean">
<property name="dataSource" ref="myDataSource" />
<property name="packagesToScan" value="src.main.java.myproject.entity" />
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
<prop key="hibernate.show_sql">true</prop>
</props>
</property>
</bean>
<!-- Step 9 Setup Hibernate transaction manager -->
<bean id="myTransactionManager"
class="org.springframework.orm.hibernate5.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
<!-- Step 10 Enable configuration of transactional behavior based on annotations -->
<tx:annotation-driven transaction-manager="myTransactionManager" />
</beans>
pom.xml
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>by.htp.spring.main</groupId>
<artifactId>spring-myproject</artifactId>
<packaging>war</packaging>
<version>0.0.1-SNAPSHOT</version>
<name>spring-myproject Maven Webapp</name>
<url>http://maven.apache.org</url>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<!-- Generic properties -->
<maven.compiler.release>1.8</maven.compiler.release>
<!-- Web -->
<jsp.version>2.2</jsp.version>
<jstl.version>1.2</jstl.version>
<servlet.version>3.1.0</servlet.version>
<!-- Spring -->
<spring-framework.version>5.0.19.RELEASE</spring-framework.version>
</properties>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>3.8.1</version>
<scope>test</scope>
</dependency>
<!-- https://mvnrepository.com/artifact/javax.servlet/javax.servlet-api -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>4.0.1</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>javax.servlet.jsp</groupId>
<artifactId>javax.servlet.jsp-api</artifactId>
<version>2.3.1</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
<version>${jstl.version}</version>
</dependency>
<!-- BD -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
<version>8.0.23</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>5.2.10.Final</version>
</dependency>
<!-- Dependency Spring Framework -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>${spring-framework.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>${spring-framework.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-orm</artifactId>
<version>${spring-framework.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-beans</artifactId>
<version>${spring-framework.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>${spring-framework.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-tx</artifactId>
<version>${spring-framework.version}</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.springframework/spring-web -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>${spring-framework.version}</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.springframework.security/spring-security-taglibs -->
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-taglibs</artifactId>
<version>${spring-framework.version}</version>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-web</artifactId>
<version>${spring-framework.version}</version>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-config</artifactId>
<version>${spring-framework.version}</version>
</dependency>
<!-- Other -->
<dependency>
<groupId>c3p0</groupId>
<artifactId>c3p0</artifactId>
<version>0.9.1.2</version>
</dependency>
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-api</artifactId>
<version>2.14.1</version>
</dependency>
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-core</artifactId>
<version>2.14.1</version>
</dependency>
<dependency>
<groupId>javax.xml.bind</groupId>
<artifactId>jaxb-api</artifactId>
<version>2.2.8</version>
</dependency>
<dependency>
<groupId>com.sun.xml.bind</groupId>
<artifactId>jaxb-core</artifactId>
<version>2.3.0.1</version>
</dependency>
<dependency>
<groupId>com.sun.xml.bind</groupId>
<artifactId>jaxb-impl</artifactId>
<version>2.3.0.1</version>
</dependency>
<dependency>
<groupId>com.sun.activation</groupId>
<artifactId>javax.activation</artifactId>
<version>1.2.0</version>
</dependency>
<dependency>
<groupId>org.mindrot</groupId>
<artifactId>jbcrypt</artifactId>
<version>0.4</version>
</dependency>
<!-- New depend -->
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-c3p0</artifactId>
<version>5.4.26.Final</version>
</dependency>
</dependencies>
<build>
<finalName>spring-myproject</finalName>
<plugins>
<plugin>
<groupId>org.apache.tomcat.maven</groupId>
<artifactId>tomcat7-maven-plugin</artifactId>
<version>2.2</version>
<configuration>
<url>http://localhost:8080/manager/text</url>
<server>tomcat-server</server>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.8.1</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
<encoding>${project.build.sourceEncoding}</encoding>
<showWarnings>true</showWarnings>
<showDeprecation>true</showDeprecation>
</configuration>
</plugin>
</plugins>
</build>
</project>
main_index_page.jsp (view)
<!--News-->
<div class="list_news">
<c:forEach var="AllNewsFromBD" items="${news}"> <!--requestScope.-->
<div class="list_news_block">
<div class="">
<h5 class="title_news">
<c:out value="${AllNewsFromBD.title}" />
</h5>
<p class="">
<c:out value="${AllNewsFromBD.brief}" />
</p>
<c:if test="${sessionScope.auth == true}">
<div class="">
<a href="Controller?command=go_to_one_news_page&idnews=<c:out value="${AllNewsFromBD.idnews}"/>">
<c:out value="${ReadMore}" /></a>
</div>
</c:if>
<br/>
</div>
</div>
</c:forEach>
</div>
There are lot of posts on stackoverflow in which addressing the same issue. But I was unable to find a definite solution for this.
Please help
You could try this:
Query<News> theQuery = currentSession.createQuery("select news from News news where news.status = :active", News.class);
theQuery.setParameter("status", active);
return theQuery.getResultList();

Getting an exception while creating simple Spring AOP Throws Advice Demo

hi I am getting Exception as ****thread "main" org.springframework.beans.factory.xml.XmlBeanDefinitionStoreException****
while try to make a simple Spring AOP throws advice Demo.
Please some one help me out.
The detail code with exception is mentioned below
MyInterface.java
package com.Spring.Aop.SpringAOPThrowsAdvice;
public class MyImplClass implements MyInterface {
public void m1(){
int java4s = 10/0;
System.out.println("Am in business method..");
}
}
MyInterface.java
package com.Spring.Aop.SpringAOPThrowsAdvice;
public interface MyInterface {
void m1();
}
MyThrowsAdvice.java
package com.Spring.Aop.SpringAOPThrowsAdvice;
import java.lang.reflect.Method;
import org.springframework.aop.ThrowsAdvice;
public class MyThrowsAdvice implements ThrowsAdvice {
//First preference
public void afterThrowing(ArithmeticException e)
{
System.out.println("This is from ArithmeticException method");
}
//Second preference
public void afterThrowing(Method m, Object args[], Object target,Exception e)
{
System.out.println("Am from 4 parameters method called from "+m.getName());
}
//Third preference
public void afterThrowing(Exception e)
{
System.out.println("Fom single parameter method");
}
}
OurLogic.java
package com.Spring.Aop.SpringAOPThrowsAdvice;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.xml.XmlBeanFactory;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
public class OurLogic {
public static void main(String args[])
{
Resource res = new ClassPathResource("spconfig.xml");
BeanFactory factory = new XmlBeanFactory(res);
MyInterface inter =(MyInterface)factory.getBean("id3");
inter.m1();
}
}
spconfig.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans>
<bean id="id1" class="com.Spring.Aop.SpringAOPThrowsAdvice.MyImplClass" />
<bean id="id2" class="com.Spring.Aop.SpringAOPThrowsAdvice.MyThrowsAdvice" />
<bean id="id3" class="org.springframework.aop.framework.ProxyFactoryBean">
<property name="proxyInterfaces" value="com.Spring.Aop.SpringAOPThrowsAdvice.MyInterface" />
<property name="interceptorNames" >
<list>
<value>id2</value>
</list>
</property>
<property name="target">
<ref bean="id1"/>
</property>
</bean>
</beans>
pom.xml
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.Spring.Aop</groupId>
<artifactId>SpringAOPThrowsAdvice</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<name>SpringAOPThrowsAdvice</name>
<url>http://maven.apache.org</url>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>3.8.1</version>
<scope>test</scope>
</dependency>
<!-- https://mvnrepository.com/artifact/org.springframework/spring-aop -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aop</artifactId>
<version>2.5.6</version>
</dependency>
</dependencies>
</project>
Exception is:
May 11, 2017 12:47:38 PM org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
INFO: Loading XML bean definitions from class path resource [spconfig.xml]
Exception in thread "main" org.springframework.beans.factory.xml.XmlBeanDefinitionStoreException: Line 2 in XML document from class path resource [spconfig.xml] is invalid; nested exception is org.xml.sax.SAXParseException; lineNumber: 2; columnNumber: 8; cvc-elt.1: Cannot find the declaration of element 'beans'.
at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.doLoadBeanDefinitions(XmlBeanDefinitionReader.java:404)
at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.loadBeanDefinitions(XmlBeanDefinitionReader.java:342)
at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.loadBeanDefinitions(XmlBeanDefinitionReader.java:310)
at org.springframework.beans.factory.xml.XmlBeanFactory.<init>(XmlBeanFactory.java:73)
at org.springframework.beans.factory.xml.XmlBeanFactory.<init>(XmlBeanFactory.java:61)
at com.Spring.Aop.SpringAOPThrowsAdvice.OurLogic.main(OurLogic.java:12)
Caused by: org.xml.sax.SAXParseException; lineNumber: 2; columnNumber: 8; cvc-elt.1: Cannot find the declaration of element 'beans'.
at com.sun.org.apache.xerces.internal.util.ErrorHandlerWrapper.createSAXParseException(ErrorHandlerWrapper.java:203)
at com.sun.org.apache.xerces.internal.util.ErrorHandlerWrapper.error(ErrorHandlerWrapper.java:134)
at com.sun.org.apache.xerces.internal.impl.XMLErrorReporter.reportError(XMLErrorReporter.java:396)
at com.sun.org.apache.xerces.internal.impl.XMLErrorReporter.reportError(XMLErrorReporter.java:327)
at com.sun.org.apache.xerces.internal.impl.XMLErrorReporter.reportError(XMLErrorReporter.java:284)
at com.sun.org.apache.xerces.internal.impl.xs.XMLSchemaValidator.handleStartElement(XMLSchemaValidator.java:1900)
at com.sun.org.apache.xerces.internal.impl.xs.XMLSchemaValidator.startElement(XMLSchemaValidator.java:740)
at com.sun.org.apache.xerces.internal.impl.XMLNSDocumentScannerImpl.scanStartElement(XMLNSDocumentScannerImpl.java:374)
at com.sun.org.apache.xerces.internal.impl.XMLNSDocumentScannerImpl$NSContentDriver.scanRootElementHook(XMLNSDocumentScannerImpl.java:613)
at com.sun.org.apache.xerces.internal.impl.XMLDocumentFragmentScannerImpl$FragmentContentDriver.next(XMLDocumentFragmentScannerImpl.java:3132)
at com.sun.org.apache.xerces.internal.impl.XMLDocumentScannerImpl$PrologDriver.next(XMLDocumentScannerImpl.java:852)
at com.sun.org.apache.xerces.internal.impl.XMLDocumentScannerImpl.next(XMLDocumentScannerImpl.java:602)
at com.sun.org.apache.xerces.internal.impl.XMLNSDocumentScannerImpl.next(XMLNSDocumentScannerImpl.java:112)
at com.sun.org.apache.xerces.internal.impl.XMLDocumentFragmentScannerImpl.scanDocument(XMLDocumentFragmentScannerImpl.java:505)
at com.sun.org.apache.xerces.internal.parsers.XML11Configuration.parse(XML11Configuration.java:841)
at com.sun.org.apache.xerces.internal.parsers.XML11Configuration.parse(XML11Configuration.java:770)
at com.sun.org.apache.xerces.internal.parsers.XMLParser.parse(XMLParser.java:141)
at com.sun.org.apache.xerces.internal.parsers.DOMParser.parse(DOMParser.java:243)
at com.sun.org.apache.xerces.internal.jaxp.DocumentBuilderImpl.parse(DocumentBuilderImpl.java:339)
at org.springframework.beans.factory.xml.DefaultDocumentLoader.loadDocument(DefaultDocumentLoader.java:75)
at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.doLoadBeanDefinitions(XmlBeanDefinitionReader.java:396)
... 5 more
You simply haven't put the namespace bean in your config file header : http://docs.spring.io/spring-integration/reference/html/xml.html

Tomcat doesn't connect to db Error Status 500 java.lang.ClassNotFoundException

When I try to connect to the db I get a 500 error and closes my eclipse/tomcat. Does anyone know how could I fix it?
Confirm Servlet
package be.pxl.tafelboeker.servlets;
import be.pxl.tafelboeker.dao.BoekingDAO;
import be.pxl.tafelboeker.domain.Boeking;
import be.pxl.tafelboeker.services.BoekingService;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebInitParam;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
#WebServlet(value = "/Confirm", initParams = {
#WebInitParam(name = "ConfirmPage",
value = "/confirm.jsp") })
public class ConfirmServlet extends HttpServlet {
private String ConfirmPage;
private String geluktPage;
private String misluktPage;
private BoekingService service = new BoekingService();
#Override
public void init() throws ServletException {
// TODO Auto-generated method stub
super.init();
ConfirmPage = getInitParameter("ConfirmPage");
geluktPage ="gelukt.jsp";
misluktPage = "mislukt.jsp";
}
#Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
Boeking bean = new Boeking();
HttpSession sess = request.getSession();
bean = (Boeking)sess.getAttribute("bean");
request.setAttribute("bean", bean);
request.getRequestDispatcher(ConfirmPage).forward(request,response);
}
#Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO STUDENT : boek tafel, toon gelukt.jsp indien de boeking gelukt is en toon mislukt.jsp indien de tafel niet geboekt kan worden
Boeking bean = new Boeking();
HttpSession sess = request.getSession();
bean = (Boeking)sess.getAttribute("bean");
BoekingDAO dao = new BoekingDAO("jdbc:mysql://localhost/survey", "root", "");
BoekingService serv = new BoekingService();
serv.setDao(dao);
if (serv.boekTafel(bean)) {
request.getRequestDispatcher(geluktPage).include(request,response);
} else {
request.getRequestDispatcher(misluktPage).include(request,response);
}
//Krijg een error bij het aanroepen van mijn Persistence krijg deze pas vandaag als ik mijn oefeningen van gister wil openen die werkte krijg ik het nu ook
//Dit is zeer vervelend. Kan nu niet testen of mijn query en de rest wel klopt.
//Heb mijn best gedaan om het zo goed mogelijk in te zullen
//Hetzelfde geld voor overzichtservlet & overzicht.jsp die ook dezelfde fout krijgen
}
}
Boeking Dao
package be.pxl.tafelboeker.dao;
import be.pxl.tafelboeker.domain.Boeking;
import javax.persistence.EntityManagerFactory;
import javax.persistence.EntityManager;
import javax.persistence.Persistence;
import javax.persistence.Query;
import java.time.LocalDate;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
public class BoekingDAO {
private String url;
private String user;
private String password;
EntityManagerFactory emf;
public BoekingDAO(String url, String user, String password) {
this.url = url;
this.user = user;
this.password = password;
}
public void setDriver(String driver)
throws ClassNotFoundException {
Class.forName("com.mysql.jdbc.Driver");
}
private EntityManager getEntityManager() {
emf = Persistence.createEntityManagerFactory("booking");
EntityManager em = emf.createEntityManager();
return em;
}
// TIP : Gebruik TemporalType.DATE voor je query parameter
public boolean isTafelBeschikbaar(LocalDate dag, int uur) {
EntityManager em = getEntityManager();
Query q1 = em.createQuery("select b from booking as b where (b.dag=?1 AND b.uur =?2) ");
q1.setParameter(1, dag);
q1.setParameter(2, uur);
if (q1.getMaxResults() == 0) {
return true;
} else {
return false;
}
}
public void boekTafel(Boeking bean) {
EntityManager em = getEntityManager();
em.persist(bean);
em.close();
emf.close();
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public String getUser() {
return user;
}
public void setUser(String user) {
this.user = user;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}
DriverLoader
package be.pxl.tafelboeker.dao;
public class DriverLoader {
static{
System.out.print("loading database");
try {
Class.forName("com.mysql.jdbc.Driver");
} catch (ClassNotFoundException e) {
System.out.println("nope");
e.printStackTrace();
}
}
}
Boeking Service
package be.pxl.tafelboeker.services;
import be.pxl.tafelboeker.dao.BoekingDAO;
import be.pxl.tafelboeker.domain.Boeking;
import java.time.LocalDate;
import java.util.Date;
public class BoekingService {
private BoekingDAO dao;
public BoekingService(){
}
public BoekingDAO getDao() {
return dao;
}
public void setDao(BoekingDAO dao) {
this.dao = dao;
}
private boolean isTafelBeschikbaar(LocalDate dag, int uur){
return dao.isTafelBeschikbaar(dag, uur) ;
}
public boolean boekTafel(Boeking boeking){
LocalDate dag = boeking.getDag();
int uur = boeking.getUur();
if(isTafelBeschikbaar(dag, uur)){
dao.boekTafel(boeking);
return true;
}
return false;
}
}
pom
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>be.pxl</groupId>
<artifactId>HerexamensOef</artifactId>
<packaging>war</packaging>
<version>0.0.1-SNAPSHOT</version>
<name>HerexamensOef Maven Webapp</name>
<url>http://maven.apache.org</url>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>3.8.1</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>javax</groupId>
<artifactId>javaee-web-api</artifactId>
<version>7.0</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>
</dependencies>
<build>
<finalName>HerexamensOef</finalName>
</build>
</project>
persistance
<?xml version="1.0" encoding="UTF-8"?>
<persistence xmlns="http://xmlns.jcp.org/xml/ns/persistence"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/persistence
http://xmlns.jcp.org/xml/ns/persistence/persistence_2_1.xsd"
version="2.1">
<persistence-unit name="booking" transaction-type="RESOURCE_LOCAL">
<properties>
<property name="javax.persistence.jdbc.driver" value="com.mysql.jdbc.Driver" />
<property name="javax.persistence.jdbc.url" value="jdbc:mysql://localhost/booking" />
<property name="javax.persistence.jdbc.user" value="root" />
<property name="javax.persistence.jdbc.password" value="" />
<property name="javax.persistence.schema-generation.database.action"
value="none" />
<!-- Hibernate specific -->
<property name="hibernate.show_sql" value="true" />
</properties>
</persistence-unit>
</persistence>
Error
HTTP Status 500 - Servlet execution threw an exception
type Exception report
message Servlet execution threw an exception
description The server encountered an internal error that prevented it from fulfilling this request.
exception
javax.servlet.ServletException: Servlet execution threw an exception
org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
root cause
java.lang.NoClassDefFoundError: javax/persistence/Persistence
be.pxl.tafelboeker.dao.BoekingDAO.getEntityManager(BoekingDAO.java:35)
be.pxl.tafelboeker.dao.BoekingDAO.isTafelBeschikbaar(BoekingDAO.java:43)
be.pxl.tafelboeker.services.BoekingService.isTafelBeschikbaar(BoekingService.java:28)
be.pxl.tafelboeker.services.BoekingService.boekTafel(BoekingService.java:34)
be.pxl.tafelboeker.servlets.ConfirmServlet.doPost(ConfirmServlet.java:59)
javax.servlet.http.HttpServlet.service(HttpServlet.java:648)
javax.servlet.http.HttpServlet.service(HttpServlet.java:729)
org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
note The full stack trace of the root cause is available in the Apache Tomcat/8.0.33 logs.
SQL of booking
-- phpMyAdmin SQL Dump
-- version 4.4.10
-- http://www.phpmyadmin.net
--
-
- Host: localhost
-- Generation Time: Jun 03, 2016 at 06:50 PM
-- Server version: 5.5.42
-- PHP Version: 7.0.0
SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO";
SET time_zone = "+00:00";
--
-- Database: `boekingdb`
--
-- --------------------------------------------------------
--
-- Table structure for table `BOOKING`
--
CREATE TABLE `BOOKING` (
`id` bigint(20) NOT NULL,
`DAY` date DEFAULT NULL,
`NAME` varchar(255) DEFAULT NULL,
`CITY` varchar(255) DEFAULT NULL,
`STREET` varchar(255) DEFAULT NULL,
`HOUR` int(11) DEFAULT NULL
) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=latin1;
--
-- Indexes for table `BOOKING`
--
ALTER TABLE `BOOKING`
ADD PRIMARY KEY (`id`);
--
-- AUTO_INCREMENT for dumped tables
--
--
-- AUTO_INCREMENT for table `BOOKING`
--
ALTER TABLE `BOOKING`
MODIFY `id` bigint(20) NOT NULL AUTO_INCREMENT,AUTO_INCREMENT=4;
Your persistence file use the JPA schema for the 2.1 version :
<persistence xmlns="http://xmlns.jcp.org/xml/ns/persistence"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/persistence
http://xmlns.jcp.org/xml/ns/persistence/persistence_2_1.xsd"
version="2.1">
so you should use a matching hibernate version : min Hibernate 4.3.X.
I guess that you use Hibernate because of it in your persistence.xml
<property name="hibernate.show_sql" value="true" />
So if you want use JPA as interface, you should add this dependency in your pom.xml :
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-entitymanager</artifactId>
<version>5.2.2.Final</version>
</dependency>
This dependency includes hibernate-jpa-2.1-api which contains the class javax.persistence.Persistence
else if you want to use Hibernate directly without JPA as interface, you could use this dependency (or + 4.3.X):
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>5.2.2.Final</version>
</dependency>
More details here : http://hibernate.org/orm/downloads/
You have to add the javax.persistence-api.jar as a dependency:
<!-- https://mvnrepository.com/artifact/javax.persistence/persistence-api -->
<dependency>
<groupId>javax.persistence</groupId>
<artifactId>persistence-api</artifactId>
<version>1.0.2</version>
</dependency>

Hibernate Session null-pointer exception

I have been stuck with this issue for days cannot figure it out, I mean I know the sessionFactory must be null as the stacktrace indicates but I cannot understand why? The exception always comes back to the line:
Session session = hibernateUtil.getSessionFactory().getCurrentSession();
Here is a trimmed version of the stacktrace:
DEBUG - Creating new transaction with name [com.sga.app.dao.DisplayStatsDAO$$EnhancerBySpringCGLIB$$f03b1e71.getForename]: PROPAGATION_REQUIRED,ISOLATION_DEFAULT; ''
DEBUG - Acquired Connection [jdbc:oracle:thin:system/system#localhost:1521/XE, UserName=SYSTEM, Oracle JDBC driver] for JDBC transaction
DEBUG - Switching JDBC Connection [jdbc:oracle:thin:system/system#localhost:1521/XE, UserName=SYSTEM, Oracle JDBC driver] to manual commit
DEBUG - Returning cached instance of singleton bean 'sessionFactory'
DEBUG - Initiating transaction rollback
DEBUG - Rolling back JDBC transaction on Connection [jdbc:oracle:thin:system/system#localhost:1521/XE, UserName=SYSTEM, Oracle JDBC driver]
DEBUG - Releasing JDBC Connection [jdbc:oracle:thin:system/system#localhost:1521/XE, UserName=SYSTEM, Oracle JDBC driver] after transaction
DEBUG - Returning JDBC Connection to DataSource
DEBUG - Invoking afterPropertiesSet() on bean with name 'error'
DEBUG - Rendering view [org.springframework.web.servlet.view.JstlView: name 'error'; URL [/WEB-INF/jsps/error.jsp]] in DispatcherServlet with name 'dispatcher'
DEBUG - Added model object 'userBean' of type [com.sga.app.beans.UserBean] to request in view with name 'error'
DEBUG - Added model object 'org.springframework.validation.BindingResult.userBean' of type [org.springframework.validation.BeanPropertyBindingResult] to request in view with name 'error'
DEBUG - Added model object 'displayStatsDAO' of type [com.sga.app.dao.DisplayStatsDAO] to request in view with name 'error'
DEBUG - Added model object 'org.springframework.validation.BindingResult.displayStatsDAO' of type [org.springframework.validation.BeanPropertyBindingResult] to request in view with name 'error'
DEBUG - Added model object 'username' of type [java.lang.String] to request in view with name 'error'
DEBUG - Forwarding to resource [/WEB-INF/jsps/error.jsp] in InternalResourceView 'error'
java.lang.NullPointerException
at com.sga.app.dao.DisplayStatsDAO.getForename(DisplayStatsDAO.java:66)
at com.sga.app.dao.DisplayStatsDAO$$FastClassBySpringCGLIB$$52d44a3e.invoke(<generated>)
at org.springframework.cglib.proxy.MethodProxy.invoke(MethodProxy.java:204)
And my DAO:
package com.sga.app.dao;
import java.io.IOException;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.hibernate.Criteria;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.criterion.Restrictions;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;
import com.sga.app.beans.UserBean;
import com.sga.app.hibernate.HibernateUtil;
#Component("displayStatsDAO")
#Repository
#Transactional
#Configuration
public class DisplayStatsDAO extends HttpServlet implements Serializable {
private static final long serialVersionUID = 1L;
public static final String TEST = "testing";
public String string = TEST;
public String example = "example String";
public String forename;
public Session session;
private HibernateUtil hibernateUtil;
#Bean
public DisplayStatsDAO displayStatsDAO() {
return new DisplayStatsDAO();
}
public DisplayStatsDAO() {
}
#Transactional
public String getForename() {
#SuppressWarnings("rawtypes")
ArrayList result = new ArrayList();
String returnValue = "";
Session session = hibernateUtil.getSessionFactory().getCurrentSession();
if (session == null) {
System.out.println("NULL SESSION");
} else {
try {
session.beginTransaction();
Authentication authentication = SecurityContextHolder
.getContext().getAuthentication();
String userLoggedIn = authentication.getName();
System.out.println("SESSION IS ACTIVE");
System.out.println(userLoggedIn);
Criteria criteria = session.createCriteria(UserBean.class);
criteria.add(Restrictions.like("username", userLoggedIn));
List<UserBean> user = (List<UserBean>) criteria.list();
session.getTransaction().commit();
for (UserBean userDetails : user) {
result.add(userDetails.getForename());
returnValue = userDetails.getForename().toString();
}
} catch (HibernateException e) {
e.printStackTrace();
}
System.out.println("Return value is " + returnValue);
}
return returnValue;
}
public Session getSession() {
return session;
}
public void setSession(Session session) {
this.session = session;
}
public String getLoggedInUserName() {
Authentication authentication = SecurityContextHolder.getContext()
.getAuthentication();
String userLoggedIn = authentication.getName();
return userLoggedIn;
}
#Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
req.getRequestDispatcher("userstats.jsp").forward(req, resp);
}
}
hibernate.cfg.xml:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<!-- Database connection settings -->
<property name="hibernate.connection.driver_class">
oracle.jdbc.OracleDriver
</property>
<property name="hibernate.connection.url">
jdbc:oracle:thin:system/system#localhost:1521/XE
</property>
<property name="hibernate.connection.username">system</property>
<property name="hibernate.connection.password">password</property>
<!-- Oracle dialect declaration -->
<property name="hibernate.dialect">
org.hibernate.dialect.Oracle10gDialect
</property>
<property name="show_sql">true</property>
<mapping resource="com/sga/app/xml/sga.hbm.xml"></mapping>
</session-factory>
</hibernate-configuration>
HibernateUtil.java:
package com.sga.app.hibernate;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;
import org.hibernate.service.ServiceRegistryBuilder;
public class HibernateUtil {
private static SessionFactory sessionFactory;
private static ServiceRegistry serviceRegistry;
public HibernateUtil() {
sessionFactory = createSessionFactory();
}
public SessionFactory getSessionFactory() {
return HibernateUtil.sessionFactory;
}
private static SessionFactory createSessionFactory() {
Configuration configuration = new Configuration();
configuration.configure("hibernate.cfg.xml");
serviceRegistry = new ServiceRegistryBuilder().applySettings(
configuration.getProperties()).buildServiceRegistry();
sessionFactory = configuration.buildSessionFactory(serviceRegistry);
return sessionFactory;
}
}
Pom.xml:
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>SgaWebApp</groupId>
<artifactId>SgaWebApp</artifactId>
<version>0.0.1-SNAPSHOT</version>
<build>
<sourceDirectory>src</sourceDirectory>
<plugins>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.1</version>
<configuration>
<source>1.7</source>
<target>1.7</target>
</configuration>
</plugin>
</plugins>
</build>
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-beans</artifactId>
<version>4.1.4.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>4.1.4.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>4.1.4.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>4.1.4.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>4.1.4.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>4.1.4.RELEASE</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>
<dependency>
<groupId>javax.validation</groupId>
<artifactId>validation-api</artifactId>
<version>1.0.0.GA</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-validator</artifactId>
<version>4.2.0.Final</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-expression</artifactId>
<version>4.1.4.RELEASE</version>
</dependency>
<dependency>
<groupId>commons-validator</groupId>
<artifactId>commons-validator</artifactId>
<version>1.4.1</version>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-core</artifactId>
<version>3.2.5.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-web</artifactId>
<version>3.2.5.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-config</artifactId>
<version>3.2.5.RELEASE</version>
</dependency>
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.12</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-orm</artifactId>
<version>4.1.1.RELEASE</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>4.1.4.Final</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
<version>1.6.4</version>
</dependency>
<dependency>
<groupId>javassist</groupId>
<artifactId>javassist</artifactId>
<version>3.12.1.GA</version>
</dependency>
</dependencies>
</project>
app.hbm.xml:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD
3.0//EN""http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
<class name="com.sga.app.beans.UserBean" table="USERS">
<id name="username" type="varchar">
<column name="USERNAME"></column>
</id>
<property name="roundScore" type="int">
<column name="ROUNDSCORE"></column>
</property>
<property name="fairways_hit" type="int">
<column name="FAIRWAYS_HIT"></column>
</property>
<property name="gir" type="int">
<column name="GIR"></column>
</property>
<property name="sand_saves" type="int">
<column name="SAND_SAVES"></column>
</property>
<property name="putts" type="int">
<column name="PUTTS"></column>
</property>
</class>
</hibernate-mapping>
userstats.jsp:
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%# taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%# taglib prefix="sql" uri="http://java.sun.com/jsp/jstl/sql"%>
<%# taglib prefix="sf" uri="http://www.springframework.org/tags/form"%>
<%# taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<link href="${pageContext.request.contextPath}/static/css/main.css"
rel="stylesheet" type="text/css">
<title>SGA-user stats</title>
</head>
<body>
</div>
<br />
<!-- Logout option -->
<div id="logoutOptionDiv" align="right">
<a id="logoutOption" style="color: blue;"
href='<c:url value="/j_spring_security_logout"></c:url>'>Logout</a>
</div>
<br />
<h2 class="displayStatsLeaderboardHeader">Your stats</h2>
<table class="displayStatsTable" border="1">
<tr>
<td>Username</td>
<td>Forename</td>
<td>Surname</td>
</tr>
<tr>
<td class="displayStatsTableData">${stats}</td>
<td class="displayStatsTableData">${stats.string}</td>
<td class="displayStatsTableData">${stats.example}</td>
</tr>
</table>
</body>
</html>
Your hibernateUtil field is null. In fact, why did you introduce an instance field for that? Nothing is injected into it and you call a instance method on this null field. Make the method static as:
public static SessionFactory getSessionFactory() {
return sessionFactory;
}
and then :
Session session = HibernateUtil.getSessionFactory().getCurrentSession();
Try This :-
Replace your HibernateUtil class with this one:-
import org.hibernate.cfg.AnnotationConfiguration;
import org.hibernate.SessionFactory;
public class HibernateUtil {
private static final SessionFactory sessionFactory;
static {
try {
sessionFactory = new AnnotationConfiguration().configure().buildSessionFactory();
} catch (Throwable ex) {
System.err.println("Initial SessionFactory creation failed." + ex);
throw new ExceptionInInitializerError(ex);
}
}
public static SessionFactory getSessionFactory() {
return sessionFactory;
}
}
and you should also try
SessionFactory sessionFactory = HibernateUtil.getSessionFactory();
Session session = sessionfactory.openSession();
instead of
Session session = hibernateUtil.getSessionFactory().getCurrentSession();
I hope it will work,.
Updated
#Autowired
private HibernateUtil hibernateUtil;
The null-pointer exception was eradicated when I changed the line:
Session session = hibernateUtil.getSessionFactory().getCurrentSession();
to:
session = HibernateUtil.createSessionFactory().openSession();
I thought the problem was that I was originally attempting to get a session that was currently closed but I'd have expected to receive the 'session is closed!' message that I've seen previously? Anyway the null-pointer exception has been resolved.
(the code within the createSessionFactory() method in HibernateUtil was not changed)

Categories