I'm new to spring and I was trying constructor injection. I get an IllegalArgumentException in the first line of the main function. It does not have problems locating the xml file when I use a property tag inside the xml(setter injection) but here it is raising an exception.
Triangle.java
package myPackage;
public class Triangle
{
private String type;
public Triangle(String type) {
this.type = type;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public void draw()
{
System.out.println(getType()+" Triangle Drawn");
}
}
DrawingApp.java
package myPackage;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class DrawingApp {
public static void main(String[] args) {
ApplicationContext context = new ClassPathXmlApplicationContext("spring.xml");
Triangle t = (Triangle) context.getBean("triangle");
t.draw();
}
}
spring.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN" "http://www.springframework.org/dtd/spring-beans.dtd">
<beans>
<bean id="triangle" class="myPackage.Triangle" >
<constructor-arg value="equilateral" />
</bean>
</beans>
These are the errors that I get.
Feb 05, 2018 1:41:14 PM org.springframework.context.support.ClassPathXmlApplicationContext prepareRefresh
INFO: Refreshing org.springframework.context.support.ClassPathXmlApplicationContext#2d8e6db6: startup date [Mon Feb 05 13:41:14 IST 2018]; root of context hierarchy
Feb 05, 2018 1:41:14 PM org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
INFO: Loading XML bean definitions from class path resource [spring.xml]
Feb 05, 2018 1:41:14 PM org.springframework.beans.factory.support.DefaultListableBeanFactory preInstantiateSingletons
INFO: Pre-instantiating singletons in org.springframework.beans.factory.support.DefaultListableBeanFactory#17550481: defining beans [triangle]; root of factory hierarchy
Exception in thread "main" java.lang.IllegalArgumentException
at org.springframework.asm.ClassReader.<init>(Unknown Source)
at org.springframework.asm.ClassReader.<init>(Unknown Source)
at org.springframework.asm.ClassReader.<init>(Unknown Source)
at org.springframework.core.LocalVariableTableParameterNameDiscoverer.inspectClass(LocalVariableTableParameterNameDiscoverer.java:112)
at org.springframework.core.LocalVariableTableParameterNameDiscoverer.getParameterNames(LocalVariableTableParameterNameDiscoverer.java:86)
at org.springframework.beans.factory.support.ConstructorResolver.autowireConstructor(ConstructorResolver.java:193)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.autowireConstructor(AbstractAutowireCapableBeanFactory.java:1049)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:953)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:490)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:461)
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:295)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:223)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:292)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:194)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:607)
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:932)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:479)
at org.springframework.context.support.ClassPathXmlApplicationContext.<init>(ClassPathXmlApplicationContext.java:139)
at org.springframework.context.support.ClassPathXmlApplicationContext.<init>(ClassPathXmlApplicationContext.java:83)
at myPackage.DrawingApp.main(DrawingApp.java:12)
Related
I was reading through a Spring tutorial and came across the following example. It mentioned that Spring supports the Java EE annotation #Resource. I was trying the example with the source below, but it gave an InvocationTargetException. I suppose it was probably due to the SpellChecker object could not be injected properly.
Relevant stacktrace:
Feb 27, 2018 8:56:23 PM org.springframework.context.support.AbstractApplicationContext prepareRefresh
INFO: Refreshing org.springframework.context.support.ClassPathXmlApplicationContext#5d76b067: startup date [Tue Feb 27 20:56:23 CST 2018];root of context hierarchy
Feb 27, 2018 8:56:32 PM org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitionsINFO: Loading XML bean definitions from class path resource [Beans.xml]
Inside TextEditor constructor.Inside SpellChecker constructor.
Exception in thread "main" java.lang.reflect.InvocationTargetException
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.base/java.lang.reflect.Method.invoke(Unknown Source) at org.springframework.boot.loader.MainMethodRunner.run(MainMethodRunner.java:48)
at org.springframework.boot.loader.Launcher.launch(Launcher.java:87) at org.springframework.boot.loader.Launcher.launch(Launcher.java:50)
at org.springframework.boot.loader.JarLauncher.main(JarLauncher.java:51)
Caused by: java.lang.NullPointerException at com.tutorialspoint.TextEditor.spellCheck(TextEditor.java:22) at com.tutorialspoint.MainApp.main(MainApp.java:10)
... 8 more
I attempted with the #Autowired annotation instead of the #Resource annotation, and it gave the expected result:
Inside TextEditor constructor.
Inside SpellChecker constructor.
Inside checkSpelling.
Would like to see if you can kindly advise / point out mistakes if any, thanks a lot.
(Reference:
https://www.tutorialspoint.com/spring/spring_jsr250_annotations.htm)
[TextEditor.java]
import javax.annotation.Resource;
public class TextEditor {
private SpellChecker spellChecker;
public TextEditor() {
System.out.println("Inside TextEditor constructor.");
}
#Resource(name = "spellChecker")
public void setSpellChecker(SpellChecker spellChecker) {
this.spellChecker = spellChecker;
}
public SpellChecker getSpellChecker() {
return spellChecker;
}
public void spellCheck() {
spellChecker.checkSpelling(); //Gave InvocationTargetException here
}
}
[SpellChecker.java]
public class SpellChecker {
public SpellChecker() {
System.out.println("Inside SpellChecker constructor.");
}
public void checkSpelling() {
System.out.println("Inside checkSpelling.");
}
}
[MainApp.java]
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class MainApp {
public static void main(String[] args) {
ApplicationContext context = new ClassPathXmlApplicationContext("Beans.xml");
TextEditor te = (TextEditor) context.getBean("textEditor");
te.spellCheck();
}
}
[Beans.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"
xsi:schemaLocation = "http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd">
<context:annotation-config/>
<!-- Definition for textEditor bean without constructor-arg -->
<bean id = "textEditor" name = "textEditor" class = "com.tutorialspoint.TextEditor"></bean>
<!-- Definition for spellChecker bean -->
<bean id = "spellChecker" name = "spellChecker" class = "com.tutorialspoint.SpellChecker"></bean>
</beans>
Project Structure:
TestController.java:
package com.mypack;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
/**
* Servlet implementation class Test
*/
#WebServlet("/test")
#Controller
public class TestController extends HttpServlet {
private static final long serialVersionUID = 1L;
#Autowired
private TestManager testManager;
public TestManager getTestManager() {
return testManager;
}
public void setTestManager(TestManager testManager) {
this.testManager = testManager;
}
public TestController() {
super();
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.getWriter().append("Served at: ").append(request.getContextPath());
String name=testManager.getName();
PrintWriter pw=response.getWriter();
pw.write(name);
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
}
}
TestManager.java:
package com.mypack;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Configurable;
import org.springframework.stereotype.Service;
#Service("testManager")
public class TestManager {
#Autowired
private TestDao testDao;
public String getName(){
return testDao.getName();
}
public TestDao getTestDao() {
return testDao;
}
public void setTestDao(TestDao testDao) {
this.testDao = testDao;
}
}
TestDao.java:
package com.mypack;
import org.springframework.stereotype.Repository;
#Repository("testDao")
public class TestDao {
public String getName(){
return "Randhir";
}
}
spring.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"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-2.5.xsd">
<!-- Enable Spring Application Context -->
<context:spring-configured />
<!-- Scan class file in class path for annotated component -> #Component, #Repository, #Service, and #Controller -->
<context:component-scan base-package="com.mypack" />
</beans>
web.xml:
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" id="WebApp_ID" version="3.1">
<display-name>SpringIOCWeb</display-name>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>
/WEB-INF/spring.xml
</param-value>
</context-param>
</web-app>
Server Console:
INFO: 1 Spring WebApplicationInitializers detected on classpath
Jan 21, 2017 7:50:39 PM org.apache.catalina.core.ApplicationContext log
INFO: Initializing Spring root WebApplicationContext
Jan 21, 2017 7:50:39 PM org.springframework.web.context.ContextLoader initWebApplicationContext
INFO: Root WebApplicationContext: initialization started
Jan 21, 2017 7:50:39 PM org.springframework.context.support.AbstractApplicationContext prepareRefresh
INFO: Refreshing Root WebApplicationContext: startup date [Sat Jan 21 19:50:39 IST 2017]; root of context hierarchy
Jan 21, 2017 7:50:39 PM org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
INFO: Loading XML bean definitions from ServletContext resource [/WEB-INF/spring.xml]
Jan 21, 2017 7:50:40 PM org.springframework.web.context.ContextLoader initWebApplicationContext
INFO: Root WebApplicationContext: initialization completed in 731 ms
Jan 21, 2017 7:50:40 PM org.apache.coyote.AbstractProtocol start
INFO: Starting ProtocolHandler ["http-nio-8090"]
Jan 21, 2017 7:50:40 PM org.apache.coyote.AbstractProtocol start
INFO: Starting ProtocolHandler ["ajp-nio-8009"]
Jan 21, 2017 7:50:40 PM org.apache.catalina.startup.Catalina start
INFO: Server startup in 2836 ms
Jan 21, 2017 7:50:45 PM org.apache.catalina.core.StandardWrapperValve invoke
SEVERE: Servlet.service() for servlet [com.mypack.TestController] in context with path [] threw exception
java.lang.NullPointerException
at com.mypack.TestController.doGet(TestController.java:43)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:618)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:725)
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:219)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:106)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:506)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:142)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:79)
at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:610)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:88)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:537)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1081)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:658)
at org.apache.coyote.http11.Http11NioProtocol$Http11ConnectionHandler.process(Http11NioProtocol.java:222)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1566)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.run(NioEndpoint.java:1523)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
at java.lang.Thread.run(Thread.java:724)
IOC Container will instantiate the bean and assign the object reference using setter method. Is my concept is right ?
But here #Autowired doesn't assign the object reference. Till I have used using main method with ApplicationContext and getBean to learn Spring.
But how the bean configuration works with servlet?
Your testManager is null.
You are mixing Servlet and Spring controllers.
You should use Spring dispatcher servlet :
<servlet>
<servlet-name>mvc-dispatcher</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>mvc-dispatcher</servlet-name>
<url-pattern>/spring/*</url-pattern>
</servlet-mapping>
The DispatcherServlet is one unique servlet, like a front controller (in a MVC2 pattern), that dispatches the request to Spring controllers (a spring component).
Then in your controller TestController, remove the inheritance of HttpServlet and override methods (doGet, doPost..), and use #RequestMapping.
In that way you will use the dependency injection of Spring framework.
#Controller
#RequestMapping("/test")
public class TestController {
#Autowired
private TestManager testManager;
#RequestMapping
#ResponseBody
public String handleRequest(final HttpServletRequest request, final HttpServletResponse response) {
String name=testManager.getName();
return name;
}
}
Since you are using servlet and not controller you could autowire it with the code
#WebServlet("/test")
public class TestController extends HttpServlet {
private static final long serialVersionUID = 1L;
private AutowireCapableBeanFactory ctx;
#Autowired
private TestManager testManager;
#Override
public void init() throws ServletException {
super.init();
WebApplicationContext context = WebApplicationContextUtils
.getWebApplicationContext(getServletContext());
ctx = context.getAutowireCapableBeanFactory();
ctx.autowireBean(this);
}
...
}
You already have integrated Spring using its own context listener
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
This is my output it shows that I could not get a constructor from org.hibernate.persister.entity.SingleTableEntityPersister. As far as I can tell it has managed to access the log on to the database. The error starts soon after that.
Jan 21, 2016 9:19:44 PM org.hibernate.Version logVersion
INFO: HHH000412: Hibernate Core {5.0.6.Final}
Jan 21, 2016 9:19:44 PM org.hibernate.cfg.Environment <clinit>
INFO: HHH000206: hibernate.properties not found
Jan 21, 2016 9:19:44 PM org.hibernate.cfg.Environment buildBytecodeProvider
INFO: HHH000021: Bytecode provider name : javassist
Jan 21, 2016 9:19:45 PM org.hibernate.annotations.common.reflection.java.JavaReflectionManager <clinit>
INFO: HCANN000001: Hibernate Commons Annotations {5.0.1.Final}
Jan 21, 2016 9:19:45 PM org.hibernate.boot.jaxb.internal.stax.LocalXmlResourceResolver resolveEntity
WARN: HHH90000012: Recognized obsolete hibernate namespace http://hibernate.sourceforge.net/hibernate-mapping. Use namespace http://www.hibernate.org/dtd/hibernate-mapping instead. Support for obsolete DTD/XSD namespaces may be removed at any time.
Jan 21, 2016 9:19:47 PM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl configure
WARN: HHH10001002: Using Hibernate built-in connection pool (not for production use!)
Jan 21, 2016 9:19:47 PM `enter code here`org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl buildCreator
INFO: HHH10001005: using driver [com.mysql.jdbc.Driver] at URL [jdbc:mysql://localhost:3306/rhs]
Jan 21, 2016 9:19:47 PM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl buildCreator
INFO: HHH10001001: Connection properties: {user=root, password=****}
Jan 21, 2016 9:19:47 PM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl buildCreator
INFO: HHH10001003: Autocommit mode: false
Jan 21, 2016 9:19:47 PM org.hibernate.engine.jdbc.connections.internal.PooledConnections <init>
INFO: HHH000115: Hibernate connection pool size: 20 (min=1)
Jan 21, 2016 9:19:48 PM org.hibernate.dialect.Dialect <init>
INFO: HHH000400: Using dialect: org.hibernate.dialect.MySQL5Dialect
Exception in thread "main" org.hibernate.MappingException: Could not get constructor for org.hibernate.persister.entity.SingleTableEntityPersister
at org.hibernate.persister.internal.PersisterFactoryImpl.createEntityPersister(PersisterFactoryImpl.java:123)
at org.hibernate.persister.internal.PersisterFactoryImpl.createEntityPersister(PersisterFactoryImpl.java:77)
at org.hibernate.internal.SessionFactoryImpl.<init>(SessionFactoryImpl.java:346)
at org.hibernate.boot.internal.SessionFactoryBuilderImpl.build(SessionFactoryBuilderImpl.java:444)
at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:708)
at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:724)
at JavaUtil.main(JavaUtil.java:20)
Caused by: org.hibernate.HibernateException: Unable to instantiate default tuplizer [org.hibernate.tuple.entity.PojoEntityTuplizer]
at org.hibernate.tuple.entity.EntityTuplizerFactory.constructTuplizer(EntityTuplizerFactory.java:91)
at org.hibernate.tuple.entity.EntityTuplizerFactory.constructDefaultTuplizer(EntityTuplizerFactory.java:116)
at org.hibernate.tuple.entity.EntityMetamodel.<init>(EntityMetamodel.java:388)
at org.hibernate.persister.entity.AbstractEntityPersister.<init>(AbstractEntityPersister.java:509)
at org.hibernate.persister.entity.SingleTableEntityPersister.<init>(SingleTableEntityPersister.java:124)
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 org.hibernate.persister.internal.PersisterFactoryImpl.createEntityPersister(PersisterFactoryImpl.java:96)
... 6 more
Caused by: java.lang.reflect.InvocationTargetException
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 org.hibernate.tuple.entity.EntityTuplizerFactory.constructTuplizer(EntityTuplizerFactory.java:88)
... 15 more
Caused by: org.hibernate.PropertyNotFoundException: Could not locate setter method for property [Profession#SALARY]
at org.hibernate.internal.util.ReflectHelper.findSetterMethod(ReflectHelper.java:532)
at org.hibernate.property.access.internal.PropertyAccessBasicImpl.<init>(PropertyAccessBasicImpl.java:44)
at org.hibernate.property.access.internal.PropertyAccessStrategyBasicImpl.buildPropertyAccess(PropertyAccessStrategyBasicImpl.java:27)
at org.hibernate.mapping.Property.getGetter(Property.java:299)
at org.hibernate.tuple.entity.PojoEntityTuplizer.buildPropertyGetter(PojoEntityTuplizer.java:270)
at org.hibernate.tuple.entity.AbstractEntityTuplizer.<init>(AbstractEntityTuplizer.java:145)
at org.hibernate.tuple.entity.PojoEntityTuplizer.<init>(PojoEntityTuplizer.java:63)
... 20 more
This is a simple POJO class
import javax.persistence.*;
public class Profession {
private int EDUCATION;
private int HOURS;
private String JOB_OUTLOOK;
private String JOBTITLE;
private double SALARY;
private String UPWARD_MOBILITY;
public Profession() {
}
public int getEDUCATION() {
return EDUCATION;
}
public void setEDUCATION(int eDUCATION) {
EDUCATION = eDUCATION;
}
public int getHOURS() {
return HOURS;
}
public void setHOURS(int hOURS) {
HOURS = hOURS;
}
public String getJOB_OUTLOOK() {
return JOB_OUTLOOK;
}
public void setJOB_OUTLOOK(String jOB_OUTLOOK) {
JOB_OUTLOOK = jOB_OUTLOOK;
}
public String getJOBTITLE() {
return JOBTITLE;
}
public void setJOBTITLE(String jOBTITLE) {
JOBTITLE = jOBTITLE;
}
public double getSALARY() {
return SALARY;
}
public void setSALRAY(double sALARY) {
SALARY = sALARY;
}
public String getUPWARD_MOBILITY() {
return UPWARD_MOBILITY;
}
public void setUPWARD_MOBILITY(String uPWARD_MOBILITY) {
UPWARD_MOBILITY = uPWARD_MOBILITY;
}
}
This is my main class
import org.hibernate.*;
import org.hibernate.cfg.*;
import java.util.Scanner;
import java.awt.*;
import java.awt.image.*;
import java.io.*;
import javax.imageio.*;
import javax.swing.*;
public class JavaUtil {
public JavaUtil() {
}
public static void main(String[] args) throws IOException {
Configuration cfg = new Configuration();
cfg.configure("hibernate.cfg.xml");
SessionFactory factory = cfg.buildSessionFactory();
Session session = factory.openSession();
Profession p = new Profession();
// closing session
Transaction tx = session.beginTransaction();
session.save(p);
System.out.println("Object saved successfully.....!!");
tx.commit();
session.close();
factory.close();
}
}
This is my hibernate config file
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<!-- Related to the connection START -->
<property name="connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="connection.url">jdbc:mysql://localhost:3306/rhs </property>
<property name="connection.user">root</property>
<property name="connection.password">root</property>
<!-- Related to the connection END -->
<!-- Related to hibernate properties START -->
<property name="show_sql">true </property>
<property name="dialet">org.hibernate.dialect.MySqlDialect </property>
<property name="hbm2ddl.auto">update </property>
<!-- Related to hibernate properties END -->
<!-- Related to mapping START -->
<mapping resource="profession.hbm.xml" />
<!-- Related to the mapping END -->
</session-factory>
</hibernate-configuration>
This is xml mapping
<?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="Profession" table="profession">
<id name="JOBTITLE" column="JOBTITLE" >
<generator class="assigned" />
</id>
<property name="EDUCATION"/>
<property name="HOURS"/>
<property name="JOB_OUTLOOK"/>
<property name="SALARY"/>
<property name="UPWARD_MOBILITY"/>
</class>
</hibernate-mapping>
Please change your property name to follow the POJO rule
public class Profession {
private int education;
private int hours;
private String jobOutlook;
private String jobTitle;
private double salary;
private String upwardMobility;
.....
}
Snapshot of the project structure
Just 2 days into java & spring.
Trying to pull data from mySQL DB using spring in a maven project.
Following a tutorial.
But when the code is run, getting the following error(Only a portion of the error is attached).
All the codes are attached below.
error:
Jul 25, 2015 11:00:15 PM
org.springframework.context.support.AbstractApplicationContext prepareRefresh
INFO: Refreshing
org.springframework.context.support.ClassPathXmlApplicationContext#da2dbb: startup date [Sat Jul 25 23:00:15 IST 2015]; root of context hierarchy
Jul 25, 2015 11:00:15 PM
org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
INFO: Loading XML bean definitions from class path resource [com/caveofprogramming/spring/test/beans/Beans.xml]
Jul 25, 2015 11:00:16 PM
org.springframework.core.io.support.PropertiesLoaderSupport loadProperties
INFO: Loading properties file from class path resource [com/caveofprogramming/spring/props/jdbc.properties]
Jul 25, 2015 11:00:16 PM org.springframework.beans.factory.support.DefaultListableBeanFactory preInstantiateSingletons
INFO: Pre-instantiating singletons in org.springframework.beans.factory.support.DefaultListableBeanFactory#f438e: defining beans [offersDao,org.springframework.context.annotation.internalConfigurationAnnotationProcessor,org.springframework.context.annotation.internalAutowiredAnnotationProcessor,org.springframework.context.annotation.internalRequiredAnnotationProcessor,org.springframework.context.annotation.internalCommonAnnotationProcessor,org.springframework.beans.factory.config.PropertyPlaceholderConfigurer#0,dataSource]; root of factory hierarchy
Jul 25, 2015 11:00:16 PM org.springframework.beans.factory.support.DefaultSingletonBeanRegistry destroySingletons
INFO: Destroying singletons in org.springframework.beans.factory.support.DefaultListableBeanFactory#f438e: defining beans [offersDao,org.springframework.context.annotation.internalConfigurationAnnotationProcessor,org.springframework.context.annotation.internalAutowiredAnnotationProcessor,org.springframework.context.annotation.internalRequiredAnnotationProcessor,org.springframework.context.annotation.internalCommonAnnotationProcessor,org.springframework.beans.factory.config.PropertyPlaceholderConfigurer#0,dataSource]; root of factory hierarchy
Exception in thread "main" org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'offersDao': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire method: public void com.caveofprogramming.spring.test.OffersDAO.setDataSource(javax.sql.DataSource); nested exception is java.lang.NoClassDefFoundError: org/apache/commons/pool/impl/GenericObjectPool
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:285)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1074)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:517)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:456)
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:291)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:222)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:288)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:190)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:580)
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:895)
at
App.java
package com.caveofprogramming.spring.test;
import java.util.List;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class App {
public static void main(String[] args) {
ApplicationContext context = new ClassPathXmlApplicationContext("com/caveofprogramming/spring/test/beans/Beans.xml");
OffersDAO offersDao = (OffersDAO)context.getBean("offersDao");
List<Offer> offers = offersDao.getOffers();
for(Offer offer:offers){
System.out.println(offer);
}
((ClassPathXmlApplicationContext)context).close();
}
}
Offer.java
package com.caveofprogramming.spring.test;
public class Offer {
private String author;
private String title;
public String getAuthor() {
return author;
}
public void setAuthor(String author) {
this.author = author;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
#Override
public String toString() {
return "Offer [author=" + author + ", title=" + title + "]";
}
}
OffersDAO.java
package com.caveofprogramming.spring.test;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;
import javax.sql.DataSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Component;
#Component("offersDao")
public class OffersDAO {
private JdbcTemplate jdbc;
#Autowired
public void setDataSource(DataSource jdbc) {
System.out.println("TESTINGGGGGGGGG in setDataSource");
this.jdbc = new JdbcTemplate(jdbc);
}
public List<Offer> getOffers(){
return jdbc.query("select * from library.book", new RowMapper<Offer>(){
public Offer mapRow(ResultSet rs, int rowNum) throws SQLException {
Offer offer = new Offer();
offer.setTitle(rs.getString("title"));
offer.setAuthor(rs.getString("author"));
return offer;
}});
}
}
jdbc.properties
jdbc.username = root
jdbc.password = 123456
jdbc.driver = com.mysql.jdbc.Driver
jdbc.url = jdbc:mysql://localhost:3306/library
Beans.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:p="http://www.springframework.org/schema/p"
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-3.0.xsd">
<context:component-scan base-package="com.caveofprogramming.spring.test"> </context:component-scan>
<context:property-placeholder
location="com/caveofprogramming/spring/props/jdbc.properties" />
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"
destroy-method="close">
<property name="driverClassName" value="${jdbc.driver}"></property>
<property name="url" value="${jdbc.url}"></property>
<property name="password" value="${jdbc.password}"></property>
<property name="username" value="${jdbc.username}"></property>
</bean>
</beans>
Do ask, if more clarity is needed.
Thanks in advance
Your exception is java.lang.NoClassDefFoundError: org/apache/commons/pool/impl/GenericObjectPool which basically means the required java class is not on the class path.
The problem is due to commons-pool not being in your class path.
Ideally this should be availed when your add the apache tomcat server as a server in your project and doing will get the commons-pool from the server
If this is not the case then kindly add it in the lib folder by downloading it
If it's a maven project then it has it in the pom.xml
commons-pool
commons-pool
1.5.6
I am new in hibernate and i want to do hibernate annotation and auto generate table in mysql as i submit data.but i have some error like sql grammar.please help me to solve this error.my all code is below..
My Jsp File
<html>
<head>
</head>
<body>
<form action="controller" method="post">
Id : <input type="text" name="id"><br>
First-Name : <input type="text" name="fName"><br>
Last-Name : <input type="text" name="lName"><br>
<input type="submit" value="submit">
</form>
</body>
</html>
This is My Pojo Class
package com.connection;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
#Entity
#Table(name = "csl_emp")
public class Employee {
#Id
private int id;
private String firstName, lastName;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
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;
}
}
This is my servler
package com.connection;
import java.io.IOException;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* Servlet implementation class controller
*/
public class controller extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* Default constructor.
*/
public controller() {
}
/**
* #see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
* response)
*/
protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
}
/**
* #see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
* response)
*/
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
System.out.println("in the controller");
String id = request.getParameter("id");
String fname = request.getParameter("fName");
String lname = request.getParameter("lName");
System.out.println(id + fname + lname);
Employee employee = new Employee();
employee.setFirstName(fname);
employee.setLastName(lname);
employee.setId(Integer.parseInt(id));
EmpDao dao = new EmpDao();
dao.addData(employee);
RequestDispatcher requestDispatcher = getServletContext().getRequestDispatcher("/success.jsp");
requestDispatcher.forward(request, response);
}
}
This is mY dao class
package com.connection;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.hibernate.cfg.AnnotationConfiguration;
public class EmpDao {
public void addData(Employee employee) {
Session session = new AnnotationConfiguration().configure().buildSessionFactory().openSession();
Transaction transaction = session.beginTransaction();
session.saveOrUpdate(employee);
transaction.commit();
session.close();
}
}
And This is my Configuration File
<?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>
<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="hibernate.connection.password">root</property>
<property name="hibernate.connection.url">jdbc:mysql://localhost:3306/javadb</property>
<property name="hibernate.connection.username">root</property>
<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
<property name="hbm2ddl.auto">true</property>
<mapping class="com.connection.Employee"/>
</session-factory>
</hibernate-configuration>
And I have getting error like this
Sep 12, 2013 11:49:25 AM org.apache.catalina.core.AprLifecycleListener init
INFO: The APR based Apache Tomcat Native library which allows optimal performance in production environments was not found on the java.library.path: C:\Program Files\java\jdk1.6.0_43\bin;C:\Windows\Sun\Java\bin;C:\Windows\system32;C:\Windows;C:/Program Files/java/jdk1.6.0_43/bin/../jre/bin/server;C:/Program Files/java/jdk1.6.0_43/bin/../jre/bin;C:/Program Files/java/jdk1.6.0_43/bin/../jre/lib/amd64;C:\Windows\System32;C:\Program Files\java\jdk1.6.0_43\bin;C:\Program Files\apache-ant-1.8.4\bin;C:\Program Files (x86)\MySQL\MySQL Server 5.0\bin;D:\eclipse;;.
Sep 12, 2013 11:49:26 AM org.apache.tomcat.util.digester.SetPropertiesRule begin
WARNING: [SetPropertiesRule]{Server/Service/Engine/Host/Context} Setting property 'source' to 'org.eclipse.jst.jee.server:jspcrud' did not find a matching property.
Sep 12, 2013 11:49:26 AM org.apache.tomcat.util.digester.SetPropertiesRule begin
WARNING: [SetPropertiesRule]{Server/Service/Engine/Host/Context} Setting property 'source' to 'org.eclipse.jst.jee.server:Hibernate-J2EE-Annotation' did not find a matching property.
Sep 12, 2013 11:49:27 AM org.apache.coyote.AbstractProtocol init
INFO: Initializing ProtocolHandler ["http-bio-8080"]
Sep 12, 2013 11:49:27 AM org.apache.coyote.AbstractProtocol init
INFO: Initializing ProtocolHandler ["ajp-bio-8009"]
Sep 12, 2013 11:49:27 AM org.apache.catalina.startup.Catalina load
INFO: Initialization processed in 2769 ms
Sep 12, 2013 11:49:27 AM org.apache.catalina.core.StandardService startInternal
INFO: Starting service Catalina
Sep 12, 2013 11:49:27 AM org.apache.catalina.core.StandardEngine startInternal
INFO: Starting Servlet Engine: Apache Tomcat/7.0.40
Sep 12, 2013 11:49:28 AM org.apache.catalina.util.SessionIdGenerator createSecureRandom
INFO: Creation of SecureRandom instance for session ID generation using [SHA1PRNG] took [203] milliseconds.
Sep 12, 2013 11:49:30 AM org.apache.catalina.loader.WebappClassLoader validateJarFile
INFO: validateJarFile(E:\projects\.metadata\.plugins\org.eclipse.wst.server.core\tmp0\wtpwebapps\Hibernate-J2EE-Annotation\WEB-INF\lib\servlet-api-2.4.jar) - jar not loaded. See Servlet Spec 2.3, section 9.7.2. Offending class: javax/servlet/Servlet.class
Sep 12, 2013 11:49:31 AM org.apache.coyote.AbstractProtocol start
INFO: Starting ProtocolHandler ["http-bio-8080"]
Sep 12, 2013 11:49:31 AM org.apache.coyote.AbstractProtocol start
INFO: Starting ProtocolHandler ["ajp-bio-8009"]
Sep 12, 2013 11:49:31 AM org.apache.catalina.startup.Catalina start
INFO: Server startup in 3324 ms
in the controller
1chiragsoni
log4j:WARN No appenders could be found for logger (org.hibernate.cfg.annotations.Version).
log4j:WARN Please initialize the log4j system properly.
Sep 12, 2013 11:49:48 AM org.apache.catalina.core.StandardWrapperValve invoke
SEVERE: Servlet.service() for servlet [controller] in context with path [/Hibernate-J2EE-Annotation] threw exception
org.hibernate.exception.SQLGrammarException: could not retrieve snapshot: [com.connection.Employee#1]
at org.hibernate.exception.SQLStateConverter.convert(SQLStateConverter.java:67)
at org.hibernate.exception.JDBCExceptionHelper.convert(JDBCExceptionHelper.java:43)
at org.hibernate.persister.entity.AbstractEntityPersister.getDatabaseSnapshot(AbstractEntityPersister.java:1039)
at org.hibernate.engine.StatefulPersistenceContext.getDatabaseSnapshot(StatefulPersistenceContext.java:232)
at org.hibernate.engine.ForeignKeys.isTransient(ForeignKeys.java:189)
at org.hibernate.event.def.AbstractSaveEventListener.getEntityState(AbstractSaveEventListener.java:487)
at org.hibernate.event.def.DefaultSaveOrUpdateEventListener.performSaveOrUpdate(DefaultSaveOrUpdateEventListener.java:84)
at org.hibernate.event.def.DefaultSaveOrUpdateEventListener.onSaveOrUpdate(DefaultSaveOrUpdateEventListener.java:70)
at org.hibernate.impl.SessionImpl.fireSaveOrUpdate(SessionImpl.java:507)
at org.hibernate.impl.SessionImpl.saveOrUpdate(SessionImpl.java:499)
at org.hibernate.impl.SessionImpl.saveOrUpdate(SessionImpl.java:495)
at com.connection.EmpDao.addData(EmpDao.java:12)
at com.connection.controller.doPost(controller.java:52)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:647)
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:472)
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:1008)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:589)
at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:312)
at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(ThreadPoolExecutor.java:895)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:918)
at java.lang.Thread.run(Thread.java:662)
Caused by: com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: Table 'test.csl_emp' doesn't exist
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:39)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:27)
at java.lang.reflect.Constructor.newInstance(Constructor.java:513)
at com.mysql.jdbc.Util.handleNewInstance(Util.java:411)
at com.mysql.jdbc.Util.getInstance(Util.java:386)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:1052)
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3609)
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3541)
at com.mysql.jdbc.MysqlIO.sendCommand(MysqlIO.java:2002)
at com.mysql.jdbc.MysqlIO.sqlQueryDirect(MysqlIO.java:2163)
at com.mysql.jdbc.ConnectionImpl.execSQL(ConnectionImpl.java:2624)
at com.mysql.jdbc.PreparedStatement.executeInternal(PreparedStatement.java:2127)
at com.mysql.jdbc.PreparedStatement.executeQuery(PreparedStatement.java:2293)
at org.hibernate.persister.entity.AbstractEntityPersister.getDatabaseSnapshot(AbstractEntityPersister.java:1012)
... 28 more
In your configuration file add this property:
<property name="hibernate.hbm2ddl.auto" value="update" />
and also, very useful are these:
<property name="hibernate.show_sql" value="true" />
<property name="hibernate.format_sql" value="true" />
From Hibernate docs
Change your configuration file property as below
<property name="hibernate.hbm2ddl.auto" value="create"/>
instead of
<property name="hbm2ddl.auto">true</property>