JPA TransactionRequiredException - java

I am new to Spring and JPA I am having an issue with a TransactionRequiredException. I tried the tips located here, here and here (such as annotating with #Transactional, starting transactions manually etc.)
My code is as follows:
Goal.java
#Entity
#Table(name = "goals")
public class Goal
{
#Id
#GeneratedValue
#Column(name = "GOAL_ID")
private Long id;
#Range(min = 1, max = 120)
#Column(name = "MINUTES")
private int minutes;
public int getMinutes()
{
return minutes;
}
public void setMinutes(int minutes)
{
this.minutes = minutes;
}
public Long getId()
{
return id;
}
public void setId(Long id)
{
this.id = id;
}
}
GoalRepositoryImpl.java
#Repository("goalRepository")
#Transactional
public class GoalRepositoryImpl implements IGoalRepository
{
#PersistenceContext
private EntityManager em;
public Goal save(Goal goal)
{
em.persist(goal);
return goal;
}
}
GoalServiceImpl.java
#Service("goalService")
public class GoalServiceImpl implements IGoalService
{
#Autowired
private IGoalRepository goalRepository;
#Transactional
public Goal save(Goal goal)
{
return goalRepository.save(goal);
}
}
GoalController
#Controller
#SessionAttributes("goal")
public class GoalController
{
#Autowired
private IGoalService goalService;
#RequestMapping(value = "/addGoal", method = RequestMethod.POST)
public String updateGoal(#Valid #ModelAttribute("goal") Goal goal, BindingResult result){
if (result.hasErrors()){
return "addGoal";
}else{
goalService.save(goal);
}
return "redirect:addMinutes.html";
}
}
jpaContext.xml
<?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"
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/tx http://www.springframework.org/schema/tx/spring-tx.xsd">
<context:annotation-config/>
<bean class="org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor" />
<bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="persistenceUnitName" value="punit" />
<property name="dataSource" ref="datasource"/>
<property name="jpaVendorAdapter">
<bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
</bean>
</property>
<property name="jpaPropertyMap">
<map>
<entry key="hibernate.dialect" value="org.hibernate.dialect.MySQL5InnoDBDialect"/>
<entry key="hibernate.hbm2ddl.auto" value="create"/>
<entry key="hibernate.format_sql" value="true"/>
</map>
</property>
</bean>
<bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
<property name="entityManagerFactory" ref="entityManagerFactory" />
</bean>
<tx:annotation-driven transaction-manager="transactionManager"/>
<bean id="datasource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver" />
<property name="url" value="jdbc:mysql://localhost:3306/fitness_tracker?autoReconnect=true"/>
<property name="username" value="root" />
<property name="password" value="root" />
</bean>
Tomcat Log
SEVERE: Servlet.service() for servlet [fitTrackerServlet] in context with path [] threw exception [Request processing failed; nested exception is javax.persistence.TransactionRequiredException: No EntityManager with actual transaction available for current thread - cannot reliably process 'persist' call] with root cause
javax.persistence.TransactionRequiredException: No EntityManager with actual transaction available for current thread - cannot reliably process 'persist' call
at org.springframework.orm.jpa.SharedEntityManagerCreator$SharedEntityManagerInvocationHandler.invoke(SharedEntityManagerCreator.java:282)
at com.sun.proxy.$Proxy41.persist(Unknown Source)
at ie.wit.repository.GoalRepositoryImpl.save(GoalRepositoryImpl.java:22)
at ie.wit.service.GoalServiceImpl.save(GoalServiceImpl.java:25)
at ie.wit.controller.GoalController.updateGoal(GoalController.java:40)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:221)
at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:136)
at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:114)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:827)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:738)
at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:85)
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:963)
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:897)
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:970)
at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:872)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:650)
at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:846)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:731)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:303)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:241)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:218)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:122)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:505)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:169)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:103)
at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:956)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:116)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:442)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1082)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:623)
at org.apache.tomcat.util.net.AprEndpoint$SocketProcessor.doRun(AprEndpoint.java:2517)
at org.apache.tomcat.util.net.AprEndpoint$SocketProcessor.run(AprEndpoint.java:2506)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
at java.lang.Thread.run(Thread.java:745)

There are things i cannot see from your project, so i cannot be sure
include spring.tx in your pom or add the library whichever way you are doing it
#Configuration #EnableTransactionManagement
without these two steps you cannot start or commit a transaction.

Related

Getting null pointer exception while using abstract factory pattern in spring-mvc [duplicate]

This question already has answers here:
Why is my Spring #Autowired field null?
(21 answers)
Closed 6 years ago.
Its the First time i am integrating spring with hibernate, When i
invoke any method of Dao class i am getting null pointer Exception
I am using abstract factory pattern Source code of Abstract class :
public abstract class Content {
#Autowired
HibernateOperations ho;
#Transactional
public List<ContentDes> getContentDes(String sql,int limit){
//do it with autowired
List<Object[]> ls = new ArrayList<Object[]>();
List<ContentDes> contentDes_ls = new ArrayList<ContentDes>();
System.out.println("--before invoking method---");
ho.just_print();
ls = ho.getResultListByLimit(sql,limit);
for(Object[] obj: ls){
ContentDes contentDes = new ContentDes();
contentDes.setCode((String)obj[0]);
contentDes.setContent_prv((String)obj[1]);
contentDes.setPricetag((String)obj[2]);
contentDes_ls.add(contentDes);
}
return contentDes_ls;
}
abstract List<ContentDes> getRandomContent(int limit);
//abstract List<ContentDes> getDistinctCat();
}
And i have five class that are extending my Content Class: coding of
one of my child id liem below:
public class Wallpaper extends Content{
#Override
public List<ContentDes> getRandomContent(int limit) {
String sql = "select code,prv,pricetag from Wallpaper where cat not like 'Holy Deities' order by rand() limit "+limit+"";
List<ContentDes> contentDes_ls = new ArrayList<ContentDes>();
contentDes_ls = getContentDes(sql,limit);
return contentDes_ls;
}
}
And class which returning clasess obects according to the content type
is :
public class GetContentFactory {
//use getContent method to get object of type Content
public Content getContent(String contentType) {
contentType = contentType.toLowerCase();
if (contentType.equalsIgnoreCase("wallpaper")) {
return new Wallpaper();
} else if (contentType.equalsIgnoreCase("animation")) {
return new Animation();
} else if (contentType.equalsIgnoreCase("ringtone")) {
return new Ringtone();
} else if (contentType.equalsIgnoreCase("video")) {
return new Video();
}
else if (contentType.equalsIgnoreCase("game")) {
return new Game();
}
else {
System.out.println(" unknow request in GetContentFactory class");
}
return null;
}
}//end of GetContentFactory class.
My main class is :
public class GetContent {
GetContentFactory contentFactory = new GetContentFactory();
}
public List<ContentDes> getRandomContent(String content_type, int limit) {
List<ContentDes> contentDes_ls = new ArrayList<ContentDes>();
Content con = contentFactory.getContent(content_type);
contentDes_ls = con.getRandomContent(limit);
for (ContentDes contentDes : contentDes_ls) {
System.out.println("prv----"+contentDes.getContent_prv());
}
return contentDes_ls;
}
}
Code of my dao class is :
#Repository
public class HibernateOperations {
private SessionFactory sessionFactory;
public void setSessionFactory(SessionFactory sf){
this.sessionFactory = sf;
}
//pass the sql query to get result for multiple column
public List<Object[]> getResultListByLimit(String query,int limit){
System.out.println("in get result-------");
Session session = this.sessionFactory.getCurrentSession();
List<Object[]> ls_ob = new ArrayList<Object[]>();
Query q = session.createQuery(query);
q.setMaxResults(limit);
ls_ob = (List<Object[]>)q.list();
return ls_ob;
}
public List<Object> getListForSingleColumn(String query){
Session session = this.sessionFactory.getCurrentSession();
List<Object> ls_ob = new ArrayList<Object>();
Query q = session.createQuery(query);
ls_ob = q.list();
return ls_ob;
}
public void SaveObject(Object obj){
Session session = this.sessionFactory.getCurrentSession();
List<Object[]> ls_ob = new ArrayList<Object[]>();
session.save(obj);
}
public void just_print(){
System.out.println("---------in method hibenate operation------");
}
}
when My controller class methods call:
GetContent gc = new GetContent();
List<ContentDes> contentDes_ls = new ArrayList<ContentDes>();
contentDes_ls = gc.getRandomContent("wallpaper", 3);
i got an exception:
its prints the
--before invoking method---(its is the sout of my content class method Name "getContentDes")
Apr 25, 2016 6:03:04 PM org.apache.catalina.core.StandardWrapperValve invoke
SEVERE: Servlet.service() for servlet [DefaultServlet] in context with path [/slwap_sh] threw exception [Request processing failed; nested exception is java.lang.NullPointerException] with root cause
java.lang.NullPointerException
at lanka.content.get.Content.getContentDes(Content.java:37)
at lanka.content.get.Wallpaper.getRandomContent(Wallpaper.java:45)
at lanka.content.controller.ContentController.sriWap(ContentController.java:65)
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.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:222)
at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:137)
at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:110)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:814)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:737)
at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:85)
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:959)
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:893)
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:969)
at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:860)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:622)
at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:845)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:729)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:291)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:239)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:212)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:106)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:502)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:141)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:79)
at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:616)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:88)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:518)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1096)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:674)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1500)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.run(NioEndpoint.java:1456)
at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
at java.lang.Thread.run(Unknown Source)
I am unable to call any of my Dao Class methods i got null pointer
when i called any method of my Dao(HibernateOperations.java) Class
Can anyone please help me to find out my mistake
coding of DefaultServlet-servlet.xml is like below:
<?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:mvc="http://www.springframework.org/schema/mvc"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:aop="http://www.springframework.org/schema/aop"
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
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop.xsd">
<mvc:annotation-driven />
<mvc:annotation-driven enable-matrix-variables="true" />
<context:component-scan base-package="lanka.content.controller" />
<context:component-scan base-package="lanka.content.domain" />
<context:component-scan base-package="lanka.content.utility" />
<bean
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/jsp/" />
<property name="suffix" value=".jsp" />
</bean>
<!-- start of languages xml code -->
<!-- lang param is defined in the mvc interceptor -->
<bean id="messageSource"
class="org.springframework.context.support.ReloadableResourceBundleMessageSource">
<property name="basename" value="WEB-INF/propFiles/content" />
<property name="defaultEncoding" value="UTF-8" />
</bean>
<bean id="localeResolver"
class="org.springframework.web.servlet.i18n.CookieLocaleResolver">
<property name="defaultLocale" value="en" />
</bean>
<!-- end of languages xml code -->
<mvc:interceptors>
<mvc:interceptor>
<mvc:mapping path="/**" />
<bean
class="org.springframework.web.servlet.i18n.LocaleChangeInterceptor">
<property name="paramName" value="lang" />
</bean>
</mvc:interceptor>
<!-- <mvc:interceptor>
<mvc:mapping path="/**" />
<mvc:exclude-mapping path="/resources/**"/>
<bean id="storingWapHits"
class="vodafone.interceptor.StroringHits">
</bean>
</mvc:interceptor> -->
</mvc:interceptors>
<mvc:resources mapping="/resources/**" location="/resources/design/" />
<!-- start of hibernate integration -->
<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/wapsite" />
<property name="username" value="root" />
<property name="password" value="" />
</bean>
<!-- hibernate4AnnotatedSessionFactory is a session fectory-->
<!-- Hibernate 4 SessionFactory Bean definition -->
<bean id="hibernate4AnnotatedSessionFactory"
class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="annotatedClasses">
<list>
<value>lanka.content.table.Game</value>
<value>lanka.content.table.Scrsaver</value>
<value>lanka.content.table.Video</value>
<value>lanka.content.table.Wallpaper</value>
</list>
</property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect
</prop>
<prop key="hibernate.show_sql">true</prop>
</props>
</property>
</bean>
<tx:annotation-driven transaction-manager="transactionManager" />
<bean id="transactionManager"
class="org.springframework.orm.hibernate4.HibernateTransactionManager">
<property name="sessionFactory" ref="hibernate4AnnotatedSessionFactory" />
</bean>
<!-- <bean id="personService" class="com.journaldev.spring.service.PersonServiceImpl">
<property name="personDAO" ref="personDAO"></property>
</bean>-->
<bean id="HibernateOperations" class="lanka.content.utility.HibernateOperations">
<property name="sessionFactory" ref="hibernate4AnnotatedSessionFactory" />
</bean>
</beans>
By doing :
new Wallpaper();
You are not letting spring do his work, that is to say inject things in your objects :
#Autowired
HibernateOperations ho;
ho will always be null.
Every Content subclasses should be spring beans, and you have to get rid of your GetContentFactory, and only autowire every single spring bean
EDIT : Abstract Factory Design
Define your beans like this :
#Component
#Scope(BeanDefinition.SCOPE_PROTOTYPE)
public class Wallpaper extends Content {
Declare the GetContentFactory as a spring bean as well :
#Component
public class GetContentFactory {
#Autowired
private Wallpaper wallpaper;
This has to be avoided as well :
GetContentFactory contentFactory = new GetContentFactory();

HTTP Status 500 - Request processing failed. Nested exception is java.lang.NullPointerException [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 7 years ago.
So I have little problem. I can't add informations to database because I get an error:
HTTP Status 500 - Request processing failed; nested exception is java.lang.NullPointerException
Here is my controller:
package pl.edu.controller;
#Controller
public class StudentAdmissionController {
#RequestMapping(value = "/admissionForm.html", method = RequestMethod.GET)
public ModelAndView getAdmissionForm() {
ModelAndView model = new ModelAndView("AdmissionForm");
return model;
}
#RequestMapping(value = "/submitAdmissionForm.html", method = RequestMethod.POST)
public ModelAndView submitAdmissionForm(#RequestParam("pojemnosc") float pojemnosc,
#RequestParam("modelSamochodu") String modelSamochodu, #RequestParam("liczbaPasazerow") int liczbaPasazerow,
#RequestParam("liczbaDrzwi") int liczbaDrzwi) {
ModelAndView model = new ModelAndView("AdmissionSuccess");
Silnik silnik = new Silnik();
silnik.setPojemnosc(pojemnosc);
silnik.setId(1);
Samochod samochod = new Samochod();
samochod.setSilnik(silnik);
samochod.setLiczbaDrzwi(liczbaDrzwi);
samochod.setLiczbaPasazerow(liczbaPasazerow);
samochod.setModel(modelSamochodu);
samochod.setLiczbaPoduszek(liczbaPasazerow * 2);
samochod.setId(1);
model.addObject("msg",
"Details submited by you: Pojemnosc: " + silnik.getPojemnosc() + " Model: " + samochod.getModel()
+ ", Liczba drzwi: " + samochod.getLiczbaDrzwi() + ", Liczba pasazerow: "
+ samochod.getLiczbaPasazerow() + ", Liczba poduszek: " + samochod.getLiczbaPoduszek());
SamochodDao samochodDao = new SamochodDao();
samochodDao.dodaj(samochod);
return model;
}
}
My SamochodDao class:
public class SamochodDao {
private JdbcTemplate jdbcTemplate;
#Autowired
public void setDataSource(DataSource dataSource) {
this.jdbcTemplate = new JdbcTemplate(dataSource);
}
#Transactional
public void dodaj(final Samochod samochod) {
final String engineQuery = "insert into silnik (pojemnosc) values (?)";
KeyHolder keyHolder = new GeneratedKeyHolder();
jdbcTemplate.update(new PreparedStatementCreator() {
public PreparedStatement createPreparedStatement(Connection connection) throws SQLException {
PreparedStatement ps = connection.prepareStatement(engineQuery, new String[] { "id" });
ps.setFloat(1, samochod.getSilnik().getPojemnosc());
return ps;
}
}, keyHolder);
String carQuery = "insert into samochod (id, silnik,model,liczbaDrzwi,liczbaPasazerow,liczbaPoduszek) values (?,?,?,?,?,?)";
Object[] inputs = new Object[] { keyHolder.getKey(), keyHolder.getKey(), samochod.getModel(),
samochod.getLiczbaDrzwi(), samochod.getLiczbaPasazerow(), samochod.getLiczbaPoduszek() };
jdbcTemplate.update(carQuery, inputs);
}
public void usun(int id) {
String query = "DELETE FROM samochod WHERE id = ?";
Object[] inputs = new Object[] { id };
jdbcTemplate.update(query, inputs);
query = "DELETE FROM silnik WHERE id = ?";
jdbcTemplate.update(query, inputs);
}
#SuppressWarnings({ "rawtypes", "unchecked" })
public List<Samochod> listuj() {
String sql = "SELECT * FROM Silnik";
List<Silnik> listaSilnikow = jdbcTemplate.query(sql, new BeanPropertyRowMapper(Silnik.class));
List<Samochod> listaSamochodow = new ArrayList();
for (Silnik silnik : listaSilnikow) {
sql = "SELECT * FROM samochod WHERE id = ?";
Samochod samochod = (Samochod) jdbcTemplate.queryForObject(sql, new Object[] { silnik.getId() },
new SamochodRowMapper());
samochod.setSilnik(silnik);
listaSamochodow.add(samochod);
}
return listaSamochodow;
}
}
And my servlet.xml:
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:context="http://www.springframework.org/schema/context"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd">
<context:component-scan base-package="pl.edu" />
<bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix">
<value>/WEB-INF/</value>
</property>
<property name="suffix">
<value>.jsp</value>
</property>
</bean>
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver" />
<property name="url" value="jdbc:mysql://localhost:3306/spring" />
<property name="username" value="root" />
<property name="password" value="" />
</bean>
</beans>
And when I'm trying to add new "Samochod" to database I have error:
HTTP Status 500 - Request processing failed; nested exception is java.lang.NullPointerException
type Exception report
message Request processing failed; nested exception is java.lang.NullPointerException
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:978)
org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:868)
javax.servlet.http.HttpServlet.service(HttpServlet.java:648)
org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:842)
javax.servlet.http.HttpServlet.service(HttpServlet.java:729)
org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
root cause
java.lang.NullPointerException
pl.edu.dao.SamochodDao.dodaj(SamochodDao.java:26)
pl.edu.controller.StudentAdmissionController.submitAdmissionForm(StudentAdmissionController.java:48)
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:497)
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:943)
org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:877)
org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:966)
org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:868)
javax.servlet.http.HttpServlet.service(HttpServlet.java:648)
org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:842)
javax.servlet.http.HttpServlet.service(HttpServlet.java:729)
org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
Somebody have maybe any idea what I'm doing wrong?
#edit
Line 26 from SamochodDao:
jdbcTemplate.update(new PreparedStatementCreator() {
#edit2
Btw. When I'm running this code as test, it works ok. Here are my beans from normal application:
<?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:tx="http://www.springframework.org/schema/tx"
xmlns:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-2.5.xsd ">
<aop:aspectj-autoproxy />
<tx:annotation-driven transaction-manager="transactionManager" />
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource" />
</bean>
<bean id="Silnik" class="pl.edu.lab1.Silnik">
<property name="pojemnosc" value="1.4"></property>
<property name="id" value="1"></property>
</bean>
<bean id="Samochod" class="pl.edu.lab1.Samochod">
<property name="silnik" ref="Silnik"></property>
<property name="model" value="Audi"></property>
<property name="liczbaPasazerow" value="2"></property>
<property name="liczbaDrzwi" value="4"></property>
<property name="liczbaPoduszek" value="2"></property>
<property name="id" value="1"></property>
</bean>
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver" />
<property name="url" value="jdbc:mysql://localhost:3306/spring" />
<property name="username" value="root" />
<property name="password" value="" />
</bean>
<bean id="SamochodDao" class="pl.edu.dao.SamochodDao">
<property name="dataSource" ref="dataSource" />
</bean>
</beans>
But when I change it to web-app I have errors.
It looks like jdbcTemplate is nullValue because it is created in controller.
Try to create Dao instance once in context and autowired into controller.

Spring Data: Injected repository is null

I had Spring Data's repository working in a #Controller a short while ago. Having moved data access down into a #Service, it stopped working. Everything looks fine to me.... Why is this DI failing?
Here's my spring-config:
<?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:data="http://www.springframework.org/schema/data/jpa"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd
http://www.springframework.org/schema/data/jpa
http://www.springframework.org/schema/data/jpa/spring-jpa.xsd">
<bean id="jpaVendorAdapter" class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
<property name="database" value="POSTGRESQL" />
<property name="databasePlatform" value="org.hibernate.dialect.PostgreSQLDialect" />
</bean>
<bean id="jpaDialect" class="org.springframework.orm.jpa.vendor.HibernateJpaDialect" />
<bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
<property name="entityManagerFactory" ref="entityManagerFactory" />
<property name="dataSource" ref="dataSource" />
<property name="jpaDialect" ref="jpaDialect" />
</bean>
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="org.postgresql.Driver" />
<property name="url" value="jdbc:postgresql://localhost:5432/cp" />
<property name="username" value="cp_user" />
<property name="password" value="+JMJ+pw0m2d" />
</bean>
<data:repositories base-package="com.mydomain.data.repository" />
<mvc:annotation-driven />
</beans>
My application:
#ComponentScan
#EnableAutoConfiguration
#ImportResource("classpath:spring-config.xml")
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
My controller:
#Controller
#RequestMapping("/app/user")
#ExposesResourceFor(User.class)
public class UserController {
#RequestMapping(value = "/{userid}", method = RequestMethod.GET, produces = "application/json")
#ResponseBody
public HttpEntity<UserResource> get(#PathVariable("userid") long id) {
ProfileService ps = new ProfileService();
UserResource resource = ps.get(id);
return new ResponseEntity<UserResource>(resource, HttpStatus.OK);
}
}
And my service:
#Service
#ExposesResourceFor(User.class)
public class ProfileService {
#Inject
private UserRepository users;
public UserResource get(long id) {
Long longId = new Long(id);
User user = users.findOne(longId); // Line 24
if (user == null) {
throw new ResourceNotFoundException();
}
UserMapper assembler = new UserMapper();
UserResource resource = assembler.toResource(user);
return resource;
}
public void update(UserResource resource) {
UserMapper assembler = new UserMapper();
User user = assembler.toEntity(resource);
users.save(user);
}
}
Throwing exception:
java.lang.NullPointerException
com.mydomain.service.ProfileService.get(ProfileService.java:24)
com.mydomain.app.web.UserController.get(UserController.java:74)
sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
java.lang.reflect.Method.invoke(Unknown Source)
org.springframework.web.method.support.InvocableHandlerMethod.invoke(InvocableHandlerMethod.java:214)
org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:132)
org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:104)
org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandleMethod(RequestMappingHandlerAdapter.java:748)
org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:689)
org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:83)
org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:947)
org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:878)
org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:946)
org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:837)
javax.servlet.http.HttpServlet.service(HttpServlet.java:621)
org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:822)
javax.servlet.http.HttpServlet.service(HttpServlet.java:728)
org.springframework.web.filter.HiddenHttpMethodFilter.doFilterInternal(HiddenHttpMethodFilter.java:77)
org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:108)
Where ProfileService:24 is:
User user = users.findOne(longId);
In your controller you create ProfileService instance with a new keyword and it is not managed by Spring (Spring doesn't know about it and cannot inject UserRepository - this causes NullPointerException). You have to inject ProfileService into UserController the same way you inject UserRepository into ProfileService. For example:
#Controller
#RequestMapping("/app/user")
#ExposesResourceFor(User.class)
public class UserController {
#Autowired
private ProfileService profileService;
#RequestMapping(value = "/{userid}", method = RequestMethod.GET, produces = "application/json")
#ResponseBody
public HttpEntity<UserResource> get(#PathVariable("userid") long id) {
UserResource resource = profileService.get(id);
return new ResponseEntity<UserResource>(resource, HttpStatus.OK);
}
}

bitronix- Unable to locate current JTA transaction

Hi I have a Java web application using spring and hibernate.
I have a model class called Role. For all model classes there is common GenericDao.java
public interface GenericDao<T>{
public void insert(T transientInstance);
public T findById(Class<?> clazz, Serializable id);
}
GenericHibernateDao.java
#Repository
public class GenericHibernateDao<T extends Serializable>
implements GenericDao<T>{
#Resource
protected SessionFactory sessionFactory;
#Override
public void insert(T transientInstance) {
sessionFactory.getCurrentSession().persist(transientInstance);
}
#SuppressWarnings("unchecked")
#Override
public T findById(Class<?> clazz, Serializable id) {
return (T) sessionFactory.getCurrentSession().get(clazz, id);
}
}
RoleService.java
public interface RoleService {
public void insert(Role role);
public Role findById(Integer id);
}
And has its implementation RoleServiceImpl.java
#Service
public class RoleServiceImpl implements RoleService {
#Autowired
private GenericDao<Role> roleDao;
#Override
public void insert(Role role) {
roleDao.insert(role);
}
#Override
public Role findById(Integer id) {
return roleDao.findById(Role.class, id);
}
}
I have a controller which calls this findbyid methid and passing a value - RegisterController.java
#Controller
public class UserRegisterController {
#Autowired
public RoleService roleService;
#RequestMapping(value = "/register", method = RequestMethod.POST, consumes= MediaType.APPLICATION_JSON_VALUE)
#ResponseBody
public void registerUser(#RequestBody User user)
{
Role role=new Role();
role=roleService.findById(1);
System.out.println("Saved");
}
}
Finally my spring applicationContext.xml is
<bean id="dataSource" class="bitronix.tm.resource.jdbc.PoolingDataSource"
init-method="init" destroy-method="close">
<property name="className"
value="com.mysql.jdbc.jdbc2.optional.MysqlXADataSource" />
<property name="uniqueName" value="ocr/DocumentDatabase" />
<property name="minPoolSize" value="1" />
<property name="maxPoolSize" value="5" />
<property name="automaticEnlistingEnabled" value="true" />
<property name="allowLocalTransactions" value="true" />
<property name="useTmJoin" value="true" />
<property name="shareTransactionConnections" value="true" />
<property name="driverProperties">
<props>
<prop key="url">${jdbc.url}</prop>
<prop key="user">${jdbc.username}</prop>
<prop key="password">${jdbc.password}</prop>
</props>
</property>
</bean>
<bean id="bitronixTransactionManager" factory-method="getTransactionManager"
class="bitronix.tm.TransactionManagerServices" depends-on="btmConfig, dataSource"
destroy-method="shutdown" />
<bean id="transactionManager"
class="org.springframework.transaction.jta.JtaTransactionManager">
<property name="transactionManager" ref="bitronixTransactionManager" />
<property name="userTransaction" ref="bitronixTransactionManager" />
</bean>
<tx:annotation-driven transaction-manager="transactionManager" />
<bean id="sessionFactory"
class="org.springframework.orm.hibernate4.LocalSessionFactoryBean"
destroy-method="destroy">
<property name="dataSource" ref="dataSource" />
<property name="jtaTransactionManager" ref="transactionManager"/>
<property name="configLocation" value="classpath:hibernate.cfg.xml" />
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">${hibernate.dialect}</prop>
<prop key="hibernate.query.substitutions">true 'Y', false 'N'</prop>
</props>
</property>
</bean>
I run this application in tomcat. It gives the following error.
SEVERE: Servlet.service() for servlet [myappdemo] in context with path [/myappdemo] threw exception [Request processing failed; nested exception is org.hibernate.HibernateException: Unable to locate current JTA transaction] with root cause
org.hibernate.HibernateException: Unable to locate current JTA transaction
at org.hibernate.context.internal.JTASessionContext.currentSession(JTASessionContext.java:88)
at org.springframework.orm.hibernate4.SpringSessionContext.currentSession(SpringSessionContext.java:90)
at org.hibernate.internal.SessionFactoryImpl.getCurrentSession(SessionFactoryImpl.java:980)
at com.myapp.myappdemo.dao.hibernate.GenericHibernateDao.findById(GenericHibernateDao.java:46)
at com.myapp.myappdemo.dao.hibernate.GenericHibernateDao.findById(GenericHibernateDao.java:15)
at com.myapp.myappdemo.service.impl.RoleServiceImpl.findById(RoleServiceImpl.java:38)
at com.myapp.myappdemo.web.UserRegisterController.registerUser(UserRegisterController.java:36)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:606)
at org.springframework.web.method.support.InvocableHandlerMethod.invoke(InvocableHandlerMethod.java:219)
at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:132)
at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:104)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandleMethod(RequestMappingHandlerAdapter.java:745)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:686)
at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:80)
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:925)
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:856)
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:920)
at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:827)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:647)
at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:801)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:728)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:305)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:222)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:123)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:502)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:171)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:99)
at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:953)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:118)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:408)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1023)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:589)
at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:310)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
at java.lang.Thread.run(Thread.java:744)
It happens when I call the roleService.findById(1);
Why its happening? And how can I resolve?
I am using spring 3.2.1.RELEASE, Hibernate 4.2.0.Final, btm 2.1.3
The sessionFactory is configured to use JtaTransactionManager. When you do that, hibernate is smart enough to look into current transactionnal resources to find the session.
Your spring configuration allows you to use annotations to do transaction demarcation.
Your transaction manager seems correctly configured.
So, everything looks fine. The only missing part are the transactional annotations !
Just add #Transactional in your service layer:
#Override
#Transactional
public Role findById(Integer id) {
return roleDao.findById(Role.class, id);
}
(you can also put this annotation on the service class)

Error com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException

I have a spring application using hibernate. I am trying to insert user object to the database table. But I am getting following error.
Hibernate: insert into USER (CONTACT_NUMBER, EMAIL, FIRST_NAME, LAST_NAME) values (?, ?, ?, ?)
Nov 08, 2013 7:23:03 PM org.apache.catalina.core.StandardWrapperValve invoke
SEVERE: Servlet.service() for servlet [spring] in context with path [/SpringFreeMakerHibernateMaven] threw exception [Request processing failed; nested exception is org.hibernate.exception.SQLGrammarException: could not insert: [com.model.User]] with root cause
com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: Table 'testspring.user' doesn't exist
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(Unknown Source)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(Unknown Source)
at java.lang.reflect.Constructor.newInstance(Unknown Source)
at com.mysql.jdbc.Util.handleNewInstance(Util.java:406)
at com.mysql.jdbc.Util.getInstance(Util.java:381)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:1030)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:956)
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3558)
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3490)
at com.mysql.jdbc.MysqlIO.sendCommand(MysqlIO.java:1959)
at com.mysql.jdbc.MysqlIO.sqlQueryDirect(MysqlIO.java:2109)
at com.mysql.jdbc.ConnectionImpl.execSQL(ConnectionImpl.java:2643)
at com.mysql.jdbc.PreparedStatement.executeInternal(PreparedStatement.java:2077)
at com.mysql.jdbc.PreparedStatement.executeUpdate(PreparedStatement.java:2362)
at com.mysql.jdbc.PreparedStatement.executeUpdate(PreparedStatement.java:2280)
at com.mysql.jdbc.PreparedStatement.executeUpdate(PreparedStatement.java:2265)
at org.apache.commons.dbcp.DelegatingPreparedStatement.executeUpdate(DelegatingPreparedStatement.java:105)
at org.apache.commons.dbcp.DelegatingPreparedStatement.executeUpdate(DelegatingPreparedStatement.java:105)
at org.hibernate.id.IdentityGenerator$GetGeneratedKeysDelegate.executeAndExtract(IdentityGenerator.java:94)
at org.hibernate.id.insert.AbstractReturningDelegate.performInsert(AbstractReturningDelegate.java:57)
at org.hibernate.persister.entity.AbstractEntityPersister.insert(AbstractEntityPersister.java:2345)
at org.hibernate.persister.entity.AbstractEntityPersister.insert(AbstractEntityPersister.java:2852)
at org.hibernate.action.EntityIdentityInsertAction.execute(EntityIdentityInsertAction.java:71)
at org.hibernate.engine.ActionQueue.execute(ActionQueue.java:273)
at org.hibernate.event.def.AbstractSaveEventListener.performSaveOrReplicate(AbstractSaveEventListener.java:320)
at org.hibernate.event.def.AbstractSaveEventListener.performSave(AbstractSaveEventListener.java:203)
at org.hibernate.event.def.AbstractSaveEventListener.saveWithGeneratedId(AbstractSaveEventListener.java:129)
at org.hibernate.event.def.DefaultSaveOrUpdateEventListener.saveWithGeneratedOrRequestedId(DefaultSaveOrUpdateEventListener.java:210)
at org.hibernate.event.def.DefaultSaveEventListener.saveWithGeneratedOrRequestedId(DefaultSaveEventListener.java:56)
at org.hibernate.event.def.DefaultSaveOrUpdateEventListener.entityIsTransient(DefaultSaveOrUpdateEventListener.java:195)
at org.hibernate.event.def.DefaultSaveEventListener.performSaveOrUpdate(DefaultSaveEventListener.java:50)
at org.hibernate.event.def.DefaultSaveOrUpdateEventListener.onSaveOrUpdate(DefaultSaveOrUpdateEventListener.java:93)
at org.hibernate.impl.SessionImpl.fireSave(SessionImpl.java:713)
at org.hibernate.impl.SessionImpl.save(SessionImpl.java:701)
at org.hibernate.impl.SessionImpl.save(SessionImpl.java:697)
at com.dao.UserDaoImpl.addUser(UserDaoImpl.java:24)
at com.service.UserManagerImpl.addUser(UserManagerImpl.java:25)
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.springframework.aop.support.AopUtils.invokeJoinpointUsingReflection(AopUtils.java:309)
at org.springframework.aop.framework.ReflectiveMethodInvocation.invokeJoinpoint(ReflectiveMethodInvocation.java:183)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:150)
at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:110)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:172)
at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:202)
at $Proxy16.addUser(Unknown Source)
at com.controller.RegistrationController.register(RegistrationController.java:28)
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.springframework.web.bind.annotation.support.HandlerMethodInvoker.invokeHandlerMethod(HandlerMethodInvoker.java:176)
at org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter.invokeHandlerMethod(AnnotationMethodHandlerAdapter.java:426)
at org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter.handle(AnnotationMethodHandlerAdapter.java:414)
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:790)
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:719)
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:644)
at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:560)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:641)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:722)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:304)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:240)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:164)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:164)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:100)
at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:563)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:118)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:403)
at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:301)
at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:162)
at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:309)
at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
at java.lang.Thread.run(Unknown Source)
User.java
#Entity
#Table(name="USER")
public class User {
#Id
#Column(name="ID")
#GeneratedValue
private Integer id;
#Column(name="FIRST_NAME")
private String firstName;
#Column(name="LAST_NAME")
private String lastName;
#Column(name="EMAIL")
private String email;
#Column(name="CONTACT_NUMBER")
private String contact;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
/**
* #return
*/
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getContact() {
return contact;
}
public void setContact(String contact) {
this.contact = contact;
}
public User(){
}
public User(String firstName, String lastName){
this.firstName = firstName;
this.lastName = lastName;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
#Override
public String toString() {
return "User [firstName=" + firstName + ", lastName=" + lastName + "]";
}
}
spring-servlet.xml
<?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:aop="http://www.springframework.org/schema/aop"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:jee="http://www.springframework.org/schema/jee" xmlns:lang="http://www.springframework.org/schema/lang"
xmlns:p="http://www.springframework.org/schema/p" xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:util="http://www.springframework.org/schema/util"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee.xsd
http://www.springframework.org/schema/lang http://www.springframework.org/schema/lang/spring-lang.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd
http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util.xsd">
<context:component-scan base-package="com.controller" />
<bean id="jspViewResolver"
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/jsp/" />
<property name="suffix" value=".jsp" />
</bean>
<bean id="messageSource"
class="org.springframework.context.support.ReloadableResourceBundleMessageSource">
<property name="basename" value="classpath:messages"></property>
<property name="defaultEncoding" value="UTF-8"></property>
</bean>
<bean id="propertyConfigurer"
class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"
p:location="/WEB-INF/jdbc.properties">
</bean>
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"
destroy-method="close" p:driverClassName="${jdbc.driverClassName}"
p:url="${jdbc.databaseurl}" p:username="${jdbc.username}" p:password="${jdbc.password}">
</bean>
<bean id="sessionFactory"
class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource"></property>
<property name="configLocation">
<value>classpath:hibernate.cfg.xml</value>
</property>
<property name="configurationClass">
<value>org.hibernate.cfg.AnnotationConfiguration</value>
</property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">${jdbc.dialect}</prop>
<prop key="hibernate.show_sql">true</prop>
</props>
</property>
</bean>
<bean id="userDao" class="com.dao.UserDaoImpl"></bean>
<bean id="userManager" class="com.service.UserManagerImpl"></bean>
<tx:annotation-driven />
<bean id="transactionManager"
class="org.springframework.orm.hibernate3.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory"></property>
</bean>
</beans>
hibernate.cfg.xml
<?xml version='1.0' encoding='utf-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<mapping class="com.model.User"></mapping>
</session-factory>
</hibernate-configuration>
Can anyone suggest me what I am doing wrong here?
If the table really, really, does exist in mySQL, and your using Linux/Unix, and the error shows the table name in all wrong/upper-case, then the issue is that table names in MySQL are case sensitive and hibernate is upper casing them. I'm using hibernate 4.3.
I just had this issue. Explanation here: lower_case_table_names=1
--edit-- In retrospect, it's probably better to find and change any #Table or hbm.xml references to match the database. I ran a wizard that generated an hbm.xml with uppercase names -- didn't realize that it was in my project until just now. I'll leave this here to make people aware of the case sensitivity.
--end of edit--
Here is how I fixed it:
Drop the database.
Add this to /etc/mysql/my.conf:
set lower_case_table_names=1 #(default value '0').
Restart mysqld.
Recreate the Database.
optional? Change to lowercase all table names in annotations/hbm.xml.
Hibernate won't automatically generate your database schema for you. You have to tell it to do so with a special hibernate property:
hibernate.hbm2ddl.auto
With value update or create based on what you want. See here and the related chapters.
In Spring, the configuration goes
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">${jdbc.dialect}</prop>
<prop key="hibernate.hbm2ddl.auto">create</prop>
<prop key="hibernate.show_sql">true</prop>
</props>
</property>

Categories

Resources